sqlite3 codefirst 适配完成,待测试

This commit is contained in:
28810 2019-01-08 22:19:40 +08:00
parent b339f60777
commit 3d132e4f52
31 changed files with 4596 additions and 45 deletions

View File

@ -0,0 +1,73 @@
using FreeSql.DataAnnotations;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace FreeSql.Tests.Sqlite3 {
public class SqliteDeleteTest {
IDelete<Topic> delete => g.sqlite3.Delete<Topic>(); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
[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.sqlite3.Delete<Topic>().ToSql());
var sql = g.sqlite3.Delete<Topic>(new[] { 1, 2 }).ToSql();
Assert.Equal("DELETE FROM \"tb_topic22211\" WHERE (\"Id\" = 1 OR \"Id\" = 2)", sql);
sql = g.sqlite3.Delete<Topic>(new Topic { Id = 1, Title = "test" }).ToSql();
Assert.Equal("DELETE FROM \"tb_topic22211\" WHERE (\"Id\" = 1)", sql);
sql = g.sqlite3.Delete<Topic>(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.sqlite3.Delete<Topic>(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);
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 items = new List<Topic>();
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() {
}
[Fact]
public void ExecuteAffrows() {
var id = g.sqlite3.Insert<Topic>(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.sqlite3.Insert<Topic>(new Topic { Title = "xxxx", CreateTime = DateTime.Now }).ExecuteInserted();
//Assert.Equal(item[0].Id, delete.Where(a => a.Id == item[0].Id).ExecuteDeleted()[0].Id);
}
}
}

View File

@ -0,0 +1,173 @@
using FreeSql.DataAnnotations;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace FreeSql.Tests.Sqlite3 {
public class SqliteInsertTest {
IInsert<Topic> insert => g.sqlite3.Insert<Topic>(); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
[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 AppendData() {
var items = new List<Topic>();
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<object>();
var sql = insert.AppendData(items.First()).ToSql();
Assert.Equal("INSERT INTO \"tb_topic\"(\"Clicks\", \"Title\", \"CreateTime\") VALUES(:Clicks0, :Title0, :CreateTime0)", sql);
data.Add(insert.AppendData(items.First()).ExecuteIdentity());
sql = insert.AppendData(items).ToSql();
Assert.Equal(@"INSERT ALL
INTO ""tb_topic""(""Clicks"", ""Title"", ""CreateTime"") VALUES(:Clicks0, :Title0, :CreateTime0)
INTO ""tb_topic""(""Clicks"", ""Title"", ""CreateTime"") VALUES(:Clicks1, :Title1, :CreateTime1)
INTO ""tb_topic""(""Clicks"", ""Title"", ""CreateTime"") VALUES(:Clicks2, :Title2, :CreateTime2)
INTO ""tb_topic""(""Clicks"", ""Title"", ""CreateTime"") VALUES(:Clicks3, :Title3, :CreateTime3)
INTO ""tb_topic""(""Clicks"", ""Title"", ""CreateTime"") VALUES(:Clicks4, :Title4, :CreateTime4)
INTO ""tb_topic""(""Clicks"", ""Title"", ""CreateTime"") VALUES(:Clicks5, :Title5, :CreateTime5)
INTO ""tb_topic""(""Clicks"", ""Title"", ""CreateTime"") VALUES(:Clicks6, :Title6, :CreateTime6)
INTO ""tb_topic""(""Clicks"", ""Title"", ""CreateTime"") VALUES(:Clicks7, :Title7, :CreateTime7)
INTO ""tb_topic""(""Clicks"", ""Title"", ""CreateTime"") VALUES(:Clicks8, :Title8, :CreateTime8)
INTO ""tb_topic""(""Clicks"", ""Title"", ""CreateTime"") VALUES(:Clicks9, :Title9, :CreateTime9)
SELECT 1 FROM DUAL", sql);
data.Add(insert.AppendData(items.First()).ExecuteIdentity());
sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql();
Assert.Equal(@"INSERT ALL
INTO ""tb_topic""(""Title"") VALUES(:Title0)
INTO ""tb_topic""(""Title"") VALUES(:Title1)
INTO ""tb_topic""(""Title"") VALUES(:Title2)
INTO ""tb_topic""(""Title"") VALUES(:Title3)
INTO ""tb_topic""(""Title"") VALUES(:Title4)
INTO ""tb_topic""(""Title"") VALUES(:Title5)
INTO ""tb_topic""(""Title"") VALUES(:Title6)
INTO ""tb_topic""(""Title"") VALUES(:Title7)
INTO ""tb_topic""(""Title"") VALUES(:Title8)
INTO ""tb_topic""(""Title"") VALUES(:Title9)
SELECT 1 FROM DUAL", sql);
data.Add(insert.AppendData(items.First()).ExecuteIdentity());
sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql();
Assert.Equal(@"INSERT ALL
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks0, :Title0)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks1, :Title1)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks2, :Title2)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks3, :Title3)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks4, :Title4)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks5, :Title5)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks6, :Title6)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks7, :Title7)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks8, :Title8)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks9, :Title9)
SELECT 1 FROM DUAL", sql);
data.Add(insert.AppendData(items.First()).ExecuteIdentity());
}
[Fact]
public void InsertColumns() {
var items = new List<Topic>();
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<object>();
var sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql();
Assert.Equal(@"INSERT ALL
INTO ""tb_topic""(""Title"") VALUES(:Title0)
INTO ""tb_topic""(""Title"") VALUES(:Title1)
INTO ""tb_topic""(""Title"") VALUES(:Title2)
INTO ""tb_topic""(""Title"") VALUES(:Title3)
INTO ""tb_topic""(""Title"") VALUES(:Title4)
INTO ""tb_topic""(""Title"") VALUES(:Title5)
INTO ""tb_topic""(""Title"") VALUES(:Title6)
INTO ""tb_topic""(""Title"") VALUES(:Title7)
INTO ""tb_topic""(""Title"") VALUES(:Title8)
INTO ""tb_topic""(""Title"") VALUES(:Title9)
SELECT 1 FROM DUAL", sql);
data.Add(insert.AppendData(items.First()).ExecuteIdentity());
sql = insert.AppendData(items).InsertColumns(a =>new { a.Title, a.Clicks }).ToSql();
Assert.Equal(@"INSERT ALL
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks0, :Title0)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks1, :Title1)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks2, :Title2)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks3, :Title3)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks4, :Title4)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks5, :Title5)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks6, :Title6)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks7, :Title7)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks8, :Title8)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks9, :Title9)
SELECT 1 FROM DUAL", sql);
data.Add(insert.AppendData(items.First()).ExecuteIdentity());
}
[Fact]
public void IgnoreColumns() {
var items = new List<Topic>();
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<object>();
var sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql();
Assert.Equal(@"INSERT ALL
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks0, :Title0)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks1, :Title1)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks2, :Title2)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks3, :Title3)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks4, :Title4)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks5, :Title5)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks6, :Title6)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks7, :Title7)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks8, :Title8)
INTO ""tb_topic""(""Clicks"", ""Title"") VALUES(:Clicks9, :Title9)
SELECT 1 FROM DUAL", sql);
data.Add(insert.AppendData(items.First()).ExecuteIdentity());
sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).ToSql();
Assert.Equal(@"INSERT ALL
INTO ""tb_topic""(""Clicks"") VALUES(:Clicks0)
INTO ""tb_topic""(""Clicks"") VALUES(:Clicks1)
INTO ""tb_topic""(""Clicks"") VALUES(:Clicks2)
INTO ""tb_topic""(""Clicks"") VALUES(:Clicks3)
INTO ""tb_topic""(""Clicks"") VALUES(:Clicks4)
INTO ""tb_topic""(""Clicks"") VALUES(:Clicks5)
INTO ""tb_topic""(""Clicks"") VALUES(:Clicks6)
INTO ""tb_topic""(""Clicks"") VALUES(:Clicks7)
INTO ""tb_topic""(""Clicks"") VALUES(:Clicks8)
INTO ""tb_topic""(""Clicks"") VALUES(:Clicks9)
SELECT 1 FROM DUAL", sql);
data.Add(insert.AppendData(items.First()).ExecuteIdentity());
}
[Fact]
public void ExecuteAffrows() {
var items = new List<Topic>();
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<Topic>();
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<Topic>();
//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();
}
}
}

View File

@ -0,0 +1,508 @@
using FreeSql.DataAnnotations;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace FreeSql.Tests.Sqlite3 {
public class SqliteSelectTest {
ISelect<Topic> select => g.sqlite3.Select<Topic>();
[Table(Name = "tb_topic22")]
class Topic {
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public int Clicks { get; set; }
public int TestTypeInfoGuid { 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<TestTypeInfo> Types { get; set; }
}
[Fact]
public void ToList() {
}
[Fact]
public void ToOne() {
}
[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());
}
[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 Caching() {
var result1 = select.Where(a => 1 == 1).Caching(20, "testcaching").ToList();
var testcaching1 = g.sqlite3.Cache.Get("testcaching");
Assert.NotNull(testcaching1);
var result2 = select.Where(a => 1 == 1).Caching(20, "testcaching").ToList();
var testcaching2 = g.sqlite3.Cache.Get("testcaching");
Assert.NotNull(testcaching2);
Assert.Equal(result1.Count, result1.Count);
}
[Fact]
public void From() {
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
var query2 = select.From<TestTypeInfo, TestTypeParentInfo>((s, b, c) => s
.LeftJoin(a => a.TestTypeInfoGuid == b.Guid)
.LeftJoin(a => b.ParentId == c.Id)
);
var sql = query2.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" b ON a.\"TestTypeInfoGuid\" = b.\"Guid\" LEFT JOIN \"TestTypeParentInfo\" c ON b.\"ParentId\" = c.\"Id\"", sql);
query2.ToList();
}
[Fact]
public void LeftJoin() {
//<2F><><EFBFBD><EFBFBD>е<EFBFBD><D0B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>a.Type<70><65>a.Type.Parent <20><><EFBFBD>ǵ<EFBFBD><C7B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
var query = select.LeftJoin(a => a.Type.Guid == a.TestTypeInfoGuid);
var sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", 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.\"TestTypeInfoGuid\"", sql);
query.ToList();
query = select.LeftJoin(a => a.Type.Guid == a.TestTypeInfoGuid && a.Type.Name == "xxx");
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", 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.\"TestTypeInfoGuid\" AND a__Type.\"Name\" = 'xxx'", sql);
query.ToList();
query = select.LeftJoin(a => a.Type.Guid == a.TestTypeInfoGuid && 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.\"TestTypeInfoGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeParentInfo\" a__Type__Parent ON 1 = 1 LEFT JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TestTypeInfoGuid\" AND a__Type.\"Name\" = 'xxx' WHERE (a__Type__Parent.\"Id\" = 10)", sql);
query.ToList();
//<2F><><EFBFBD>û<EFBFBD>е<EFBFBD><D0B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
query = select.LeftJoin<TestTypeInfo>((a, b) => b.Guid == a.TestTypeInfoGuid);
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" b ON b.\"Guid\" = a.\"TestTypeInfoGuid\"", sql);
query.ToList();
query = select.LeftJoin<TestTypeInfo>((a, b) => b.Guid == a.TestTypeInfoGuid && b.Name == "xxx");
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" b ON b.\"Guid\" = a.\"TestTypeInfoGuid\" AND b.\"Name\" = 'xxx'", sql);
query.ToList();
query = select.LeftJoin<TestTypeInfo>((a, b) => b.Guid == a.TestTypeInfoGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10);
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeParentInfo\" b__Parent ON 1 = 1 LEFT JOIN \"TestTypeInfo\" b ON b.\"Guid\" = a.\"TestTypeInfoGuid\" AND b.\"Name\" = 'xxx' WHERE (b__Parent.\"Id\" = 10)", sql);
query.ToList();
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
query = select
.LeftJoin(a => a.Type.Guid == a.TestTypeInfoGuid)
.LeftJoin(a => a.Type.Parent.Id == a.Type.ParentId);
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", 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.\"TestTypeInfoGuid\" LEFT JOIN \"TestTypeParentInfo\" a__Type__Parent ON a__Type__Parent.\"Id\" = a__Type.\"ParentId\"", sql);
query.ToList();
query = select
.LeftJoin<TestTypeInfo>((a, b) => b.Guid == a.TestTypeInfoGuid)
.LeftJoin<TestTypeParentInfo>((a, c) => c.Id == a.Type.ParentId);
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" b ON b.\"Guid\" = a.\"TestTypeInfoGuid\" LEFT JOIN \"TestTypeParentInfo\" c ON c.\"Id\" = b.\"ParentId\"", sql);
query.ToList();
//<2F><><EFBFBD>û<EFBFBD>е<EFBFBD><D0B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>b<EFBFBD><62>c<EFBFBD><63><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ϵ
var query2 = select.From<TestTypeInfo, TestTypeParentInfo>((s, b, c) => s
.LeftJoin(a => a.TestTypeInfoGuid == b.Guid)
.LeftJoin(a => b.ParentId == c.Id));
sql = query2.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" b ON a.\"TestTypeInfoGuid\" = b.\"Guid\" LEFT JOIN \"TestTypeParentInfo\" c ON b.\"ParentId\" = c.\"Id\"", sql);
query2.ToList();
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>϶<EFBFBD><CFB6><EFBFBD><EFBFBD><EFBFBD><E3B2BB>
query = select.LeftJoin("\"TestTypeInfo\" b on b.\"Guid\" = a.\"TestTypeInfoGuid\"");
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" b on b.\"Guid\" = a.\"TestTypeInfoGuid\"", sql);
query.ToList();
query = select.LeftJoin("\"TestTypeInfo\" b on b.\"Guid\" = a.\"TestTypeInfoGuid\" and b.\"Name\" = :bname", new { bname = "xxx" });
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" b on b.\"Guid\" = a.\"TestTypeInfoGuid\" and b.\"Name\" = :bname", sql);
query.ToList();
}
[Fact]
public void InnerJoin() {
//<2F><><EFBFBD><EFBFBD>е<EFBFBD><D0B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>a.Type<70><65>a.Type.Parent <20><><EFBFBD>ǵ<EFBFBD><C7B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
var query = select.InnerJoin(a => a.Type.Guid == a.TestTypeInfoGuid);
var sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", 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.\"TestTypeInfoGuid\"", sql);
query.ToList();
query = select.InnerJoin(a => a.Type.Guid == a.TestTypeInfoGuid && a.Type.Name == "xxx");
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", 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.\"TestTypeInfoGuid\" AND a__Type.\"Name\" = 'xxx'", sql);
query.ToList();
query = select.InnerJoin(a => a.Type.Guid == a.TestTypeInfoGuid && 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.\"TestTypeInfoGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeParentInfo\" a__Type__Parent ON 1 = 1 INNER JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TestTypeInfoGuid\" AND a__Type.\"Name\" = 'xxx' WHERE (a__Type__Parent.\"Id\" = 10)", sql);
query.ToList();
//<2F><><EFBFBD>û<EFBFBD>е<EFBFBD><D0B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
query = select.InnerJoin<TestTypeInfo>((a, b) => b.Guid == a.TestTypeInfoGuid);
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" b ON b.\"Guid\" = a.\"TestTypeInfoGuid\"", sql);
query.ToList();
query = select.InnerJoin<TestTypeInfo>((a, b) => b.Guid == a.TestTypeInfoGuid && b.Name == "xxx");
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" b ON b.\"Guid\" = a.\"TestTypeInfoGuid\" AND b.\"Name\" = 'xxx'", sql);
query.ToList();
query = select.InnerJoin<TestTypeInfo>((a, b) => b.Guid == a.TestTypeInfoGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10);
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeParentInfo\" b__Parent ON 1 = 1 INNER JOIN \"TestTypeInfo\" b ON b.\"Guid\" = a.\"TestTypeInfoGuid\" AND b.\"Name\" = 'xxx' WHERE (b__Parent.\"Id\" = 10)", sql);
query.ToList();
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
query = select
.InnerJoin(a => a.Type.Guid == a.TestTypeInfoGuid)
.InnerJoin(a => a.Type.Parent.Id == a.Type.ParentId);
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", 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.\"TestTypeInfoGuid\" INNER JOIN \"TestTypeParentInfo\" a__Type__Parent ON a__Type__Parent.\"Id\" = a__Type.\"ParentId\"", sql);
query.ToList();
query = select
.InnerJoin<TestTypeInfo>((a, b) => b.Guid == a.TestTypeInfoGuid)
.InnerJoin<TestTypeParentInfo>((a, c) => c.Id == a.Type.ParentId);
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" b ON b.\"Guid\" = a.\"TestTypeInfoGuid\" INNER JOIN \"TestTypeParentInfo\" c ON c.\"Id\" = b.\"ParentId\"", sql);
query.ToList();
//<2F><><EFBFBD>û<EFBFBD>е<EFBFBD><D0B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>b<EFBFBD><62>c<EFBFBD><63><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ϵ
var query2 = select.From<TestTypeInfo, TestTypeParentInfo>((s, b, c) => s
.InnerJoin(a => a.TestTypeInfoGuid == b.Guid)
.InnerJoin(a => b.ParentId == c.Id));
sql = query2.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" b ON a.\"TestTypeInfoGuid\" = b.\"Guid\" INNER JOIN \"TestTypeParentInfo\" c ON b.\"ParentId\" = c.\"Id\"", sql);
query2.ToList();
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>϶<EFBFBD><CFB6><EFBFBD><EFBFBD><EFBFBD><E3B2BB>
query = select.InnerJoin("\"TestTypeInfo\" b on b.\"Guid\" = a.\"TestTypeInfoGuid\"");
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" b on b.\"Guid\" = a.\"TestTypeInfoGuid\"", sql);
query.ToList();
query = select.InnerJoin("\"TestTypeInfo\" b on b.\"Guid\" = a.\"TestTypeInfoGuid\" and b.\"Name\" = :bname", new { bname = "xxx" });
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" b on b.\"Guid\" = a.\"TestTypeInfoGuid\" and b.\"Name\" = :bname", sql);
query.ToList();
}
[Fact]
public void RightJoin() {
//<2F><><EFBFBD><EFBFBD>е<EFBFBD><D0B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>a.Type<70><65>a.Type.Parent <20><><EFBFBD>ǵ<EFBFBD><C7B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
var query = select.RightJoin(a => a.Type.Guid == a.TestTypeInfoGuid);
var sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", 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.\"TestTypeInfoGuid\"", sql);
query.ToList();
query = select.RightJoin(a => a.Type.Guid == a.TestTypeInfoGuid && a.Type.Name == "xxx");
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", 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.\"TestTypeInfoGuid\" AND a__Type.\"Name\" = 'xxx'", sql);
query.ToList();
query = select.RightJoin(a => a.Type.Guid == a.TestTypeInfoGuid && 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.\"TestTypeInfoGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeParentInfo\" a__Type__Parent ON 1 = 1 RIGHT JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TestTypeInfoGuid\" AND a__Type.\"Name\" = 'xxx' WHERE (a__Type__Parent.\"Id\" = 10)", sql);
query.ToList();
//<2F><><EFBFBD>û<EFBFBD>е<EFBFBD><D0B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
query = select.RightJoin<TestTypeInfo>((a, b) => b.Guid == a.TestTypeInfoGuid);
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a RIGHT JOIN \"TestTypeInfo\" b ON b.\"Guid\" = a.\"TestTypeInfoGuid\"", sql);
query.ToList();
query = select.RightJoin<TestTypeInfo>((a, b) => b.Guid == a.TestTypeInfoGuid && b.Name == "xxx");
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a RIGHT JOIN \"TestTypeInfo\" b ON b.\"Guid\" = a.\"TestTypeInfoGuid\" AND b.\"Name\" = 'xxx'", sql);
query.ToList();
query = select.RightJoin<TestTypeInfo>((a, b) => b.Guid == a.TestTypeInfoGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10);
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeParentInfo\" b__Parent ON 1 = 1 RIGHT JOIN \"TestTypeInfo\" b ON b.\"Guid\" = a.\"TestTypeInfoGuid\" AND b.\"Name\" = 'xxx' WHERE (b__Parent.\"Id\" = 10)", sql);
query.ToList();
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
query = select
.RightJoin(a => a.Type.Guid == a.TestTypeInfoGuid)
.RightJoin(a => a.Type.Parent.Id == a.Type.ParentId);
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", 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.\"TestTypeInfoGuid\" RIGHT JOIN \"TestTypeParentInfo\" a__Type__Parent ON a__Type__Parent.\"Id\" = a__Type.\"ParentId\"", sql);
query.ToList();
query = select
.RightJoin<TestTypeInfo>((a, b) => b.Guid == a.TestTypeInfoGuid)
.RightJoin<TestTypeParentInfo>((a, c) => c.Id == a.Type.ParentId);
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a RIGHT JOIN \"TestTypeInfo\" b ON b.\"Guid\" = a.\"TestTypeInfoGuid\" RIGHT JOIN \"TestTypeParentInfo\" c ON c.\"Id\" = b.\"ParentId\"", sql);
query.ToList();
//<2F><><EFBFBD>û<EFBFBD>е<EFBFBD><D0B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>b<EFBFBD><62>c<EFBFBD><63><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ϵ
var query2 = select.From<TestTypeInfo, TestTypeParentInfo>((s, b, c) => s
.RightJoin(a => a.TestTypeInfoGuid == b.Guid)
.RightJoin(a => b.ParentId == c.Id));
sql = query2.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a RIGHT JOIN \"TestTypeInfo\" b ON a.\"TestTypeInfoGuid\" = b.\"Guid\" RIGHT JOIN \"TestTypeParentInfo\" c ON b.\"ParentId\" = c.\"Id\"", sql);
query2.ToList();
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>϶<EFBFBD><CFB6><EFBFBD><EFBFBD><EFBFBD><E3B2BB>
query = select.RightJoin("\"TestTypeInfo\" b on b.\"Guid\" = a.\"TestTypeInfoGuid\"");
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a RIGHT JOIN \"TestTypeInfo\" b on b.\"Guid\" = a.\"TestTypeInfoGuid\"", sql);
query.ToList();
query = select.RightJoin("\"TestTypeInfo\" b on b.\"Guid\" = a.\"TestTypeInfoGuid\" and b.\"Name\" = :bname", new { bname = "xxx" });
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a RIGHT JOIN \"TestTypeInfo\" b on b.\"Guid\" = a.\"TestTypeInfoGuid\" and b.\"Name\" = :bname", sql);
query.ToList();
}
[Fact]
public void Where() {
//<2F><><EFBFBD><EFBFBD>е<EFBFBD><D0B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>a.Type<70><65>a.Type.Parent <20><><EFBFBD>ǵ<EFBFBD><C7B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
var query = select.Where(a => a.Id == 10);
var sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", 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.\"TestTypeInfoGuid\", 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.\"TestTypeInfoGuid\", 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.\"TestTypeInfoGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a, \"TestTypeInfo\" a__Type WHERE (a__Type.\"Name\" = 'typeTitle')", sql);
query.ToList();
query = select.Where(a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TestTypeInfoGuid);
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a, \"TestTypeInfo\" a__Type WHERE (a__Type.\"Name\" = 'typeTitle' AND a__Type.\"Guid\" = a.\"TestTypeInfoGuid\")", 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.\"TestTypeInfoGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a, \"TestTypeInfo\" a__Type, \"TestTypeParentInfo\" a__Type__Parent WHERE (a__Type__Parent.\"Name\" = 'tparent')", sql);
query.ToList();
//<2F><><EFBFBD>û<EFBFBD>е<EFBFBD><D0B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ԣ<EFBFBD><D4A3>򵥶<EFBFBD><F2B5A5B6><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
query = select.Where<TestTypeInfo>((a, b) => b.Guid == a.TestTypeInfoGuid && b.Name == "typeTitle");
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a, \"TestTypeInfo\" b WHERE (b.\"Guid\" = a.\"TestTypeInfoGuid\" AND b.\"Name\" = 'typeTitle')", sql);
query.ToList();
query = select.Where<TestTypeInfo>((a, b) => b.Name == "typeTitle" && b.Guid == a.TestTypeInfoGuid);
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a, \"TestTypeInfo\" b WHERE (b.\"Name\" = 'typeTitle' AND b.\"Guid\" = a.\"TestTypeInfoGuid\")", sql);
query.ToList();
query = select.Where<TestTypeInfo, TestTypeParentInfo>((a, b, c) => c.Name == "tparent");
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a, \"TestTypeParentInfo\" c WHERE (c.\"Name\" = 'tparent')", sql);
query.ToList();
//<2F><><EFBFBD><EFBFBD>һ<EFBFBD><D2BB> From <20><>Ķ<EFBFBD><C4B6><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
var query2 = select.From<TestTypeInfo, TestTypeParentInfo>((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.\"TestTypeInfoGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a, \"TestTypeParentInfo\" c, \"TestTypeInfo\" b WHERE (a.\"Id\" = 10 AND c.\"Name\" = 'xxx') AND (b.\"ParentId\" = 20)", sql);
query2.ToList();
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>϶<EFBFBD><CFB6><EFBFBD><EFBFBD><EFBFBD><E3B2BB>
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.\"TestTypeInfoGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a WHERE (a.\"Clicks\" > 100 and a.\"Id\" = :id)", sql);
query.ToList();
}
[Fact]
public void WhereIf() {
//<2F><><EFBFBD><EFBFBD>е<EFBFBD><D0B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>a.Type<70><65>a.Type.Parent <20><><EFBFBD>ǵ<EFBFBD><C7B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
var query = select.WhereIf(true, a => a.Id == 10);
var sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", 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.\"TestTypeInfoGuid\", 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.\"TestTypeInfoGuid\", 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.\"TestTypeInfoGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a, \"TestTypeInfo\" a__Type WHERE (a__Type.\"Name\" = 'typeTitle')", sql);
query.ToList();
query = select.WhereIf(true, a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TestTypeInfoGuid);
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a, \"TestTypeInfo\" a__Type WHERE (a__Type.\"Name\" = 'typeTitle' AND a__Type.\"Guid\" = a.\"TestTypeInfoGuid\")", 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.\"TestTypeInfoGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a, \"TestTypeInfo\" a__Type, \"TestTypeParentInfo\" a__Type__Parent WHERE (a__Type__Parent.\"Name\" = 'tparent')", sql);
query.ToList();
//<2F><><EFBFBD><EFBFBD>һ<EFBFBD><D2BB> From <20><>Ķ<EFBFBD><C4B6><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
var query2 = select.From<TestTypeInfo, TestTypeParentInfo>((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.\"TestTypeInfoGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a, \"TestTypeParentInfo\" c, \"TestTypeInfo\" b WHERE (a.\"Id\" = 10 AND c.\"Name\" = 'xxx') AND (b.\"ParentId\" = 20)", sql);
query2.ToList();
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>϶<EFBFBD><CFB6><EFBFBD><EFBFBD><EFBFBD><E3B2BB>
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.\"TestTypeInfoGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a WHERE (a.\"Clicks\" > 100 and a.\"Id\" = :id)", sql);
query.ToList();
// ==========================================WhereIf(false)
//<2F><><EFBFBD><EFBFBD>е<EFBFBD><D0B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>a.Type<70><65>a.Type.Parent <20><><EFBFBD>ǵ<EFBFBD><C7B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
query = select.WhereIf(false, a => a.Id == 10);
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", 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.\"TestTypeInfoGuid\", 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.\"TestTypeInfoGuid\", 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.\"TestTypeInfoGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a", sql);
query.ToList();
query = select.WhereIf(false, a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TestTypeInfoGuid);
sql = query.ToSql().Replace("\r\n", "");
Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TestTypeInfoGuid\", 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.\"TestTypeInfoGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a", sql);
query.ToList();
//<2F><><EFBFBD><EFBFBD>һ<EFBFBD><D2BB> From <20><>Ķ<EFBFBD><C4B6><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
query2 = select.From<TestTypeInfo, TestTypeParentInfo>((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.\"TestTypeInfoGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a", sql);
query2.ToList();
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>϶<EFBFBD><CFB6><EFBFBD><EFBFBD><EFBFBD><E3B2BB>
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.\"TestTypeInfoGuid\", 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<TestTypeInfo, TestTypeParentInfo>((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())
.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)")
});
}
[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() {
}
[Fact]
public void Skip_Offset() {
}
[Fact]
public void Take_Limit() {
}
[Fact]
public void Page() {
}
[Fact]
public void Sum() {
}
[Fact]
public void Min() {
}
[Fact]
public void Max() {
}
[Fact]
public void Avg() {
}
[Fact]
public void As() {
}
}
}

View File

@ -0,0 +1,107 @@
using FreeSql.DataAnnotations;
using System;
using System.Collections.Generic;
using Xunit;
namespace FreeSql.Tests.Sqlite3 {
public class SqliteUpdateTest {
IUpdate<Topic> update => g.sqlite3.Update<Topic>();
[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.sqlite3.Update<Topic>().ToSql());
Assert.Equal("UPDATE \"tb_topic\" SET title='test' \r\nWHERE (\"Id\" = 1 OR \"Id\" = 2)", g.sqlite3.Update<Topic>(new[] { 1, 2 }).SetRaw("title='test'").ToSql());
Assert.Equal("UPDATE \"tb_topic\" SET title='test1' \r\nWHERE (\"Id\" = 1)", g.sqlite3.Update<Topic>(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.sqlite3.Update<Topic>(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.sqlite3.Update<Topic>(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);
var items = new List<Topic>();
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).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);
}
[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 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.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.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\" = nvl(\"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);
}
[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);
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<Topic>();
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 ExecuteUpdated() {
}
}
}

View File

@ -0,0 +1,54 @@
using FreeSql.DataAnnotations;
using System;
using Xunit;
namespace FreeSql.Tests.Sqlite3 {
public class SqliteAdoTest {
[Fact]
public void Pool() {
var t1 = g.sqlite3.Ado.MasterPool.StatisticsFullily;
}
[Fact]
public void SlavePools() {
var t2 = g.sqlite3.Ado.SlavePools.Count;
}
[Fact]
public void IsTracePerformance() {
Assert.True(g.sqlite3.Ado.IsTracePerformance);
}
[Fact]
public void ExecuteReader() {
}
[Fact]
public void ExecuteArray() {
}
[Fact]
public void ExecuteNonQuery() {
}
[Fact]
public void ExecuteScalar() {
}
[Fact]
public void Query() {
var t3 = g.sqlite3.Ado.Query<xxx>("select * from \"song\"");
var t4 = g.sqlite3.Ado.Query<(int, string, string)>("select * from \"song\"");
var t5 = g.sqlite3.Ado.Query<dynamic>("select * from \"song\"");
}
class xxx {
public int Id { get; set; }
public string Path { get; set; }
public string Title2 { get; set; }
}
}
}

View File

@ -0,0 +1,194 @@
using FreeSql.DataAnnotations;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
namespace FreeSql.Tests.Sqlite3 {
public class SqliteCodeFirstTest {
[Fact]
public void AddField() {
var sql = g.sqlite3.CodeFirst.GetComparisonDDLStatements<TopicAddField>();
var id = g.sqlite3.Insert<TopicAddField>().AppendData(new TopicAddField { }).ExecuteIdentity();
//var inserted = g.sqlite3.Insert<TopicAddField>().AppendData(new TopicAddField { }).ExecuteInserted();
}
[Table(Name = "xxxtb.TopicAddField", OldName = "TopicAddField")]
public class TopicAddField {
[Column(IsIdentity = true)]
public int Id { get; set; }
public string name { get; set; }
[Column(DbType = "varchar(200) not null", OldName = "title2")]
public string title3223 { get; set; } = "10";
}
[Fact]
public void GetComparisonDDLStatements() {
var sql = g.sqlite3.CodeFirst.GetComparisonDDLStatements<TableAllType>();
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,
`Short` SMALLINT(6) NOT NULL,
`Int` INT(11) NOT NULL,
`Long` BIGINT(20) NOT NULL,
`Byte` TINYINT(3) UNSIGNED NOT NULL,
`UShort` SMALLINT(5) UNSIGNED NOT NULL,
`UInt` INT(10) UNSIGNED NOT NULL,
`ULong` BIGINT(20) UNSIGNED NOT NULL,
`Double` DOUBLE NOT NULL,
`Float` FLOAT NOT NULL,
`Decimal` DECIMAL(10,2) NOT NULL,
`TimeSpan` TIME NOT NULL,
`DateTime` DATETIME NOT NULL,
`Bytes` VARBINARY(255),
`String` VARCHAR(255),
`Guid` VARCHAR(36),
`BoolNullable` BIT(1),
`SByteNullable` TINYINT(3),
`ShortNullable` SMALLINT(6),
`IntNullable` INT(11),
`testFielLongNullable` BIGINT(20),
`ByteNullable` TINYINT(3) UNSIGNED,
`UShortNullable` SMALLINT(5) UNSIGNED,
`UIntNullable` INT(10) UNSIGNED,
`ULongNullable` BIGINT(20) UNSIGNED,
`DoubleNullable` DOUBLE,
`FloatNullable` FLOAT,
`DecimalNullable` DECIMAL(10,2),
`TimeSpanNullable` TIME,
`DateTimeNullable` DATETIME,
`GuidNullable` VARCHAR(36),
`Point` POINT,
`LineString` LINESTRING,
`Polygon` POLYGON,
`MultiPoint` MULTIPOINT,
`MultiLineString` MULTILINESTRING,
`MultiPolygon` MULTIPOLYGON,
`Enum1` ENUM('E1','E2','E3') NOT NULL,
`Enum1Nullable` ENUM('E1','E2','E3'),
`Enum2` SET('F1','F2','F3') NOT NULL,
`Enum2Nullable` SET('F1','F2','F3'),
PRIMARY KEY (`Id`)
) Engine=InnoDB CHARACTER SET utf8;
", sql);
}
//sql = g.sqlite3.CodeFirst.GetComparisonDDLStatements<Tb_alltype>();
}
IInsert<TableAllType> insert => g.sqlite3.Insert<TableAllType>();
ISelect<TableAllType> select => g.sqlite3.Select<TableAllType>();
[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 {
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();
}
[Table(Name = "tb_alltype")]
class TableAllType {
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
//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? 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 enum TableAllTypeEnumType1 { e1, e2, e3, e5 }
[Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 }
}
}

View File

@ -0,0 +1,114 @@
using FreeSql.DataAnnotations;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace FreeSql.Tests.Sqlite3Expression {
public class ConvertTest {
ISelect<Topic> select => g.sqlite3.Select<Topic>();
[Table(Name = "tb_topic")]
class Topic {
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public int Clicks { get; set; }
public int TestTypeInfoGuid { 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<TestTypeInfo> Types { get; set; }
}
[Fact]
public void ToBoolean() {
//var data = new List<object>();
//data.Add(select.Where(a => (Convert.ToBoolean(a.Clicks) ? 1 : 2) > 0).ToList());
//SELECT a.`Id`, a.`Clicks`, a.`TestTypeInfoGuid`, a.`Title`, a.`CreateTime`
//FROM `tb_topic` a
//WHERE ((a.`Clicks` not in ('0','false')))
}
[Fact]
public void ToByte() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToByte(a.Clicks) > 0).ToList());
}
[Fact]
public void ToChar() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToChar(a.Clicks) == 'a').ToList());
}
[Fact]
public void ToDateTime() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToDateTime(a.CreateTime.ToString()).Year > 0).ToList());
}
[Fact]
public void ToDecimal() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToDecimal(a.Clicks) > 0).ToList());
}
[Fact]
public void ToDouble() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToDouble(a.Clicks) > 0).ToList());
}
[Fact]
public void ToInt16() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToInt16(a.Clicks) > 0).ToList());
}
[Fact]
public void ToInt32() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToInt32(a.Clicks) > 0).ToList());
}
[Fact]
public void ToInt64() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToInt64(a.Clicks) > 0).ToList());
}
[Fact]
public void ToSByte() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToSByte(a.Clicks) > 0).ToList());
}
[Fact]
public void ToSingle() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToSingle(a.Clicks) > 0).ToList());
}
[Fact]
public void this_ToString() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToString(a.Clicks).Equals("")).ToList());
}
[Fact]
public void ToUInt16() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToUInt16(a.Clicks) > 0).ToList());
}
[Fact]
public void ToUInt32() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToUInt32(a.Clicks) > 0).ToList());
}
[Fact]
public void ToUInt64() {
var data = new List<object>();
data.Add(select.Where(a => Convert.ToUInt64(a.Clicks) > 0).ToList());
}
}
}

View File

@ -0,0 +1,622 @@
using FreeSql.DataAnnotations;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace FreeSql.Tests.Sqlite3Expression {
public class DateTimeTest {
ISelect<Topic> select => g.sqlite3.Select<Topic>();
[Table(Name = "tb_topic111333")]
class Topic {
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public int Clicks { get; set; }
public int TestTypeInfoGuid { get; set; }
public TestTypeInfo Type { get; set; }
public string Title { get; set; }
public DateTime CreateTime { get; set; }
}
[Table(Name = "TestTypeInfo333")]
class TestTypeInfo {
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<TestTypeInfo> Types { get; set; }
public DateTime Time2 { get; set; }
}
[Fact]
public void Now() {
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.Date == DateTime.Now.Date).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` 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<object>();
data.Add(select.Where(a => a.CreateTime.Date == DateTime.UtcNow.Date).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` 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<object>();
data.Add(select.Where(a => a.CreateTime.Date == DateTime.MinValue.Date).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` 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<object>();
data.Add(select.Where(a => a.CreateTime.Date == DateTime.MaxValue.Date).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` 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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic111333` a
//WHERE (((a.`CreateTime`) - (now())) = 0);
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`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.`TestTypeInfoGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`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())
}
}
}

View File

@ -0,0 +1,132 @@
using FreeSql.DataAnnotations;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace FreeSql.Tests.Sqlite3Expression {
public class MathTest {
ISelect<Topic> select => g.sqlite3.Select<Topic>();
[Table(Name = "tb_topic")]
class Topic {
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public int Clicks { get; set; }
public int TestTypeInfoGuid { 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<TestTypeInfo> Types { get; set; }
}
[Fact]
public void PI() {
var data = new List<object>();
data.Add(select.Where(a => Math.PI + a.Clicks > 0).ToList());
}
[Fact]
public void Abs() {
var data = new List<object>();
data.Add(select.Where(a => Math.Abs(-a.Clicks) > 0).ToList());
}
[Fact]
public void Sign() {
var data = new List<object>();
data.Add(select.Where(a => Math.Sign(-a.Clicks) > 0).ToList());
}
[Fact]
public void Floor() {
var data = new List<object>();
data.Add(select.Where(a => Math.Floor(a.Clicks + 0.5) == a.Clicks).ToList());
}
[Fact]
public void Ceiling() {
var data = new List<object>();
data.Add(select.Where(a => Math.Ceiling(a.Clicks + 0.5) == a.Clicks + 1).ToList());
}
[Fact]
public void Round() {
var data = new List<object>();
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<object>();
data.Add(select.Where(a => Math.Exp(1) == a.Clicks + 1).ToList());
}
[Fact]
public void Log() {
var data = new List<object>();
data.Add(select.Where(a => Math.Log(a.Clicks + 0.5) == a.Clicks + 1).ToList());
}
[Fact]
public void Log10() {
var data = new List<object>();
data.Add(select.Where(a => Math.Log10(a.Clicks + 0.5) == a.Clicks + 1).ToList());
}
[Fact]
public void Pow() {
var data = new List<object>();
data.Add(select.Where(a => Math.Pow(2, a.Clicks % 5) == a.Clicks + 1).ToList());
}
[Fact]
public void Sqrt() {
var data = new List<object>();
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<object>();
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<object>();
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<object>();
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<object>();
//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<object>();
//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<object>();
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<object>();
//data.Add(select.Where(a => Math.Atan2(2, a.Clicks) == a.Clicks + 1).ToList());
}
[Fact]
public void Truncate() {
var data = new List<object>();
data.Add(select.Where(a => Math.Truncate(a.Clicks * 1.0 / 3) == a.Clicks + 1).ToList());
}
}
}

View File

@ -0,0 +1,80 @@
using FreeSql.DataAnnotations;
using System;
using System.Linq;
using Xunit;
namespace FreeSql.Tests.Sqlite3Expression {
public class OtherTest {
ISelect<TableAllType> select => g.sqlite3.Select<TableAllType>();
public OtherTest() {
}
[Fact]
public void Array() {
//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();
}
[Table(Name = "tb_alltype")]
class TableAllType {
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
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? 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 enum TableAllTypeEnumType1 { e1, e2, e3, e5 }
[Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 }
}
}

View File

@ -0,0 +1,683 @@
using FreeSql.DataAnnotations;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace FreeSql.Tests.Sqlite3Expression {
public class StringTest {
ISelect<Topic> select => g.sqlite3.Select<Topic>();
[Table(Name = "tb_topic")]
class Topic {
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public int Clicks { get; set; }
public int TestTypeInfoGuid { 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<TestTypeInfo> Types { get; set; }
}
[Fact]
public void Empty() {
var data = new List<object>();
data.Add(select.Where(a => (a.Title ?? "") == string.Empty).ToSql());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (ifnull(a.`Title`, '') = '')
}
[Fact]
public void StartsWith() {
var list = new List<object>();
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.`TestTypeInfoGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE((a.`Title`) LIKE '%aaa')
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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<object>();
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.`TestTypeInfoGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE((a.`Title`) LIKE 'aaa%')
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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<object>();
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.`TestTypeInfoGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE((a.`Title`) LIKE '%aaa%')
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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<object>();
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.`TestTypeInfoGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE(lower(a.`Title`) = 'aaa');
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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<object>();
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.`TestTypeInfoGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (upper(a.`Title`) = 'aaa');
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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<object>();
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.`TestTypeInfoGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (trim(a.`Title`) = 'aaa');
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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<object>();
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.`TestTypeInfoGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (ltrim(a.`Title`) = 'aaa');
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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<object>();
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.`TestTypeInfoGuid` as3, a.`Title` as4, a.`CreateTime` as5
//FROM `tb_topic` a
//WHERE (rtrim(a.`Title`) = 'aaa');
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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<object>();
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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` 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.`TestTypeInfoGuid` as3, a__Type.`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<object>();
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());
}
}
}

View File

@ -0,0 +1,260 @@
using FreeSql.DataAnnotations;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace FreeSql.Tests.Sqlite3Expression {
public class TimeSpanTest {
ISelect<Topic> select => g.sqlite3.Select<Topic>();
[Table(Name = "tb_topic")]
class Topic {
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public int Clicks { get; set; }
public int TestTypeInfoGuid { 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<TestTypeInfo> Types { get; set; }
}
[Fact]
public void Zero() {
var data = new List<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.Zero).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, 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<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.MinValue).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, 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<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay < TimeSpan.MaxValue).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, 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<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Days == 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, 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<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Hours > 0).ToSql());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, 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<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Milliseconds > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, 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<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Minutes > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, 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<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Seconds > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, 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<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Ticks > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, 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<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalDays > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, 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<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalHours > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, 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<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMilliseconds > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, 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<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMinutes > 0).ToSql());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, 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<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalSeconds > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, 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<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Add(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, 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<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Subtract(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, 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<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.CompareTo(TimeSpan.FromDays(1)) > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, 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<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.Equals(TimeSpan.FromDays(1))).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, 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<object>();
data.Add(select.Where(a => a.CreateTime.TimeOfDay.ToString() == "ssss").ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` 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<object>();
data.Add(select.Where(a => TimeSpan.Compare(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1)) > 0).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, 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<object>();
data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, 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<object>();
data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, 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<object>();
data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromHours(1))).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, 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<object>();
data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMilliseconds(1))).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, 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<object>();
data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMinutes(1))).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, 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<object>();
data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromSeconds(1))).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, 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<object>();
data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromTicks(1))).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` as3, a.`Title` as4, 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<object>();
data.Add(select.Where(a => TimeSpan.Parse(a.CreateTime.TimeOfDay.ToString()) > TimeSpan.Zero).ToList());
//SELECT a.`Id` as1, a.`Clicks` as2, a.`TestTypeInfoGuid` 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)
}
}
}

View File

@ -33,4 +33,9 @@ public class g {
.UseConnectionString(FreeSql.DataType.Oracle, "user id=user1;password=123456;data source=//127.0.0.1:1521/XE;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")
.UseAutoSyncStructure(true) .UseAutoSyncStructure(true)
.Build(); .Build();
public static IFreeSql sqlite3 = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite3, @"Data Source=|DataDirectory|\document.db;Attachs=xxxtb.db;Pooling=true;Max Pool Size=10")
.UseAutoSyncStructure(true)
.Build();
} }

View File

@ -32,6 +32,14 @@
/// <returns></returns> /// <returns></returns>
public static string FormatOracleSQL(this string that, params object[] args) => _oracleAdo.Addslashes(that, args); public static string FormatOracleSQL(this string that, params object[] args) => _oracleAdo.Addslashes(that, args);
static FreeSql.Oracle.OracleAdo _oracleAdo = new FreeSql.Oracle.OracleAdo(); static FreeSql.Oracle.OracleAdo _oracleAdo = new FreeSql.Oracle.OracleAdo();
/// <summary>
/// 特殊处理类似 string.Format 的使用方法,防止注入,以及 IS NULL 转换
/// </summary>
/// <param name="that"></param>
/// <param name="args"></param>
/// <returns></returns>
public static string FormatSqlite (this string that, params object[] args) => _sqliteAdo.Addslashes(that, args);
static FreeSql.Sqlite3.SqliteAdo _sqliteAdo = new FreeSql.Sqlite3.SqliteAdo();
} }
namespace System.Runtime.CompilerServices { namespace System.Runtime.CompilerServices {

View File

@ -11,11 +11,11 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="CS-Script.Core" Version="1.0.5" /> <PackageReference Include="CS-Script.Core" Version="1.0.6" />
<PackageReference Include="Microsoft.CSharp" Version="4.5.0" /> <PackageReference Include="Microsoft.CSharp" Version="4.5.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="2.2.0" /> <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="2.2.0" /> <PackageReference Include="Microsoft.Extensions.Logging" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="2.2.0" /> <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="2.1.0" />
<PackageReference Include="MySql.Data" Version="8.0.13" /> <PackageReference Include="MySql.Data" Version="8.0.13" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.1" /> <PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
<PackageReference Include="Npgsql" Version="4.0.4" /> <PackageReference Include="Npgsql" Version="4.0.4" />
@ -23,6 +23,7 @@
<PackageReference Include="Oracle.ManagedDataAccess.Core" Version="2.18.3" /> <PackageReference Include="Oracle.ManagedDataAccess.Core" Version="2.18.3" />
<PackageReference Include="SafeObjectPool" Version="1.0.12" /> <PackageReference Include="SafeObjectPool" Version="1.0.12" />
<PackageReference Include="System.Data.SqlClient" Version="4.6.0" /> <PackageReference Include="System.Data.SqlClient" Version="4.6.0" />
<PackageReference Include="System.Data.SQLite.Core" Version="1.0.109.2" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -93,6 +93,7 @@ namespace FreeSql {
case DataType.SqlServer: ret = new SqlServer.SqlServerProvider(_cache, _logger, _masterConnectionString, _slaveConnectionString); break; case DataType.SqlServer: ret = new SqlServer.SqlServerProvider(_cache, _logger, _masterConnectionString, _slaveConnectionString); break;
case DataType.PostgreSQL: ret = new PostgreSQL.PostgreSQLProvider(_cache, _logger, _masterConnectionString, _slaveConnectionString); break; case DataType.PostgreSQL: ret = new PostgreSQL.PostgreSQLProvider(_cache, _logger, _masterConnectionString, _slaveConnectionString); break;
case DataType.Oracle: ret = new Oracle.OracleProvider(_cache, _logger, _masterConnectionString, _slaveConnectionString); break; case DataType.Oracle: ret = new Oracle.OracleProvider(_cache, _logger, _masterConnectionString, _slaveConnectionString); break;
case DataType.Sqlite3: ret = new Sqlite3.SqliteProvider(_cache, _logger, _masterConnectionString, _slaveConnectionString); break;
} }
if (ret != null) { if (ret != null) {
ret.CodeFirst.IsAutoSyncStructure = _isAutoSyncStructure; ret.CodeFirst.IsAutoSyncStructure = _isAutoSyncStructure;
@ -105,5 +106,5 @@ namespace FreeSql {
} }
} }
public enum DataType { MySql, SqlServer, PostgreSQL, Oracle } public enum DataType { MySql, SqlServer, PostgreSQL, Oracle, Sqlite3 }
} }

View File

@ -541,7 +541,7 @@ return rTn;");
#region Complie #region Complie
private static ITemplateOutput Complie(string cscode, string typename) { private static ITemplateOutput Complie(string cscode, string typename) {
var assemly = _compiler.Value.CompileCode(cscode); var assemly = _compiler.Value.CompileCode(cscode);
return assemly.CreateObject(typename) as ITemplateOutput; return assemly.CreateInstance(typename) as ITemplateOutput;
} }
static ConcurrentDictionary<string, (DateTime, object)> _compiler_objs = new ConcurrentDictionary<string, (DateTime, object)>(); static ConcurrentDictionary<string, (DateTime, object)> _compiler_objs = new ConcurrentDictionary<string, (DateTime, object)>();
static Lazy<CSScriptLib.RoslynEvaluator> _compiler = new Lazy<CSScriptLib.RoslynEvaluator>(() => { static Lazy<CSScriptLib.RoslynEvaluator> _compiler = new Lazy<CSScriptLib.RoslynEvaluator>(() => {

20
FreeSql/Interface/IAop.cs Normal file
View File

@ -0,0 +1,20 @@
//using FreeSql.DatabaseModel;
//using System;
//using System.Collections.Generic;
//namespace FreeSql {
// public interface IAop {
// ISelect<T1> SelectFitler<T1>(ISelect<T1> select) where T1 : class;
// //ISelect<T1, T2, T3> SelectFitler<T1, T2, T3>(ISelect<T1, T2, T3> select) where T1 : class where T2 : class where T3 : class;
// //ISelect<T1, T2, T3, T4> SelectFitler<T1, T2, T3, T4>(ISelect<T1, T2, T3, T4> select) where T1 : class where T2 : class where T3 : class where T4 : class;
// //ISelect<T1, T2, T3, T4, T5, T6> SelectFitler<T1, T2, T3, T4, T5, T6>(ISelect<T1, T2, T3, T4, T5, T6> select) where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class;
// //ISelect<T1, T2, T3, T4, T5, T6, T7> SelectFitler<T1, T2, T3, T4, T5, T6, T7>(ISelect<T1, T2, T3, T4, T5, T6, T7> select) where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class;
// //ISelect<T1, T2, T3, T4, T5, T6, T7, T8> SelectFitler<T1, T2, T3, T4, T5, T6, T7, T8>(ISelect<T1, T2, T3, T4, T5, T6, T7, T8> select) where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class;
// //ISelect<T1, T2, T3, T4, T5, T6, T7, T8, T9> SelectFitler<T1, T2, T3, T4, T5, T6, T7, T8, T9>(ISelect<T1, T2, T3, T4, T5, T6, T7, T8, T9> select) 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;
// //ISelect<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> SelectFitler<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(ISelect<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> select) 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;
// IUpdate<T1> UpdateFitler<T1>(IUpdate<T1> update) where T1 : class;
// IDelete<T1> DeleteFitler<T1>(IUpdate<T1> delete) where T1 : class;
// }
//}

View File

@ -252,7 +252,10 @@ namespace FreeSql.Internal {
case "Newtonsoft.Json.Linq.JArray": return JArray.Parse(string.Concat(value)); case "Newtonsoft.Json.Linq.JArray": return JArray.Parse(string.Concat(value));
case "Npgsql.LegacyPostgis.PostgisGeometry": return value; case "Npgsql.LegacyPostgis.PostgisGeometry": return value;
} }
if (type != value.GetType()) return Convert.ChangeType(value, type); if (type != value.GetType()) {
if (type.FullName == "System.TimeSpan") return TimeSpan.FromMilliseconds(double.Parse(value.ToString()));
return Convert.ChangeType(value, type);
}
return value; return value;
} }
internal static string GetCsName(string name) { internal static string GetCsName(string name) {

View File

@ -96,47 +96,47 @@ namespace FreeSql.Oracle.Curd {
public override List<T1> ExecuteInserted() { public override List<T1> ExecuteInserted() {
throw new NotImplementedException(); throw new NotImplementedException();
var sql = this.ToSql(); // var sql = this.ToSql();
if (string.IsNullOrEmpty(sql)) return new List<T1>(); // if (string.IsNullOrEmpty(sql)) return new List<T1>();
var sb = new StringBuilder(); // var sb = new StringBuilder();
sb.Append(@"declare // sb.Append(@"declare
type v_tp_rec is record("); //type v_tp_rec is record(");
var colidx = 0; // var colidx = 0;
foreach (var col in _table.Columns.Values) { // foreach (var col in _table.Columns.Values) {
if (colidx > 0) sb.Append(", "); // if (colidx > 0) sb.Append(", ");
sb.Append(_commonUtils.QuoteSqlName(col.CsName)).Append(" ").Append(_commonUtils.QuoteSqlName(_table.DbName)).Append(".").Append(_commonUtils.QuoteSqlName(col.Attribute.Name)).Append("%type"); // sb.Append(_commonUtils.QuoteSqlName(col.CsName)).Append(" ").Append(_commonUtils.QuoteSqlName(_table.DbName)).Append(".").Append(_commonUtils.QuoteSqlName(col.Attribute.Name)).Append("%type");
++colidx; // ++colidx;
} // }
sb.Append(@"); // sb.Append(@");
type v_tp_tab is table of v_tp_rec; //type v_tp_tab is table of v_tp_rec;
v_tab v_tp_tab; //v_tab v_tp_tab;
begin //begin
"); //");
sb.Append(sql).Append(" RETURNING "); // sb.Append(sql).Append(" RETURNING ");
colidx = 0; // colidx = 0;
foreach (var col in _table.Columns.Values) { // foreach (var col in _table.Columns.Values) {
if (colidx > 0) sb.Append(", "); // if (colidx > 0) sb.Append(", ");
sb.Append(_commonUtils.QuoteReadColumn(col.CsType, _commonUtils.QuoteSqlName(col.Attribute.Name))); // sb.Append(_commonUtils.QuoteReadColumn(col.CsType, _commonUtils.QuoteSqlName(col.Attribute.Name)));
++colidx; // ++colidx;
} // }
sb.Append(@"bulk collect into v_tab; // sb.Append(@"bulk collect into v_tab;
for i in 1..v_tab.count loop //for i in 1..v_tab.count loop
dbms_output.put_line("); // dbms_output.put_line(");
//v_tab(i).empno||'-'||v_tab(i).ename // //v_tab(i).empno||'-'||v_tab(i).ename
colidx = 0; // colidx = 0;
foreach (var col in _table.Columns.Values) { // foreach (var col in _table.Columns.Values) {
if (colidx > 0) sb.Append("||'-'||"); // if (colidx > 0) sb.Append("||'-'||");
sb.Append("v_tab(i).").Append(_commonUtils.QuoteSqlName(col.CsName)); // sb.Append("v_tab(i).").Append(_commonUtils.QuoteSqlName(col.CsName));
++colidx; // ++colidx;
} // }
sb.Append(@"); // sb.Append(@");
end loop; //end loop;
end; //end;
"); //");
return _orm.Ado.Query<T1>(CommandType.Text, sb.ToString(), _params); // return _orm.Ado.Query<T1>(CommandType.Text, sb.ToString(), _params);
} }
public override Task<List<T1>> ExecuteInsertedAsync() { public override Task<List<T1>> ExecuteInsertedAsync() {
throw new NotImplementedException(); throw new NotImplementedException();

View File

@ -0,0 +1,22 @@
using FreeSql.Internal;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
namespace FreeSql.Sqlite3.Curd {
class SqliteDelete<T1> : Internal.CommonProvider.DeleteProvider<T1> where T1 : class {
public SqliteDelete(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere)
: base(orm, commonUtils, commonExpression, dywhere) {
}
public override List<T1> ExecuteDeleted() {
throw new NotImplementedException();
}
public override Task<List<T1>> ExecuteDeletedAsync() {
throw new NotImplementedException();
}
}
}

View File

@ -0,0 +1,35 @@
using FreeSql.Internal;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
namespace FreeSql.Sqlite3.Curd {
class SqliteInsert<T1> : Internal.CommonProvider.InsertProvider<T1> where T1 : class {
public SqliteInsert(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression)
: base(orm, commonUtils, commonExpression) {
}
public override long ExecuteIdentity() {
var sql = this.ToSql();
if (string.IsNullOrEmpty(sql)) return 0;
return long.TryParse(string.Concat(_orm.Ado.ExecuteScalar(CommandType.Text, string.Concat(sql, "; SELECT last_insert_rowid();"), _params)), out var trylng) ? trylng : 0;
}
async public override Task<long> ExecuteIdentityAsync() {
var sql = this.ToSql();
if (string.IsNullOrEmpty(sql)) return 0;
return long.TryParse(string.Concat(await _orm.Ado.ExecuteScalarAsync(CommandType.Text, string.Concat(sql, "; SELECT last_insert_rowid();"), _params)), out var trylng) ? trylng : 0;
}
public override List<T1> ExecuteInserted() {
throw new NotImplementedException();
}
public override Task<List<T1>> ExecuteInsertedAsync() {
throw new NotImplementedException();
}
}
}

View File

@ -0,0 +1,115 @@
using FreeSql.Internal;
using FreeSql.Internal.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace FreeSql.Sqlite3.Curd {
class SqliteSelect<T1> : FreeSql.Internal.CommonProvider.Select1Provider<T1> where T1 : class {
internal static string ToSqlStatic(CommonUtils _commonUtils, string _select, string field, StringBuilder _join, StringBuilder _where, string _groupby, string _having, string _orderby, int _skip, int _limit, List<SelectTableInfo> _tables, IFreeSql _orm) {
if (_orm.CodeFirst.IsAutoSyncStructure)
_orm.CodeFirst.SyncStructure(_tables.Select(a => a.Table.Type).ToArray());
var sb = new StringBuilder();
sb.Append(_select).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(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(tbsfrom[b].Table.DbName)).Append(" ").Append(tbsfrom[b].Alias).Append(" ON 1 = 1");
break;
}
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(tb.Table.DbName)).Append(" ").Append(tb.Alias).Append(" ON ").Append(tb.On);
}
if (_join.Length > 0) sb.Append(_join);
var sbqf = new StringBuilder();
foreach (var tb in _tables) {
if (tb.Type == SelectTableInfoType.Parent) continue;
if (string.IsNullOrEmpty(tb.Table.SelectFilter) == false)
sbqf.Append(" AND (").Append(tb.Table.SelectFilter.Replace("a.", $"{tb.Alias}.")).Append(")");
}
if (_where.Length > 0) {
sb.Append(" \r\nWHERE ").Append(_where.ToString().Substring(5));
if (sbqf.Length > 0) sb.Append(sbqf.ToString());
} else {
if (sbqf.Length > 0) sb.Append(" \r\nWHERE ").Append(sbqf.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);
return sb.ToString();
}
public SqliteSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { }
public override ISelect<T1, T2, T3> From<T2, T3>(Expression<Func<ISelectFromExpression<T1>, T2, T3, ISelectFromExpression<T1>>> exp) { this.InternalFrom(exp?.Body); var ret = new SqliteSelect<T1, T2, T3>(_orm, _commonUtils, _commonExpression, null); SqliteSelect<T1>.CopyData(this, ret); return ret; }
public override ISelect<T1, T2, T3, T4> From<T2, T3, T4>(Expression<Func<ISelectFromExpression<T1>, T2, T3, T4, ISelectFromExpression<T1>>> exp) { this.InternalFrom(exp?.Body); var ret = new SqliteSelect<T1, T2, T3, T4>(_orm, _commonUtils, _commonExpression, null); SqliteSelect<T1>.CopyData(this, ret); return ret; }
public override ISelect<T1, T2, T3, T4, T5> From<T2, T3, T4, T5>(Expression<Func<ISelectFromExpression<T1>, T2, T3, T4, T5, ISelectFromExpression<T1>>> exp) { this.InternalFrom(exp?.Body); var ret = new SqliteSelect<T1, T2, T3, T4, T5>(_orm, _commonUtils, _commonExpression, null); SqliteSelect<T1>.CopyData(this, ret); return ret; }
public override ISelect<T1, T2, T3, T4, T5, T6> From<T2, T3, T4, T5, T6>(Expression<Func<ISelectFromExpression<T1>, T2, T3, T4, T5, T6, ISelectFromExpression<T1>>> exp) { this.InternalFrom(exp?.Body); var ret = new SqliteSelect<T1, T2, T3, T4, T5, T6>(_orm, _commonUtils, _commonExpression, null); SqliteSelect<T1>.CopyData(this, ret); return ret; }
public override ISelect<T1, T2, T3, T4, T5, T6, T7> From<T2, T3, T4, T5, T6, T7>(Expression<Func<ISelectFromExpression<T1>, T2, T3, T4, T5, T6, T7, ISelectFromExpression<T1>>> exp) { this.InternalFrom(exp?.Body); var ret = new SqliteSelect<T1, T2, T3, T4, T5, T6, T7>(_orm, _commonUtils, _commonExpression, null); SqliteSelect<T1>.CopyData(this, ret); return ret; }
public override ISelect<T1, T2, T3, T4, T5, T6, T7, T8> From<T2, T3, T4, T5, T6, T7, T8>(Expression<Func<ISelectFromExpression<T1>, T2, T3, T4, T5, T6, T7, T8, ISelectFromExpression<T1>>> exp) { this.InternalFrom(exp?.Body); var ret = new SqliteSelect<T1, T2, T3, T4, T5, T6, T7, T8>(_orm, _commonUtils, _commonExpression, null); SqliteSelect<T1>.CopyData(this, ret); return ret; }
public override ISelect<T1, T2, T3, T4, T5, T6, T7, T8, T9> From<T2, T3, T4, T5, T6, T7, T8, T9>(Expression<Func<ISelectFromExpression<T1>, T2, T3, T4, T5, T6, T7, T8, T9, ISelectFromExpression<T1>>> exp) { this.InternalFrom(exp?.Body); var ret = new SqliteSelect<T1, T2, T3, T4, T5, T6, T7, T8, T9>(_orm, _commonUtils, _commonExpression, null); SqliteSelect<T1>.CopyData(this, ret); return ret; }
public override ISelect<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> From<T2, T3, T4, T5, T6, T7, T8, T9, T10>(Expression<Func<ISelectFromExpression<T1>, T2, T3, T4, T5, T6, T7, T8, T9, T10, ISelectFromExpression<T1>>> exp) { this.InternalFrom(exp?.Body); var ret = new SqliteSelect<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(_orm, _commonUtils, _commonExpression, null); SqliteSelect<T1>.CopyData(this, ret); return ret; }
public override string ToSql(string field = null) => ToSqlStatic(_commonUtils, _select, field ?? this.GetAllField().field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, _orm);
}
class SqliteSelect<T1, T2, T3> : FreeSql.Internal.CommonProvider.Select3Provider<T1, T2, T3> 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<T1>.ToSqlStatic(_commonUtils, _select, field ?? this.GetAllField().field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, _orm);
}
class SqliteSelect<T1, T2, T3, T4> : FreeSql.Internal.CommonProvider.Select4Provider<T1, T2, T3, T4> 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<T1>.ToSqlStatic(_commonUtils, _select, field ?? this.GetAllField().field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, _orm);
}
class SqliteSelect<T1, T2, T3, T4, T5> : FreeSql.Internal.CommonProvider.Select5Provider<T1, T2, T3, T4, T5> 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<T1>.ToSqlStatic(_commonUtils, _select, field ?? this.GetAllField().field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, _orm);
}
class SqliteSelect<T1, T2, T3, T4, T5, T6> : FreeSql.Internal.CommonProvider.Select6Provider<T1, T2, T3, T4, T5, T6> 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<T1>.ToSqlStatic(_commonUtils, _select, field ?? this.GetAllField().field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, _orm);
}
class SqliteSelect<T1, T2, T3, T4, T5, T6, T7> : FreeSql.Internal.CommonProvider.Select7Provider<T1, T2, T3, T4, T5, T6, T7> 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<T1>.ToSqlStatic(_commonUtils, _select, field ?? this.GetAllField().field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, _orm);
}
class SqliteSelect<T1, T2, T3, T4, T5, T6, T7, T8> : FreeSql.Internal.CommonProvider.Select8Provider<T1, T2, T3, T4, T5, T6, T7, T8> 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<T1>.ToSqlStatic(_commonUtils, _select, field ?? this.GetAllField().field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, _orm);
}
class SqliteSelect<T1, T2, T3, T4, T5, T6, T7, T8, T9> : FreeSql.Internal.CommonProvider.Select9Provider<T1, T2, T3, T4, T5, T6, T7, T8, T9> 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<T1>.ToSqlStatic(_commonUtils, _select, field ?? this.GetAllField().field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, _orm);
}
class SqliteSelect<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> : FreeSql.Internal.CommonProvider.Select10Provider<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> 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<T1>.ToSqlStatic(_commonUtils, _select, field ?? this.GetAllField().field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, _orm);
}
}

View File

@ -0,0 +1,55 @@
using FreeSql.Internal;
using FreeSql.Internal.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FreeSql.Sqlite3.Curd {
class SqliteUpdate<T1> : Internal.CommonProvider.UpdateProvider<T1> where T1 : class {
public SqliteUpdate(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere)
: base(orm, commonUtils, commonExpression, dywhere) {
}
public override List<T1> ExecuteUpdated() {
throw new NotImplementedException();
}
public override Task<List<T1>> ExecuteUpdatedAsync() {
throw new NotImplementedException();
}
protected override void ToSqlCase(StringBuilder caseWhen, ColumnInfo[] primarys) {
if (_table.Primarys.Length == 1) {
caseWhen.Append(_commonUtils.QuoteReadColumn(_table.Primarys.First().CsType, _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.CsType, _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.Properties.TryGetValue(_table.Primarys.First().CsName, out var tryp2) ? tryp2.GetValue(d) : null));
return;
}
sb.Append("CONCAT(");
var pkidx = 0;
foreach (var pk in _table.Primarys) {
if (pkidx > 0) sb.Append(", ");
sb.Append(_commonUtils.FormatSql("{0}", _table.Properties.TryGetValue(pk.CsName, out var tryp2) ? tryp2.GetValue(d) : null));
++pkidx;
}
sb.Append(")");
}
}
}

View File

@ -0,0 +1,67 @@
using FreeSql.Internal;
using Microsoft.Extensions.Logging;
using SafeObjectPool;
using System;
using System.Collections;
using System.Data.Common;
using System.Data.SQLite;
using System.Text;
using System.Threading;
namespace FreeSql.Sqlite3 {
class SqliteAdo : FreeSql.Internal.CommonProvider.AdoProvider {
CommonUtils _util;
public SqliteAdo() : base(null, null) { }
public SqliteAdo(CommonUtils util, ICache cache, ILogger log, string masterConnectionString, string[] slaveConnectionStrings) : base(cache, log) {
this._util = util;
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) {
if (param == null) return "NULL";
if (param is bool || param is bool?)
return (bool)param ? 1 : 0;
else if (param is string)
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)
return string.Concat("'", ((DateTime)param).ToString("yyyy-MM-dd HH:mm:ss"), "'");
else if (param is DateTime?)
return string.Concat("'", (param as DateTime?).Value.ToString("yyyy-MM-dd HH:mm:ss"), "'");
else if (param is TimeSpan)
return ((TimeSpan)param).Ticks / 10000;
else if (param is TimeSpan?)
return (param as TimeSpan?).Value.Ticks / 10000;
else if (param is MygisGeometry)
return (param as MygisGeometry).AsText();
else if (param is IEnumerable) {
var sb = new StringBuilder();
var ie = param as IEnumerable;
foreach (var z in ie) sb.Append(",").Append(AddslashesProcessParam(z));
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 SQLiteCommand();
}
protected override void ReturnConnection(ObjectPool<DbConnection> pool, Object<DbConnection> conn, Exception ex) {
(pool as SqliteConnectionPool).Return(conn, ex);
}
protected override DbParameter[] GetDbParamtersByObject(string sql, object obj) => _util.GetDbParamtersByObject(sql, obj);
}
}

View File

@ -0,0 +1,178 @@
using SafeObjectPool;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace FreeSql.Sqlite3 {
class SqliteConnectionPool : ObjectPool<DbConnection> {
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;
this.availableHandler = availableHandler;
this.unavailableHandler = unavailableHandler;
}
public void Return(Object<DbConnection> obj, Exception exception, bool isRecreate = false) {
if (exception != null && exception is SQLiteException) {
try { if ((obj.Value as SQLiteConnection).Ping() == false) obj.Value.OpenAndAttach(policy.Attaches); } catch { base.SetUnavailable(exception); }
}
base.Return(obj, isRecreate);
}
internal SqliteConnectionPoolPolicy policy;
}
class SqliteConnectionPoolPolicy : IPolicy<DbConnection> {
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 int AsyncGetCapacity { get; set; } = 10000;
public bool IsThrowGetTimeoutException { get; set; } = true;
public int CheckAvailableInterval { get; set; } = 5;
public string[] Attaches = new string[0];
private string _connectionString;
public string ConnectionString {
get => _connectionString;
set {
_connectionString = value ?? "";
var m = Regex.Match(_connectionString, @"Max\s*pool\s*size\s*=\s*(\d+)", RegexOptions.IgnoreCase);
if (m.Success == false || int.TryParse(m.Groups[1].Value, out var poolsize) == false || poolsize <= 0) poolsize = 100;
PoolSize = poolsize;
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 initConns = new Object<DbConnection>[poolsize];
for (var a = 0; a < poolsize; a++) try { initConns[a] = _pool.Get(); } catch { }
foreach (var conn in initConns) _pool.Return(conn);
}
}
public bool OnCheckAvailable(Object<DbConnection> obj) {
if ((obj.Value as SQLiteConnection).Ping() == false) obj.Value.OpenAndAttach(Attaches);
return (obj.Value as SQLiteConnection).Ping();
}
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 OnGet(Object<DbConnection> obj) {
if (_pool.IsAvailable) {
if (obj.Value.State != ConnectionState.Open || DateTime.Now.Subtract(obj.LastReturnTime).TotalSeconds > 60 && (obj.Value as SQLiteConnection).Ping() == false) {
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<DbConnection> obj) {
if (_pool.IsAvailable) {
if (obj.Value.State != ConnectionState.Open || DateTime.Now.Subtract(obj.LastReturnTime).TotalSeconds > 60 && (obj.Value as SQLiteConnection).Ping() == false) {
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 OnReturn(Object<DbConnection> obj) {
}
public void OnAvailable() {
_pool.availableHandler?.Invoke();
}
public void OnUnavailable() {
_pool.unavailableHandler?.Invoke();
}
}
static class SqliteConnectionExtensions {
public static bool Ping(this DbConnection that) {
try {
var cmd = that.CreateCommand();
cmd.CommandText = "select 1";
cmd.ExecuteNonQuery();
return true;
} catch {
if (that.State != ConnectionState.Closed) try { that.Close(); } catch { }
return false;
}
}
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");
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");
var cmd = that.CreateCommand();
cmd.CommandText = sb.ToString();
await cmd.ExecuteNonQueryAsync();
}
}
}
}

View File

@ -0,0 +1,239 @@
using FreeSql.DatabaseModel;
using FreeSql.Internal;
using FreeSql.Internal.Model;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace FreeSql.Sqlite3 {
class SqliteCodeFirst : ICodeFirst {
IFreeSql _orm;
protected CommonUtils _commonUtils;
protected CommonExpression _commonExpression;
public SqliteCodeFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) {
_orm = orm;
_commonUtils = commonUtils;
_commonExpression = commonExpression;
}
public bool IsAutoSyncStructure { get; set; } = true;
public bool IsSyncStructureToLower { get; set; } = false;
static object _dicCsToDbLock = new object();
static Dictionary<string, (DbType type, string dbtype, string dbtypeFull, bool? isUnsigned, bool? isnullable, object defaultValue)> _dicCsToDb = new Dictionary<string, (DbType type, string dbtype, string dbtypeFull, bool? isUnsigned, bool? isnullable, object defaultValue)>() {
{ 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(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(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(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 (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.FullName.StartsWith("System.Nullable`1[") && 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 string GetComparisonDDLStatements<TEntity>() => this.GetComparisonDDLStatements(typeof(TEntity));
public 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);
var tbname = tb.DbName.Split(new[] { '.' }, 2);
if (tbname?.Length == 1) tbname = new[] { "main", tbname[0] };
var tboldname = tb.DbOldName?.Split(new[] { '.' }, 2); //旧表名
if (tboldname?.Length == 1) tboldname = new[] { "main", tboldname[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 && tbcol.Attribute.DbType.IndexOf("AUTOINCREMENT", StringComparison.CurrentCultureIgnoreCase) == -1) {
isIndent = true;
sb.Append(" PRIMARY KEY AUTOINCREMENT");
}
sb.Append(",");
}
if (isIndent || tb.Primarys.Any() == false)
sb.Remove(sb.Length - 1, 1);
else {
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(")");
}
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 tbtmp = tboldname ?? tbname;
var dsql = _orm.Ado.ExecuteScalar(CommandType.Text, $" select 1 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[0]}\" ");
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);
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 (tbstructcol.column == tbcol.Attribute.OldName)
//修改列名
istmpatler = true;
continue;
}
//添加列
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 && tbcol.Attribute.DbType.IndexOf("AUTOINCREMENT", StringComparison.CurrentCultureIgnoreCase) == -1) {
isIndent = true;
sb.Append(" PRIMARY KEY AUTOINCREMENT");
}
sb.Append(",");
}
if (isIndent || tb.Primarys.Any() == false)
sb.Remove(sb.Length - 1, 1);
else {
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(")");
}
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();
}
ConcurrentDictionary<string, bool> dicSyced = new ConcurrentDictionary<string, bool>();
public bool SyncStructure<TEntity>() => this.SyncStructure(typeof(TEntity));
public bool SyncStructure(params Type[] entityTypes) {
if (entityTypes == null) return true;
var syncTypes = entityTypes.Where(a => dicSyced.ContainsKey(a.FullName) == false).ToArray();
if (syncTypes.Any() == false) return true;
var 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;
}
}
}

View File

@ -0,0 +1,385 @@
using FreeSql.DatabaseModel;
using FreeSql.Internal;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
namespace FreeSql.Sqlite3 {
class SqliteDbFirst : IDbFirst {
IFreeSql _orm;
protected CommonUtils _commonUtils;
protected CommonExpression _commonExpression;
public SqliteDbFirst(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;
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 "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 "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 "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 "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<int, (string csConvert, string csParse, string csStringify, string csType, Type csTypeInfo, Type csNullableTypeInfo, string csTypeValue, string dataReaderMethod)> _dicDbToCs = new Dictionary<int, (string csConvert, string csParse, string csStringify, string csType, Type csTypeInfo, Type csNullableTypeInfo, string csTypeValue, string dataReaderMethod)>() {
{ (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.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.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.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.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.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 List<string> 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<DbTableInfo> GetTablesByDatabase(params string[] database) {
var loc1 = new List<DbTableInfo>();
var loc2 = new Dictionary<string, DbTableInfo>();
var loc3 = new Dictionary<string, Dictionary<string, DbColumnInfo>>();
if (database == null || database.Any() == false) return loc1;
var databaseIn = string.Join(",", database.Select(a => "{0}".FormatMySql(a)));
var sql = string.Format(@"
select
concat(a.table_schema, '.', a.table_name) 'id',
a.table_schema 'schema',
a.table_name 'table',
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 loc6 = new List<string>();
var loc66 = new List<string>();
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 type = string.Concat(row[3]) == "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, Type = type });
loc3.Add(table_id, new Dictionary<string, DbColumnInfo>());
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(@"
select
concat(a.table_schema, '.', a.table_name),
a.column_name,
a.data_type,
ifnull(a.character_maximum_length, 0) 'len',
a.column_type,
case when a.is_nullable = 'YES' then 1 else 0 end 'is_nullable',
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 ({1}) and a.table_name in ({0})
", loc8, databaseIn);
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]);
}
sql = string.Format(@"
select
concat(a.constraint_schema, '.', a.table_name) 'table_id',
a.column_name,
concat(a.constraint_schema, '/', a.table_name, '/', a.constraint_name) 'index_id',
1 'IsUnique',
case when constraint_name = 'PRIMARY' then 1 else 0 end 'IsPrimaryKey',
0 'IsClustered',
0 'IsDesc'
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;
var indexColumns = new Dictionary<string, Dictionary<string, List<DbColumnInfo>>>();
var uniqueColumns = new Dictionary<string, Dictionary<string, List<DbColumnInfo>>>();
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<string, List<DbColumnInfo>> loc10 = null;
List<DbColumnInfo> loc11 = null;
if (!indexColumns.TryGetValue(table_id, out loc10))
indexColumns.Add(table_id, loc10 = new Dictionary<string, List<DbColumnInfo>>());
if (!loc10.TryGetValue(index_id, out loc11))
loc10.Add(index_id, loc11 = new List<DbColumnInfo>());
loc11.Add(loc9);
if (is_unique) {
if (!uniqueColumns.TryGetValue(table_id, out loc10))
uniqueColumns.Add(table_id, loc10 = new Dictionary<string, List<DbColumnInfo>>());
if (!loc10.TryGetValue(index_id, out loc11))
loc10.Add(index_id, loc11 = new List<DbColumnInfo>());
loc11.Add(loc9);
}
}
foreach (string table_id in indexColumns.Keys) {
foreach (var columns in indexColumns[table_id].Values)
loc2[table_id].Indexes.Add(columns);
}
foreach (string table_id in uniqueColumns.Keys) {
foreach (var columns in uniqueColumns[table_id].Values) {
columns.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
loc2[table_id].Uniques.Add(columns);
}
}
sql = string.Format(@"
select
concat(a.constraint_schema, '.', a.table_name) 'table_id',
a.column_name,
concat(a.constraint_schema, '/', a.constraint_name) 'FKId',
concat(a.referenced_table_schema, '.', a.referenced_table_name) 'ref_table_id',
1 'IsForeignKey',
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;
var fkColumns = new Dictionary<string, Dictionary<string, DbForeignInfo>>();
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<string, DbForeignInfo> loc12 = null;
DbForeignInfo loc13 = null;
if (!fkColumns.TryGetValue(table_id, out loc12))
fkColumns.Add(table_id, loc12 = new Dictionary<string, DbForeignInfo>());
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].Values)
loc2[table_id].Foreigns.Add(fk);
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.Uniques.Count > 0) {
foreach (var loc5 in loc4.Uniques[0]) {
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.Foreigns.Find(fk => fk.Columns.Find(c3 => c3.Name == c1.Name) != null) != null;
bool b2 = loc4.Foreigns.Find(fk => fk.Columns.Find(c3 => c3.Name == c2.Name) != null) != null;
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 loc4 in loc1) {
var dicUniques = new Dictionary<string, List<DbColumnInfo>>();
if (loc4.Primarys.Count > 0) dicUniques.Add(string.Join(",", loc4.Primarys.Select(a => a.Name)), loc4.Primarys);
foreach(var loc5 in loc4.Uniques) {
var dickey = string.Join(",", loc5.Select(a => a.Name));
if (dicUniques.ContainsKey(dickey)) continue;
dicUniques.Add(dickey, loc5);
}
loc4.Uniques = dicUniques.Values.ToList();
}
loc2.Clear();
loc3.Clear();
return loc1;
}
public List<DbEnumInfo> GetEnumsByDatabase(params string[] database) {
return new List<DbEnumInfo>();
}
}
}

View File

@ -0,0 +1,315 @@
using FreeSql.Internal;
using FreeSql.Internal.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace FreeSql.Sqlite3 {
class SqliteExpression : CommonExpression {
public SqliteExpression(CommonUtils common) : base(common) { }
internal override string ExpressionLambdaToSqlOther(Expression exp, List<SelectTableInfo> _tables, List<SelectColumnInfo> _selectColumnMap, Func<Expression[], string> getSelectGroupingMapString, SelectTableInfoType tbtype, bool isQuoteName) {
Func<Expression, string> getExp = exparg => ExpressionLambdaToSql(exparg, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName);
switch (exp.NodeType) {
case ExpressionType.Call:
var callExp = exp as MethodCallExpression;
var objExp = callExp.Object;
var objType = objExp?.Type;
if (objType?.FullName == "System.Byte[]") return null;
var argIndex = 0;
if (objType == null && callExp.Method.DeclaringType.FullName == typeof(Enumerable).FullName) {
objExp = callExp.Arguments.FirstOrDefault();
objType = objExp?.Type;
argIndex++;
}
if (objType == null) objType = callExp.Method.DeclaringType;
if (objType != null) {
var left = objExp == null ? null : getExp(objExp);
if (objType.IsArray == true) {
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]));
}
return arrSb.Append(")").ToString();
}
return null;
}
internal override string ExpressionLambdaToSqlMemberAccessString(MemberExpression exp, List<SelectTableInfo> _tables, List<SelectColumnInfo> _selectColumnMap, Func<Expression[], string> getSelectGroupingMapString, SelectTableInfoType tbtype, bool isQuoteName) {
if (exp.Expression == null) {
switch (exp.Member.Name) {
case "Empty": return "''";
}
return null;
}
var left = ExpressionLambdaToSql(exp.Expression, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName);
switch (exp.Member.Name) {
case "Length": return $"char_length({left})";
}
return null;
}
internal override string ExpressionLambdaToSqlMemberAccessDateTime(MemberExpression exp, List<SelectTableInfo> _tables, List<SelectColumnInfo> _selectColumnMap, Func<Expression[], string> getSelectGroupingMapString, SelectTableInfoType tbtype, bool isQuoteName) {
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, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName);
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;
}
internal override string ExpressionLambdaToSqlMemberAccessTimeSpan(MemberExpression exp, List<SelectTableInfo> _tables, List<SelectColumnInfo> _selectColumnMap, Func<Expression[], string> getSelectGroupingMapString, SelectTableInfoType tbtype, bool isQuoteName) {
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, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName);
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;
}
internal override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, List<SelectTableInfo> _tables, List<SelectColumnInfo> _selectColumnMap, Func<Expression[], string> getSelectGroupingMapString, SelectTableInfoType tbtype, bool isQuoteName) {
Func<Expression, string> getExp = exparg => ExpressionLambdaToSql(exparg, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName);
if (exp.Object == null) {
switch (exp.Method.Name) {
case "IsNullOrEmpty":
var arg1 = getExp(exp.Arguments[0]);
return $"({arg1} is null or {arg1} = '')";
}
} 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} 解析");
}
internal override string ExpressionLambdaToSqlCallMath(MethodCallExpression exp, List<SelectTableInfo> _tables, List<SelectColumnInfo> _selectColumnMap, Func<Expression[], string> getSelectGroupingMapString, SelectTableInfoType tbtype, bool isQuoteName) {
Func<Expression, string> getExp = exparg => ExpressionLambdaToSql(exparg, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName);
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} 解析");
}
internal override string ExpressionLambdaToSqlCallDateTime(MethodCallExpression exp, List<SelectTableInfo> _tables, List<SelectColumnInfo> _selectColumnMap, Func<Expression[], string> getSelectGroupingMapString, SelectTableInfoType tbtype, bool isQuoteName) {
Func<Expression, string> getExp = exparg => ExpressionLambdaToSql(exparg, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName);
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 "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":
if (exp.Arguments[0].Type.FullName == "System.DateTime" || exp.Arguments[0].Type.GenericTypeArguments.FirstOrDefault()?.FullName == "System.DateTime")
return $"timestampdiff(microsecond, {args1}, {left})";
if (exp.Arguments[0].Type.FullName == "System.TimeSpan" || exp.Arguments[0].Type.GenericTypeArguments.FirstOrDefault()?.FullName == "System.TimeSpan")
return $"date_sub({left}, interval ({args1}) microsecond)";
break;
case "Equals": return $"({left} = {getExp(exp.Arguments[0])})";
case "CompareTo": return $"(({left}) - ({getExp(exp.Arguments[0])}))";
case "ToString": return $"date_format({left}, '%Y-%m-%d %H:%i:%s.%f')";
}
}
throw new Exception($"MySqlExpression 未现实函数表达式 {exp} 解析");
}
internal override string ExpressionLambdaToSqlCallTimeSpan(MethodCallExpression exp, List<SelectTableInfo> _tables, List<SelectColumnInfo> _selectColumnMap, Func<Expression[], string> getSelectGroupingMapString, SelectTableInfoType tbtype, bool isQuoteName) {
Func<Expression, string> getExp = exparg => ExpressionLambdaToSql(exparg, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName);
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} 解析");
}
internal override string ExpressionLambdaToSqlCallConvert(MethodCallExpression exp, List<SelectTableInfo> _tables, List<SelectColumnInfo> _selectColumnMap, Func<Expression[], string> getSelectGroupingMapString, SelectTableInfoType tbtype, bool isQuoteName) {
Func<Expression, string> getExp = exparg => ExpressionLambdaToSql(exparg, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName);
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} 解析");
}
}
}

View File

@ -0,0 +1,49 @@
using FreeSql.Internal;
using FreeSql.Internal.CommonProvider;
using FreeSql.Sqlite3.Curd;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Data.Common;
namespace FreeSql.Sqlite3 {
class SqliteProvider : IFreeSql {
public ISelect<T1> Select<T1>() where T1 : class => new SqliteSelect<T1>(this, this.InternalCommonUtils, this.InternalCommonExpression, null);
public ISelect<T1> Select<T1>(object dywhere) where T1 : class => new SqliteSelect<T1>(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere);
public IInsert<T1> Insert<T1>() where T1 : class => new SqliteInsert<T1>(this, this.InternalCommonUtils, this.InternalCommonExpression);
public IInsert<T1> Insert<T1>(T1 source) where T1 : class => this.Insert<T1>().AppendData(source);
public IInsert<T1> Insert<T1>(IEnumerable<T1> source) where T1 : class => this.Insert<T1>().AppendData(source);
public IUpdate<T1> Update<T1>() where T1 : class => new SqliteUpdate<T1>(this, this.InternalCommonUtils, this.InternalCommonExpression, null);
public IUpdate<T1> Update<T1>(object dywhere) where T1 : class => new SqliteUpdate<T1>(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere);
public IDelete<T1> Delete<T1>() where T1 : class => new SqliteDelete<T1>(this, this.InternalCommonUtils, this.InternalCommonExpression, null);
public IDelete<T1> Delete<T1>(object dywhere) where T1 : class => new SqliteDelete<T1>(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere);
public IAdo Ado { get; }
public ICache Cache { get; }
public ICodeFirst CodeFirst { get; }
public IDbFirst DbFirst { get; }
public SqliteProvider(IDistributedCache cache, ILogger log, string masterConnectionString, string[] slaveConnectionString) {
if (log == null) log = new LoggerFactory(new[] { new Microsoft.Extensions.Logging.Debug.DebugLoggerProvider() }).CreateLogger("FreeSql.Sqlite");
this.InternalCommonUtils = new SqliteUtils(this);
this.InternalCommonExpression = new SqliteExpression(this.InternalCommonUtils);
this.Cache = new CacheProvider(cache, log);
this.Ado = new SqliteAdo(this.InternalCommonUtils, this.Cache, log, masterConnectionString, slaveConnectionString);
this.DbFirst = new SqliteDbFirst(this, this.InternalCommonUtils, this.InternalCommonExpression);
this.InternalCommonUtils.CodeFirst = this.CodeFirst = new SqliteCodeFirst(this, this.InternalCommonUtils, this.InternalCommonExpression);
}
internal CommonUtils InternalCommonUtils { get; }
internal CommonExpression InternalCommonExpression { get; }
public void Transaction(Action handler) => Ado.Transaction(handler);
public void Transaction(Action handler, TimeSpan timeout) => Ado.Transaction(handler, timeout);
}
}

View File

@ -0,0 +1,53 @@
using FreeSql.Internal;
using FreeSql.Internal.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SQLite;
namespace FreeSql.Sqlite3 {
class SqliteUtils : CommonUtils {
IFreeSql _orm;
public SqliteUtils(IFreeSql orm) {
_orm = orm;
}
internal override DbParameter AppendParamter(List<DbParameter> _params, string parameterName, Type type, object value) {
if (string.IsNullOrEmpty(parameterName)) parameterName = $"p_{_params?.Count}";
else if (_orm.CodeFirst.IsSyncStructureToLower) parameterName = parameterName.ToLower();
var dbtype = (DbType)_orm.CodeFirst.GetDbInfo(type)?.type;
if (dbtype == DbType.Time) {
if (value == null) value = null;
else value = ((TimeSpan)value).Ticks / 10000;
dbtype = DbType.Int64;
}
var ret = new SQLiteParameter { ParameterName = $"@{parameterName}", DbType = dbtype, Value = value };
_params?.Add(ret);
return ret;
}
internal override DbParameter[] GetDbParamtersByObject(string sql, object obj) =>
Utils.GetDbParamtersByObject<SQLiteParameter>(sql, obj, "@", (name, type, value) => {
var dbtype = (DbType)_orm.CodeFirst.GetDbInfo(type)?.type;
if (dbtype == DbType.Time) {
if (value == null) value = null;
else value = ((TimeSpan)value).Ticks / 10000;
dbtype = DbType.Int64;
}
var ret = new SQLiteParameter { ParameterName = $"@{name}", DbType = dbtype, Value = value };
return ret;
});
internal override string FormatSql(string sql, params object[] args) => sql?.FormatSqlite(args);
internal override string QuoteSqlName(string name) => $"\"{name.Trim('"').Replace(".", "\".\"")}\"";
internal override string QuoteParamterName(string name) => $"@{(_orm.CodeFirst.IsSyncStructureToLower ? name.ToLower() : name)}";
internal override string IsNull(string sql, object value) => $"ifnull({sql}, {value})";
internal override string StringConcat(string left, string right, Type leftType, Type rightType) => $"{left} || {right}";
internal override string Mod(string left, string right, Type leftType, Type rightType) => $"{left} % {right}";
internal override string QuoteWriteParamter(Type type, string paramterName) => paramterName;
internal override string QuoteReadColumn(Type type, string columnName) => columnName;
}
}