完成 in 查询,完成子表 exists 查询

This commit is contained in:
28810 2018-12-29 17:22:43 +08:00
parent 90bbff32a5
commit 74a6ab5859
14 changed files with 455 additions and 265 deletions

View File

@ -520,11 +520,41 @@ namespace FreeSql.Tests.MySql {
query.ToList(); query.ToList();
} }
[Fact] [Fact]
public void GroupBy() { 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] [Fact]
public void Having() { 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] [Fact]
public void OrderBy() { public void OrderBy() {
} }

View File

@ -520,10 +520,39 @@ namespace FreeSql.Tests.PostgreSQL {
query.ToList(); query.ToList();
} }
[Fact] [Fact]
public void GroupBy() { 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] [Fact]
public void Having() { 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] [Fact]
public void OrderBy() { public void OrderBy() {

View File

@ -9,11 +9,11 @@ namespace FreeSql.Tests.SqlServer {
IDelete<Topic> delete => g.sqlserver.Delete<Topic>(); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> IDelete<Topic> delete => g.sqlserver.Delete<Topic>(); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
[Table(Name = "tb_topic")] [Table(Name = "tb_topic22211")]
class Topic { class Topic {
[Column(IsIdentity = true, IsPrimary = true)] [Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; } public int Id { get; set; }
public int Clicks { get; set; } public int? Clicks { get; set; }
public TestTypeInfo Type { get; set; } public TestTypeInfo Type { get; set; }
public string Title { get; set; } public string Title { get; set; }
public DateTime CreateTime { get; set; } public DateTime CreateTime { get; set; }
@ -23,35 +23,35 @@ namespace FreeSql.Tests.SqlServer {
public void Dywhere() { public void Dywhere() {
Assert.Null(g.sqlserver.Delete<Topic>().ToSql()); Assert.Null(g.sqlserver.Delete<Topic>().ToSql());
var sql = g.sqlserver.Delete<Topic>(new[] { 1, 2 }).ToSql(); var sql = g.sqlserver.Delete<Topic>(new[] { 1, 2 }).ToSql();
Assert.Equal("DELETE FROM [tb_topic] WHERE ([Id] = 1 OR [Id] = 2)", sql); Assert.Equal("DELETE FROM [tb_topic22211] WHERE ([Id] = 1 OR [Id] = 2)", sql);
sql = g.sqlserver.Delete<Topic>(new Topic { Id = 1, Title = "test" }).ToSql(); sql = g.sqlserver.Delete<Topic>(new Topic { Id = 1, Title = "test" }).ToSql();
Assert.Equal("DELETE FROM [tb_topic] WHERE ([Id] = 1)", sql); Assert.Equal("DELETE FROM [tb_topic22211] WHERE ([Id] = 1)", sql);
sql = g.sqlserver.Delete<Topic>(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).ToSql(); sql = g.sqlserver.Delete<Topic>(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).ToSql();
Assert.Equal("DELETE FROM [tb_topic] WHERE ([Id] = 1 OR [Id] = 2)", sql); Assert.Equal("DELETE FROM [tb_topic22211] WHERE ([Id] = 1 OR [Id] = 2)", sql);
sql = g.sqlserver.Delete<Topic>(new { id = 1 }).ToSql(); sql = g.sqlserver.Delete<Topic>(new { id = 1 }).ToSql();
Assert.Equal("DELETE FROM [tb_topic] WHERE ([Id] = 1)", sql); Assert.Equal("DELETE FROM [tb_topic22211] WHERE ([Id] = 1)", sql);
} }
[Fact] [Fact]
public void Where() { public void Where() {
var sql = delete.Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); var sql = delete.Where(a => a.Id == 1).ToSql().Replace("\r\n", "");
Assert.Equal("DELETE FROM [tb_topic] WHERE ([Id] = 1)", sql); Assert.Equal("DELETE FROM [tb_topic22211] WHERE ([Id] = 1)", sql);
sql = delete.Where("id = ?id", new { id = 1 }).ToSql().Replace("\r\n", ""); sql = delete.Where("id = ?id", new { id = 1 }).ToSql().Replace("\r\n", "");
Assert.Equal("DELETE FROM [tb_topic] WHERE (id = ?id)", sql); Assert.Equal("DELETE FROM [tb_topic22211] WHERE (id = ?id)", sql);
var item = new Topic { Id = 1, Title = "newtitle" }; var item = new Topic { Id = 1, Title = "newtitle" };
sql = delete.Where(item).ToSql().Replace("\r\n", ""); sql = delete.Where(item).ToSql().Replace("\r\n", "");
Assert.Equal("DELETE FROM [tb_topic] WHERE ([Id] = 1)", sql); Assert.Equal("DELETE FROM [tb_topic22211] WHERE ([Id] = 1)", sql);
var items = new List<Topic>(); 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 }); 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", ""); sql = delete.Where(items).ToSql().Replace("\r\n", "");
Assert.Equal("DELETE FROM [tb_topic] WHERE ([Id] IN (1,2,3,4,5,6,7,8,9,10))", sql); Assert.Equal("DELETE FROM [tb_topic22211] WHERE ([Id] IN (1,2,3,4,5,6,7,8,9,10))", sql);
} }
[Fact] [Fact]
public void WhereExists() { public void WhereExists() {

View File

@ -443,10 +443,39 @@ namespace FreeSql.Tests.SqlServer {
query.ToList(); query.ToList();
} }
[Fact] [Fact]
public void GroupBy() { 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] [Fact]
public void Having() { 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] [Fact]
public void OrderBy() { public void OrderBy() {

View File

@ -20,6 +20,16 @@ namespace FreeSql.Tests {
[Fact] [Fact]
public void Test1() { public void Test1() {
var sql2222 = select.Where(a =>
select.Where(b => b.Id == a.Id && select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id)
.Offset(a.Id)
.Any()
).Any()
).ToSql();
var groupby = g.mysql.Select<TestInfo>().From<TestTypeInfo, TestTypeParentInfo>((s, b, c) => s var groupby = g.mysql.Select<TestInfo>().From<TestTypeInfo, TestTypeParentInfo>((s, b, c) => s
.Where(a => a.Id == 1) .Where(a => a.Id == 1)
) )
@ -28,7 +38,7 @@ namespace FreeSql.Tests {
.Having(a => a.Count() < 300 || a.Avg(a.Key.mod4) < 100) .Having(a => a.Count() < 300 || a.Avg(a.Key.mod4) < 100)
.OrderBy(a => a.Key.tt2) .OrderBy(a => a.Key.tt2)
.OrderByDescending(a => a.Count()) .OrderByDescending(a => a.Count())
.ToList(a => new { a.Key.tt2, cou1 = a.Count(), arg1 = a.Avg(a.Key.mod4), .ToSql(a => new { a.Key.tt2, cou1 = a.Count(), arg1 = a.Avg(a.Key.mod4),
ccc2 = a.Key.tt2 ?? "now()", 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)") //ccc = Convert.ToDateTime("now()"), partby = Convert.ToDecimal("sum(num) over(PARTITION BY server_id,os,rid,chn order by id desc)")
}); });

View File

@ -3,7 +3,7 @@
<PropertyGroup> <PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework> <TargetFramework>netstandard2.0</TargetFramework>
<AssemblyVersion>0.0.0.1</AssemblyVersion> <AssemblyVersion>0.0.0.1</AssemblyVersion>
<Version>0.0.3</Version> <Version>0.0.4</Version>
<FileVersion>0.0.0.0</FileVersion> <FileVersion>0.0.0.0</FileVersion>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild> <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
</PropertyGroup> </PropertyGroup>

View File

@ -3,6 +3,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Reflection;
using System.Text; using System.Text;
namespace FreeSql.Internal { namespace FreeSql.Internal {
@ -223,6 +224,67 @@ namespace FreeSql.Internal {
case "Min": return $"min({ExpressionLambdaToSql(exp3.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Min": return $"min({ExpressionLambdaToSql(exp3.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})";
} }
} }
if (callType.FullName.StartsWith("FreeSql.ISelect`")) { //子表查询
if (exp3.Method.Name == "Any") { //exists
var exp3Stack = new Stack<Expression>();
var exp3tmp = exp3.Object;
while (exp3tmp != null) {
exp3Stack.Push(exp3tmp);
switch (exp3tmp.NodeType) {
case ExpressionType.Call: exp3tmp = (exp3tmp as MethodCallExpression).Object; continue;
case ExpressionType.MemberAccess: exp3tmp = (exp3tmp as MemberExpression).Expression; continue;
}
break;
}
object fsql = null;
List<SelectTableInfo> fsqltables = null;
var fsqltable1SetAlias = false;
Type fsqlType = null;
while (exp3Stack.Any()) {
exp3tmp = exp3Stack.Pop();
if (exp3tmp.Type.FullName.StartsWith("FreeSql.ISelect`") && fsql == null) {
fsql = Expression.Lambda(exp3tmp).Compile().DynamicInvoke();
fsqlType = fsql?.GetType();
if (fsqlType == null) break;
fsqlType.GetField("_limit", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(fsql, 1);
fsqltables = fsqlType.GetField("_tables", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(fsql) as List<SelectTableInfo>;
//fsqltables[0].Alias = $"{_tables[0].Alias}_{fsqltables[0].Alias}";
fsqltables.AddRange(_tables.Select(a => new SelectTableInfo {
Alias = a.Type == SelectTableInfoType.Parent ? a.Alias : $"__parent_{a.Alias}_parent__",
On = "1=1",
Table = a.Table,
Type = SelectTableInfoType.Parent
}));
} else if (fsqlType != null) {
var call3Exp = exp3tmp as MethodCallExpression;
var method = fsqlType.GetMethod(call3Exp.Method.Name, call3Exp.Arguments.Select(a => a.Type).ToArray());
if (call3Exp.Method.ContainsGenericParameters) method.MakeGenericMethod(call3Exp.Method.GetGenericArguments());
var parms = method.GetParameters();
var args = new object[call3Exp.Arguments.Count];
for (var a = 0; a < args.Length; a++) {
var argExp = (call3Exp.Arguments[a] as UnaryExpression)?.Operand;
if (argExp != null && argExp.NodeType == ExpressionType.Lambda) {
if (fsqltable1SetAlias == false) {
fsqltables[0].Alias = (argExp as LambdaExpression).Parameters.First().Name;
fsqltable1SetAlias = true;
}
}
args[a] = argExp;
//if (args[a] == null) ExpressionLambdaToSql(call3Exp.Arguments[a], fsqltables, null, null, SelectTableInfoType.From, true);
}
method.Invoke(fsql, args);
}
}
if (fsql != null) {
var sql = fsqlType.GetMethod("ToSql", new Type[] { typeof(string) })?.Invoke(fsql, new object[] { "1" })?.ToString();
if (string.IsNullOrEmpty(sql) == false) {
foreach (var tb in _tables)
sql = sql.Replace($"__parent_{tb.Alias}_parent__", tb.Alias);
return $"exists({sql})";
}
}
}
}
var other3Exp = ExpressionLambdaToSqlOther(exp3, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var other3Exp = ExpressionLambdaToSqlOther(exp3, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName);
if (string.IsNullOrEmpty(other3Exp) == false) return other3Exp; if (string.IsNullOrEmpty(other3Exp) == false) return other3Exp;
throw new Exception($"未现实函数表达式 {exp3} 解析"); throw new Exception($"未现实函数表达式 {exp3} 解析");
@ -287,6 +349,19 @@ namespace FreeSql.Internal {
if (isQuoteName) name = _common.QuoteSqlName(name); if (isQuoteName) name = _common.QuoteSqlName(name);
return name; return name;
} }
Func<TableInfo, string, SelectTableInfo> getOrAddTable = (tbtmp, alias) => {
var finds = _tables.Where((a2, c2) => a2.Table.CsName == tbtmp.CsName).ToArray(); //外部表,内部表一起查
if (finds.Length > 1) {
finds = _tables.Where((a2, c2) => a2.Table.CsName == tbtmp.CsName && a2.Type == SelectTableInfoType.Parent && a2.Alias == $"__parent_{alias}_parent__").ToArray(); //查询外部表
if (finds.Any() == false) {
finds = _tables.Where((a2, c2) => a2.Table.CsName == tbtmp.CsName && a2.Type != SelectTableInfoType.Parent).ToArray(); //查询内部表
if (finds.Length > 1) finds = _tables.Where((a2, c2) => a2.Table.CsName == tbtmp.CsName && a2.Type != SelectTableInfoType.Parent && a2.Alias == alias).ToArray();
}
}
var find = finds.FirstOrDefault();
if (find == null) _tables.Add(find = new SelectTableInfo { Table = tbtmp, Alias = alias, On = null, Type = tbtype });
return find;
};
TableInfo tb2 = null; TableInfo tb2 = null;
string alias2 = "", name2 = ""; string alias2 = "", name2 = "";
@ -298,6 +373,7 @@ namespace FreeSql.Internal {
throw new NotImplementedException("未现实 MemberAccess 下的 Constant"); throw new NotImplementedException("未现实 MemberAccess 下的 Constant");
case ExpressionType.Parameter: case ExpressionType.Parameter:
case ExpressionType.MemberAccess: case ExpressionType.MemberAccess:
var exp2Type = exp2.Type; var exp2Type = exp2.Type;
if (exp2Type.FullName.StartsWith("FreeSql.ISelectGroupingAggregate`")) exp2Type = exp2Type.GenericTypeArguments.FirstOrDefault() ?? exp2.Type; if (exp2Type.FullName.StartsWith("FreeSql.ISelectGroupingAggregate`")) exp2Type = exp2Type.GenericTypeArguments.FirstOrDefault() ?? exp2.Type;
var tb2tmp = _common.GetTableByEntity(exp2Type); var tb2tmp = _common.GetTableByEntity(exp2Type);
@ -306,10 +382,7 @@ namespace FreeSql.Internal {
if (tb2tmp != null) { if (tb2tmp != null) {
if (exp2.NodeType == ExpressionType.Parameter) alias2 = (exp2 as ParameterExpression).Name; if (exp2.NodeType == ExpressionType.Parameter) alias2 = (exp2 as ParameterExpression).Name;
else alias2 = $"{alias2}__{mp2.Member.Name}"; else alias2 = $"{alias2}__{mp2.Member.Name}";
var find2s = _tables.Where((a2, c2) => a2.Table.CsName == tb2tmp.CsName).ToArray(); find2 = getOrAddTable(tb2tmp, alias2);
if (find2s.Length > 1) find2s = _tables.Where((a2, c2) => a2.Table.CsName == tb2tmp.CsName && a2.Alias == alias2).ToArray();
find2 = find2s.FirstOrDefault();
if (find2 == null) _tables.Add(find2 = new SelectTableInfo { Table = tb2tmp, Alias = alias2, On = null, Type = tbtype });
alias2 = find2.Alias; alias2 = find2.Alias;
tb2 = tb2tmp; tb2 = tb2tmp;
} }
@ -318,12 +391,7 @@ namespace FreeSql.Internal {
if (_selectColumnMap != null) { if (_selectColumnMap != null) {
var tb3 = _common.GetTableByEntity(mp2.Type); var tb3 = _common.GetTableByEntity(mp2.Type);
if (tb3 != null) { if (tb3 != null) {
var alias3 = $"{alias2}__{mp2.Member.Name}"; var find3 = getOrAddTable(tb2tmp, $"{alias2}__{mp2.Member.Name}");
var find3s = _tables.Where((a3, c3) => a3.Table.CsName == tb3.CsName).ToArray();
if (find3s.Length > 1) find3s = _tables.Where((a3, c3) => a3.Table.CsName == tb3.CsName && a3.Alias == alias3).ToArray();
var find3 = find3s.FirstOrDefault();
if (find3 == null) _tables.Add(find3 = new SelectTableInfo { Table = tb3, Alias = alias3, On = null, Type = tbtype });
alias3 = find3.Alias;
foreach (var tb3c in tb3.Columns.Values) foreach (var tb3c in tb3.Columns.Values)
_selectColumnMap.Add(new SelectColumnInfo { Table = find3, Column = tb3c }); _selectColumnMap.Add(new SelectColumnInfo { Table = find3, Column = tb3c });

View File

@ -5,5 +5,5 @@
public string On { get; set; } public string On { get; set; }
public SelectTableInfoType Type { get; set; } public SelectTableInfoType Type { get; set; }
} }
enum SelectTableInfoType { From, LeftJoin, InnerJoin, RightJoin } enum SelectTableInfoType { From, LeftJoin, InnerJoin, RightJoin, Parent }
} }

View File

@ -29,6 +29,7 @@ namespace FreeSql.MySql.Curd {
if (a < tbsfrom.Length - 1) sb.Append(", "); if (a < tbsfrom.Length - 1) sb.Append(", ");
} }
foreach (var tb in tbsjoin) { foreach (var tb in tbsjoin) {
if (tb.Type == SelectTableInfoType.Parent) continue;
switch (tb.Type) { switch (tb.Type) {
case SelectTableInfoType.LeftJoin: case SelectTableInfoType.LeftJoin:
sb.Append(" \r\nLEFT JOIN "); sb.Append(" \r\nLEFT JOIN ");
@ -46,6 +47,7 @@ namespace FreeSql.MySql.Curd {
var sbqf = new StringBuilder(); var sbqf = new StringBuilder();
foreach (var tb in _tables) { foreach (var tb in _tables) {
if (tb.Type == SelectTableInfoType.Parent) continue;
if (string.IsNullOrEmpty(tb.Table.SelectFilter) == false) if (string.IsNullOrEmpty(tb.Table.SelectFilter) == false)
sbqf.Append(" AND (").Append(tb.Table.SelectFilter.Replace("a.", $"{tb.Alias}.")).Append(")"); sbqf.Append(" AND (").Append(tb.Table.SelectFilter.Replace("a.", $"{tb.Alias}.")).Append(")");
} }

View File

@ -12,6 +12,7 @@ namespace FreeSql.MySql {
public MySqlExpression(CommonUtils common) : base(common) { } public MySqlExpression(CommonUtils common) : base(common) { }
internal override string ExpressionLambdaToSqlOther(Expression exp, List<SelectTableInfo> _tables, List<SelectColumnInfo> _selectColumnMap, Func<Expression[], string> getSelectGroupingMapString, SelectTableInfoType tbtype, bool isQuoteName) { 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) { switch (exp.NodeType) {
case ExpressionType.Call: case ExpressionType.Call:
var callExp = exp as MethodCallExpression; var callExp = exp as MethodCallExpression;
@ -27,12 +28,12 @@ namespace FreeSql.MySql {
} }
if (objType == null) objType = callExp.Method.DeclaringType; if (objType == null) objType = callExp.Method.DeclaringType;
if (objType != null) { if (objType != null) {
var left = objExp == null ? null : ExpressionLambdaToSql(objExp, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var left = objExp == null ? null : getExp(objExp);
if (objType.IsArray == true) { if (objType.IsArray == true) {
switch (callExp.Method.Name) { switch (callExp.Method.Name) {
case "Contains": case "Contains":
//判断 in //判断 in
return $"({ExpressionLambdaToSql(callExp.Arguments[argIndex], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}) in {left}"; return $"({getExp(callExp.Arguments[argIndex])}) in {left}";
} }
} }
} }
@ -43,7 +44,7 @@ namespace FreeSql.MySql {
arrSb.Append("("); arrSb.Append("(");
for (var a = 0; a < arrExp.Expressions.Count; a++) { for (var a = 0; a < arrExp.Expressions.Count; a++) {
if (a > 0) arrSb.Append(","); if (a > 0) arrSb.Append(",");
arrSb.Append(ExpressionLambdaToSql(arrExp.Expressions[a], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)); arrSb.Append(getExp(arrExp.Expressions[a]));
} }
return arrSb.Append(")").ToString(); return arrSb.Append(")").ToString();
} }
@ -118,19 +119,20 @@ namespace FreeSql.MySql {
} }
internal override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, List<SelectTableInfo> _tables, List<SelectColumnInfo> _selectColumnMap, Func<Expression[], string> getSelectGroupingMapString, SelectTableInfoType tbtype, bool isQuoteName) { 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) { if (exp.Object == null) {
switch (exp.Method.Name) { switch (exp.Method.Name) {
case "IsNullOrEmpty": case "IsNullOrEmpty":
var arg1 = ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var arg1 = getExp(exp.Arguments[0]);
return $"({arg1} is null or {arg1} = '')"; return $"({arg1} is null or {arg1} = '')";
} }
} else { } else {
var left = ExpressionLambdaToSql(exp.Object, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var left = getExp(exp.Object);
switch (exp.Method.Name) { switch (exp.Method.Name) {
case "StartsWith": case "StartsWith":
case "EndsWith": case "EndsWith":
case "Contains": case "Contains":
var args0Value = ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var args0Value = getExp(exp.Arguments[0]);
if (args0Value == "NULL") return $"({left}) IS NULL"; 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 == "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 (exp.Method.Name == "EndsWith") return $"({left}) LIKE {(args0Value.StartsWith("'") ? args0Value.Insert(1, "%") : $"concat('%', {args0Value})")}";
@ -139,26 +141,26 @@ namespace FreeSql.MySql {
case "ToLower": return $"lower({left})"; case "ToLower": return $"lower({left})";
case "ToUpper": return $"upper({left})"; case "ToUpper": return $"upper({left})";
case "Substring": case "Substring":
var substrArgs1 = ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var substrArgs1 = getExp(exp.Arguments[0]);
if (long.TryParse(substrArgs1, out var testtrylng1)) substrArgs1 = (testtrylng1 + 1).ToString(); if (long.TryParse(substrArgs1, out var testtrylng1)) substrArgs1 = (testtrylng1 + 1).ToString();
else substrArgs1 += "+1"; else substrArgs1 += "+1";
if (exp.Arguments.Count == 1) return $"substr({left}, {substrArgs1})"; if (exp.Arguments.Count == 1) return $"substr({left}, {substrArgs1})";
return $"substr({left}, {substrArgs1}, {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; return $"substr({left}, {substrArgs1}, {getExp(exp.Arguments[1])})";
case "IndexOf": case "IndexOf":
var indexOfFindStr = ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var indexOfFindStr = getExp(exp.Arguments[0]);
if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") { if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") {
var locateArgs1 = ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var locateArgs1 = getExp(exp.Arguments[1]);
if (long.TryParse(locateArgs1, out var testtrylng2)) locateArgs1 = (testtrylng2 + 1).ToString(); if (long.TryParse(locateArgs1, out var testtrylng2)) locateArgs1 = (testtrylng2 + 1).ToString();
else locateArgs1 += "+1"; else locateArgs1 += "+1";
return $"(locate({left}, {indexOfFindStr}, {locateArgs1})-1)"; return $"(locate({left}, {indexOfFindStr}, {locateArgs1})-1)";
} }
return $"(locate({left}, {indexOfFindStr})-1)"; return $"(locate({left}, {indexOfFindStr})-1)";
case "PadLeft": case "PadLeft":
if (exp.Arguments.Count == 1) return $"lpad({left}, {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; if (exp.Arguments.Count == 1) return $"lpad({left}, {getExp(exp.Arguments[0])})";
return $"lpad({left}, {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}, {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; return $"lpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
case "PadRight": case "PadRight":
if (exp.Arguments.Count == 1) return $"rpad({left}, {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; if (exp.Arguments.Count == 1) return $"rpad({left}, {getExp(exp.Arguments[0])})";
return $"rpad({left}, {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}, {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; return $"rpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
case "Trim": case "Trim":
case "TrimStart": case "TrimStart":
case "TrimEnd": case "TrimEnd":
@ -174,63 +176,65 @@ namespace FreeSql.MySql {
argsTrim01s = arritem.Expressions.ToArray(); argsTrim01s = arritem.Expressions.ToArray();
} }
foreach (var argsTrim01 in argsTrim01s) { foreach (var argsTrim01 in argsTrim01s) {
if (exp.Method.Name == "Trim") left = $"trim({ExpressionLambdaToSql(argsTrim01, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} from {left})"; if (exp.Method.Name == "Trim") left = $"trim({getExp(argsTrim01)} from {left})";
if (exp.Method.Name == "TrimStart") left = $"trim(leading {ExpressionLambdaToSql(argsTrim01, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} from {left})"; if (exp.Method.Name == "TrimStart") left = $"trim(leading {getExp(argsTrim01)} from {left})";
if (exp.Method.Name == "TrimEnd") left = $"trim(trailing {ExpressionLambdaToSql(argsTrim01, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} from {left})"; if (exp.Method.Name == "TrimEnd") left = $"trim(trailing {getExp(argsTrim01)} from {left})";
} }
} }
return left; return left;
case "Replace": return $"replace({left}, {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}, {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Replace": return $"replace({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
case "CompareTo": return $"strcmp({left}, {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "CompareTo": return $"strcmp({left}, {getExp(exp.Arguments[0])})";
case "Equals": return $"({left} = {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Equals": return $"({left} = {getExp(exp.Arguments[0])})";
} }
} }
throw new Exception($"MySqlExpression 未现实函数表达式 {exp} 解析"); 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) { 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) { switch (exp.Method.Name) {
case "Abs": return $"abs({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Abs": return $"abs({getExp(exp.Arguments[0])})";
case "Sign": return $"sign({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Sign": return $"sign({getExp(exp.Arguments[0])})";
case "Floor": return $"floor({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Floor": return $"floor({getExp(exp.Arguments[0])})";
case "Ceiling": return $"ceiling({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Ceiling": return $"ceiling({getExp(exp.Arguments[0])})";
case "Round": case "Round":
if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") return $"round({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}, {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") return $"round({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
return $"round({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; return $"round({getExp(exp.Arguments[0])})";
case "Exp": return $"exp({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Exp": return $"exp({getExp(exp.Arguments[0])})";
case "Log": return $"log({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Log": return $"log({getExp(exp.Arguments[0])})";
case "Log10": return $"log10({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Log10": return $"log10({getExp(exp.Arguments[0])})";
case "Pow": return $"pow({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}, {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Pow": return $"pow({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
case "Sqrt": return $"sqrt({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Sqrt": return $"sqrt({getExp(exp.Arguments[0])})";
case "Cos": return $"cos({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Cos": return $"cos({getExp(exp.Arguments[0])})";
case "Sin": return $"sin({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Sin": return $"sin({getExp(exp.Arguments[0])})";
case "Tan": return $"tan({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Tan": return $"tan({getExp(exp.Arguments[0])})";
case "Acos": return $"acos({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Acos": return $"acos({getExp(exp.Arguments[0])})";
case "Asin": return $"asin({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Asin": return $"asin({getExp(exp.Arguments[0])})";
case "Atan": return $"atan({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Atan": return $"atan({getExp(exp.Arguments[0])})";
case "Atan2": return $"atan2({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}, {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Atan2": return $"atan2({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
case "Truncate": return $"truncate({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}, 0)"; case "Truncate": return $"truncate({getExp(exp.Arguments[0])}, 0)";
} }
throw new Exception($"MySqlExpression 未现实函数表达式 {exp} 解析"); 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) { 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) { if (exp.Object == null) {
switch (exp.Method.Name) { switch (exp.Method.Name) {
case "Compare": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} - ({ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}))"; case "Compare": return $"({getExp(exp.Arguments[0])} - ({getExp(exp.Arguments[1])}))";
case "DaysInMonth": return $"dayofmonth(last_day(concat({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}, '-', {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}, '-01')))"; case "DaysInMonth": return $"dayofmonth(last_day(concat({getExp(exp.Arguments[0])}, '-', {getExp(exp.Arguments[1])}, '-01')))";
case "Equals": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} = {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})";
case "IsLeapYear": case "IsLeapYear":
var isLeapYearArgs1 = ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var isLeapYearArgs1 = getExp(exp.Arguments[0]);
return $"(({isLeapYearArgs1})%4=0 AND ({isLeapYearArgs1})%100<>0 OR ({isLeapYearArgs1})%400=0)"; return $"(({isLeapYearArgs1})%4=0 AND ({isLeapYearArgs1})%100<>0 OR ({isLeapYearArgs1})%400=0)";
case "Parse": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as datetime)"; case "Parse": return $"cast({getExp(exp.Arguments[0])} as datetime)";
case "ParseExact": case "ParseExact":
case "TryParse": case "TryParse":
case "TryParseExact": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as datetime)"; case "TryParseExact": return $"cast({getExp(exp.Arguments[0])} as datetime)";
} }
} else { } else {
var left = ExpressionLambdaToSql(exp.Object, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var left = getExp(exp.Object);
var args1 = exp.Arguments.Count == 0 ? null : ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]);
switch (exp.Method.Name) { switch (exp.Method.Name) {
case "Add": return $"date_add({left}, interval ({args1}) microsecond)"; case "Add": return $"date_add({left}, interval ({args1}) microsecond)";
case "AddDays": return $"date_add({left}, interval ({args1}) day)"; case "AddDays": return $"date_add({left}, interval ({args1}) day)";
@ -247,60 +251,62 @@ namespace FreeSql.MySql {
if (exp.Arguments[0].Type.FullName == "System.TimeSpan" || exp.Arguments[0].Type.GenericTypeArguments.FirstOrDefault()?.FullName == "System.TimeSpan") if (exp.Arguments[0].Type.FullName == "System.TimeSpan" || exp.Arguments[0].Type.GenericTypeArguments.FirstOrDefault()?.FullName == "System.TimeSpan")
return $"date_sub({left}, interval ({args1}) microsecond)"; return $"date_sub({left}, interval ({args1}) microsecond)";
break; break;
case "Equals": return $"({left} = {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Equals": return $"({left} = {getExp(exp.Arguments[0])})";
case "CompareTo": return $"(({left}) - ({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}))"; case "CompareTo": return $"(({left}) - ({getExp(exp.Arguments[0])}))";
case "ToString": return $"date_format({left}, '%Y-%m-%d %H:%i:%s.%f')"; case "ToString": return $"date_format({left}, '%Y-%m-%d %H:%i:%s.%f')";
} }
} }
throw new Exception($"MySqlExpression 未现实函数表达式 {exp} 解析"); 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) { 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) { if (exp.Object == null) {
switch (exp.Method.Name) { switch (exp.Method.Name) {
case "Compare": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}-({ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}))"; case "Compare": return $"({getExp(exp.Arguments[0])}-({getExp(exp.Arguments[1])}))";
case "Equals": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} = {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})";
case "FromDays": return $"(({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})*{(long)1000000 * 60 * 60 * 24})"; case "FromDays": return $"(({getExp(exp.Arguments[0])})*{(long)1000000 * 60 * 60 * 24})";
case "FromHours": return $"(({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})*{(long)1000000 * 60 * 60})"; case "FromHours": return $"(({getExp(exp.Arguments[0])})*{(long)1000000 * 60 * 60})";
case "FromMilliseconds": return $"(({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})*1000)"; case "FromMilliseconds": return $"(({getExp(exp.Arguments[0])})*1000)";
case "FromMinutes": return $"(({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})*{(long)1000000 * 60})"; case "FromMinutes": return $"(({getExp(exp.Arguments[0])})*{(long)1000000 * 60})";
case "FromSeconds": return $"(({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})*1000000)"; case "FromSeconds": return $"(({getExp(exp.Arguments[0])})*1000000)";
case "FromTicks": return $"(({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})/10)"; case "FromTicks": return $"(({getExp(exp.Arguments[0])})/10)";
case "Parse": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as signed)"; case "Parse": return $"cast({getExp(exp.Arguments[0])} as signed)";
case "ParseExact": case "ParseExact":
case "TryParse": case "TryParse":
case "TryParseExact": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as signed)"; case "TryParseExact": return $"cast({getExp(exp.Arguments[0])} as signed)";
} }
} else { } else {
var left = ExpressionLambdaToSql(exp.Object, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var left = getExp(exp.Object);
var args1 = exp.Arguments.Count == 0 ? null : ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]);
switch (exp.Method.Name) { switch (exp.Method.Name) {
case "Add": return $"({left}+{args1})"; case "Add": return $"({left}+{args1})";
case "Subtract": return $"({left}-({args1}))"; case "Subtract": return $"({left}-({args1}))";
case "Equals": return $"({left} = {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Equals": return $"({left} = {getExp(exp.Arguments[0])})";
case "CompareTo": return $"({left}-({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}))"; case "CompareTo": return $"({left}-({getExp(exp.Arguments[0])}))";
case "ToString": return $"cast({left} as char)"; case "ToString": return $"cast({left} as char)";
} }
} }
throw new Exception($"MySqlExpression 未现实函数表达式 {exp} 解析"); 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) { 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) { if (exp.Object == null) {
switch (exp.Method.Name) { switch (exp.Method.Name) {
case "ToBoolean": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} not in ('0','false'))"; case "ToBoolean": return $"({getExp(exp.Arguments[0])} not in ('0','false'))";
case "ToByte": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as unsigned)"; case "ToByte": return $"cast({getExp(exp.Arguments[0])} as unsigned)";
case "ToChar": return $"substr(cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as char), 1, 1)"; case "ToChar": return $"substr(cast({getExp(exp.Arguments[0])} as char), 1, 1)";
case "ToDateTime": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as datetime)"; case "ToDateTime": return $"cast({getExp(exp.Arguments[0])} as datetime)";
case "ToDecimal": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as decimal(36,18))"; case "ToDecimal": return $"cast({getExp(exp.Arguments[0])} as decimal(36,18))";
case "ToDouble": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as decimal(32,16))"; case "ToDouble": return $"cast({getExp(exp.Arguments[0])} as decimal(32,16))";
case "ToInt16": case "ToInt16":
case "ToInt32": case "ToInt32":
case "ToInt64": case "ToInt64":
case "ToSByte": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as signed)"; case "ToSByte": return $"cast({getExp(exp.Arguments[0])} as signed)";
case "ToSingle": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as decimal(14,7))"; case "ToSingle": return $"cast({getExp(exp.Arguments[0])} as decimal(14,7))";
case "ToString": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as char)"; case "ToString": return $"cast({getExp(exp.Arguments[0])} as char)";
case "ToUInt16": case "ToUInt16":
case "ToUInt32": case "ToUInt32":
case "ToUInt64": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as unsigned)"; case "ToUInt64": return $"cast({getExp(exp.Arguments[0])} as unsigned)";
} }
} }
throw new Exception($"MySqlExpression 未现实函数表达式 {exp} 解析"); throw new Exception($"MySqlExpression 未现实函数表达式 {exp} 解析");

View File

@ -29,6 +29,7 @@ namespace FreeSql.PostgreSQL.Curd {
if (a < tbsfrom.Length - 1) sb.Append(", "); if (a < tbsfrom.Length - 1) sb.Append(", ");
} }
foreach (var tb in tbsjoin) { foreach (var tb in tbsjoin) {
if (tb.Type == SelectTableInfoType.Parent) continue;
switch (tb.Type) { switch (tb.Type) {
case SelectTableInfoType.LeftJoin: case SelectTableInfoType.LeftJoin:
sb.Append(" \r\nLEFT JOIN "); sb.Append(" \r\nLEFT JOIN ");
@ -46,6 +47,7 @@ namespace FreeSql.PostgreSQL.Curd {
var sbqf = new StringBuilder(); var sbqf = new StringBuilder();
foreach (var tb in _tables) { foreach (var tb in _tables) {
if (tb.Type == SelectTableInfoType.Parent) continue;
if (string.IsNullOrEmpty(tb.Table.SelectFilter) == false) if (string.IsNullOrEmpty(tb.Table.SelectFilter) == false)
sbqf.Append(" AND (").Append(tb.Table.SelectFilter.Replace("a.", $"{tb.Alias}.")).Append(")"); sbqf.Append(" AND (").Append(tb.Table.SelectFilter.Replace("a.", $"{tb.Alias}.")).Append(")");
} }

View File

@ -13,9 +13,10 @@ namespace FreeSql.PostgreSQL {
public PostgreSQLExpression(CommonUtils common) : base(common) { } public PostgreSQLExpression(CommonUtils common) : base(common) { }
internal override string ExpressionLambdaToSqlOther(Expression exp, List<SelectTableInfo> _tables, List<SelectColumnInfo> _selectColumnMap, Func<Expression[], string> getSelectGroupingMapString, SelectTableInfoType tbtype, bool isQuoteName) { 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) { switch (exp.NodeType) {
case ExpressionType.ArrayLength: case ExpressionType.ArrayLength:
var arrOperExp = ExpressionLambdaToSql((exp as UnaryExpression).Operand, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var arrOperExp = getExp((exp as UnaryExpression));
if (arrOperExp.StartsWith("(") || arrOperExp.EndsWith(")")) return $"array_length(array[{arrOperExp.TrimStart('(').TrimEnd(')')}],1)"; if (arrOperExp.StartsWith("(") || arrOperExp.EndsWith(")")) return $"array_length(array[{arrOperExp.TrimStart('(').TrimEnd(')')}],1)";
return $"case when {arrOperExp} is null then 0 else array_length({arrOperExp},1) end"; return $"case when {arrOperExp} is null then 0 else array_length({arrOperExp},1) end";
case ExpressionType.Call: case ExpressionType.Call:
@ -32,7 +33,7 @@ namespace FreeSql.PostgreSQL {
} }
if (objType == null) objType = callExp.Method.DeclaringType; if (objType == null) objType = callExp.Method.DeclaringType;
if (objType != null) { if (objType != null) {
var left = objExp == null ? null : ExpressionLambdaToSql(objExp, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var left = objExp == null ? null : getExp(objExp);
if (objType.IsArray == true) { if (objType.IsArray == true) {
switch (callExp.Method.Name) { switch (callExp.Method.Name) {
case "Any": case "Any":
@ -40,7 +41,7 @@ namespace FreeSql.PostgreSQL {
return $"(case when {left} is null then 0 else array_length({left},1) end > 0)"; return $"(case when {left} is null then 0 else array_length({left},1) end > 0)";
case "Contains": case "Contains":
//判断 in 或 array @> array //判断 in 或 array @> array
var right1 = ExpressionLambdaToSql(callExp.Arguments[argIndex], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var right1 = getExp(callExp.Arguments[argIndex]);
if (left.StartsWith("array[") || left.EndsWith("]")) if (left.StartsWith("array[") || left.EndsWith("]"))
return $"{right1} in ({left.Substring(6, left.Length - 7)})"; return $"{right1} in ({left.Substring(6, left.Length - 7)})";
if (left.StartsWith("(") || left.EndsWith(")")) if (left.StartsWith("(") || left.EndsWith(")"))
@ -49,7 +50,7 @@ namespace FreeSql.PostgreSQL {
return $"({left} @> array[{right1}])"; return $"({left} @> array[{right1}])";
case "Concat": case "Concat":
if (left.StartsWith("(") || left.EndsWith(")")) left = $"array[{left.TrimStart('(').TrimEnd(')')}]"; if (left.StartsWith("(") || left.EndsWith(")")) left = $"array[{left.TrimStart('(').TrimEnd(')')}]";
var right2 = ExpressionLambdaToSql(callExp.Arguments[argIndex], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var right2 = getExp(callExp.Arguments[argIndex]);
if (right2.StartsWith("(") || right2.EndsWith(")")) right2 = $"array[{right2.TrimStart('(').TrimEnd(')')}]"; if (right2.StartsWith("(") || right2.EndsWith(")")) right2 = $"array[{right2.TrimStart('(').TrimEnd(')')}]";
return $"({left} || {right2})"; return $"({left} || {right2})";
case "GetLength": case "GetLength":
@ -67,17 +68,17 @@ namespace FreeSql.PostgreSQL {
switch (callExp.Method.Name) { switch (callExp.Method.Name) {
case "Any": return $"(jsonb_array_length(coalesce({left},'[]')) > 0)"; case "Any": return $"(jsonb_array_length(coalesce({left},'[]')) > 0)";
case "Contains": case "Contains":
var json = ExpressionLambdaToSql(callExp.Arguments[argIndex], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var json = getExp(callExp.Arguments[argIndex]);
if (json.StartsWith("'") && json.EndsWith("'")) return $"(coalesce({left},'{{}}') @> {_common.FormatSql("{0}", JToken.Parse(json.Trim('\'')))})"; if (json.StartsWith("'") && json.EndsWith("'")) return $"(coalesce({left},'{{}}') @> {_common.FormatSql("{0}", JToken.Parse(json.Trim('\'')))})";
return $"(coalesce({left},'{{}}') @> ({json})::jsonb)"; return $"(coalesce({left},'{{}}') @> ({json})::jsonb)";
case "ContainsKey": return $"(coalesce({left},'{{}}') ? {ExpressionLambdaToSql(callExp.Arguments[argIndex], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "ContainsKey": return $"(coalesce({left},'{{}}') ? {getExp(callExp.Arguments[argIndex])})";
case "Concat": case "Concat":
var right2 = ExpressionLambdaToSql(callExp.Arguments[argIndex], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var right2 = getExp(callExp.Arguments[argIndex]);
return $"(coalesce({left},'{{}}') || {right2})"; return $"(coalesce({left},'{{}}') || {right2})";
case "LongCount": case "LongCount":
case "Count": return $"jsonb_array_length(coalesce({left},'[]'))"; case "Count": return $"jsonb_array_length(coalesce({left},'[]'))";
case "Parse": case "Parse":
var json2 = ExpressionLambdaToSql(callExp.Arguments[argIndex], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var json2 = getExp(callExp.Arguments[argIndex]);
if (json2.StartsWith("'") && json2.EndsWith("'")) return _common.FormatSql("{0}", JToken.Parse(json2.Trim('\''))); if (json2.StartsWith("'") && json2.EndsWith("'")) return _common.FormatSql("{0}", JToken.Parse(json2.Trim('\'')));
return $"({json2})::jsonb"; return $"({json2})::jsonb";
} }
@ -86,10 +87,10 @@ namespace FreeSql.PostgreSQL {
if (objType.FullName == typeof(Dictionary<string, string>).FullName) { if (objType.FullName == typeof(Dictionary<string, string>).FullName) {
switch (callExp.Method.Name) { switch (callExp.Method.Name) {
case "Contains": case "Contains":
var right = ExpressionLambdaToSql(callExp.Arguments[argIndex], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var right = getExp(callExp.Arguments[argIndex]);
return $"({left} @> ({right}))"; return $"({left} @> ({right}))";
case "ContainsKey": return $"({left} ? {ExpressionLambdaToSql(callExp.Arguments[argIndex], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "ContainsKey": return $"({left} ? {getExp(callExp.Arguments[argIndex])})";
case "Concat": return $"({left} || {ExpressionLambdaToSql(callExp.Arguments[argIndex], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Concat": return $"({left} || {getExp(callExp.Arguments[argIndex])})";
case "GetLength": case "GetLength":
case "GetLongLength": case "GetLongLength":
case "Count": return $"case when {left} is null then 0 else array_length(akeys({left}),1) end"; case "Count": return $"case when {left} is null then 0 else array_length(akeys({left}),1) end";
@ -105,7 +106,7 @@ namespace FreeSql.PostgreSQL {
if (memParentExp?.FullName == "System.Byte[]") return null; if (memParentExp?.FullName == "System.Byte[]") return null;
if (memParentExp != null) { if (memParentExp != null) {
if (memParentExp.IsArray == true) { if (memParentExp.IsArray == true) {
var left = ExpressionLambdaToSql(memExp.Expression, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var left = getExp(memExp.Expression);
if (left.StartsWith("(") || left.EndsWith(")")) left = $"array[{left.TrimStart('(').TrimEnd(')')}]"; if (left.StartsWith("(") || left.EndsWith(")")) left = $"array[{left.TrimStart('(').TrimEnd(')')}]";
switch (memExp.Member.Name) { switch (memExp.Member.Name) {
case "Length": case "Length":
@ -116,14 +117,14 @@ namespace FreeSql.PostgreSQL {
case "Newtonsoft.Json.Linq.JToken": case "Newtonsoft.Json.Linq.JToken":
case "Newtonsoft.Json.Linq.JObject": case "Newtonsoft.Json.Linq.JObject":
case "Newtonsoft.Json.Linq.JArray": case "Newtonsoft.Json.Linq.JArray":
var left = ExpressionLambdaToSql(memExp.Expression, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var left = getExp(memExp.Expression);
switch (memExp.Member.Name) { switch (memExp.Member.Name) {
case "Count": return $"jsonb_array_length(coalesce({left},'[]'))"; case "Count": return $"jsonb_array_length(coalesce({left},'[]'))";
} }
break; break;
} }
if (memParentExp.FullName == typeof(Dictionary<string, string>).FullName) { if (memParentExp.FullName == typeof(Dictionary<string, string>).FullName) {
var left = ExpressionLambdaToSql(memExp.Expression, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var left = getExp(memExp.Expression);
switch (memExp.Member.Name) { switch (memExp.Member.Name) {
case "Count": return $"case when {left} is null then 0 else array_length(akeys({left}),1) end"; case "Count": return $"case when {left} is null then 0 else array_length(akeys({left}),1) end";
case "Keys": return $"akeys({left})"; case "Keys": return $"akeys({left})";
@ -138,7 +139,7 @@ namespace FreeSql.PostgreSQL {
arrSb.Append("array["); arrSb.Append("array[");
for (var a = 0; a < arrExp.Expressions.Count; a++) { for (var a = 0; a < arrExp.Expressions.Count; a++) {
if (a > 0) arrSb.Append(","); if (a > 0) arrSb.Append(",");
arrSb.Append(ExpressionLambdaToSql(arrExp.Expressions[a], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)); arrSb.Append(getExp(arrExp.Expressions[a]));
} }
return arrSb.Append("]").ToString(); return arrSb.Append("]").ToString();
} }
@ -213,24 +214,25 @@ namespace FreeSql.PostgreSQL {
} }
internal override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, List<SelectTableInfo> _tables, List<SelectColumnInfo> _selectColumnMap, Func<Expression[], string> getSelectGroupingMapString, SelectTableInfoType tbtype, bool isQuoteName) { 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) { if (exp.Object == null) {
switch (exp.Method.Name) { switch (exp.Method.Name) {
case "IsNullOrEmpty": case "IsNullOrEmpty":
var arg1 = ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var arg1 = getExp(exp.Arguments[0]);
return $"({arg1} is null or {arg1} = '')"; return $"({arg1} is null or {arg1} = '')";
} }
} else { } else {
var left = ExpressionLambdaToSql(exp.Object, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var left = getExp(exp.Object);
switch (exp.Method.Name) { switch (exp.Method.Name) {
case "StartsWith": case "StartsWith":
case "EndsWith": case "EndsWith":
case "Contains": case "Contains":
var args0Value = ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var args0Value = getExp(exp.Arguments[0]);
if (args0Value == "NULL") return $"({left}) IS NULL"; if (args0Value == "NULL") return $"({left}) IS NULL";
var likeOpt = "LIKE"; var likeOpt = "LIKE";
if (exp.Arguments.Count > 1) { if (exp.Arguments.Count > 1) {
if (exp.Arguments[1].Type == typeof(bool) || if (exp.Arguments[1].Type == typeof(bool) ||
exp.Arguments[1].Type == typeof(StringComparison) && ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName).Contains("IgnoreCase")) likeOpt = "ILIKE"; exp.Arguments[1].Type == typeof(StringComparison) && getExp(exp.Arguments[0]).Contains("IgnoreCase")) likeOpt = "ILIKE";
} }
if (exp.Method.Name == "StartsWith") return $"({left}) {likeOpt} {(args0Value.EndsWith("'") ? args0Value.Insert(args0Value.Length - 1, "%") : $"(({args0Value})::varchar || '%')")}"; if (exp.Method.Name == "StartsWith") return $"({left}) {likeOpt} {(args0Value.EndsWith("'") ? args0Value.Insert(args0Value.Length - 1, "%") : $"(({args0Value})::varchar || '%')")}";
if (exp.Method.Name == "EndsWith") return $"({left}) {likeOpt} {(args0Value.StartsWith("'") ? args0Value.Insert(1, "%") : $"('%' || ({args0Value})::varchar)")}"; if (exp.Method.Name == "EndsWith") return $"({left}) {likeOpt} {(args0Value.StartsWith("'") ? args0Value.Insert(1, "%") : $"('%' || ({args0Value})::varchar)")}";
@ -239,18 +241,18 @@ namespace FreeSql.PostgreSQL {
case "ToLower": return $"lower({left})"; case "ToLower": return $"lower({left})";
case "ToUpper": return $"upper({left})"; case "ToUpper": return $"upper({left})";
case "Substring": case "Substring":
var substrArgs1 = ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var substrArgs1 = getExp(exp.Arguments[0]);
if (long.TryParse(substrArgs1, out var testtrylng1)) substrArgs1 = (testtrylng1 + 1).ToString(); if (long.TryParse(substrArgs1, out var testtrylng1)) substrArgs1 = (testtrylng1 + 1).ToString();
else substrArgs1 += "+1"; else substrArgs1 += "+1";
if (exp.Arguments.Count == 1) return $"substr({left}, {substrArgs1})"; if (exp.Arguments.Count == 1) return $"substr({left}, {substrArgs1})";
return $"substr({left}, {substrArgs1}, {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; return $"substr({left}, {substrArgs1}, {getExp(exp.Arguments[1])})";
case "IndexOf": return $"(strpos({left}, {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})-1)"; case "IndexOf": return $"(strpos({left}, {getExp(exp.Arguments[0])})-1)";
case "PadLeft": case "PadLeft":
if (exp.Arguments.Count == 1) return $"lpad({left}, {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; if (exp.Arguments.Count == 1) return $"lpad({left}, {getExp(exp.Arguments[0])})";
return $"lpad({left}, {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}, {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; return $"lpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
case "PadRight": case "PadRight":
if (exp.Arguments.Count == 1) return $"rpad({left}, {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; if (exp.Arguments.Count == 1) return $"rpad({left}, {getExp(exp.Arguments[0])})";
return $"rpad({left}, {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}, {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; return $"rpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
case "Trim": case "Trim":
case "TrimStart": case "TrimStart":
case "TrimEnd": case "TrimEnd":
@ -268,7 +270,7 @@ namespace FreeSql.PostgreSQL {
argsTrim01s = arritem.Expressions.ToArray(); argsTrim01s = arritem.Expressions.ToArray();
} }
foreach (var argsTrim01 in argsTrim01s) { foreach (var argsTrim01 in argsTrim01s) {
var trimChr = ExpressionLambdaToSql(argsTrim01, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName).Trim('\''); var trimChr = getExp(argsTrim01).Trim('\'');
if (trimChr.Length == 1) trimArg1 += trimChr; if (trimChr.Length == 1) trimArg1 += trimChr;
else trimArg2 += $" || ({trimChr})"; else trimArg2 += $" || ({trimChr})";
} }
@ -277,57 +279,59 @@ namespace FreeSql.PostgreSQL {
if (exp.Method.Name == "TrimStart") left = $"ltrim({left}, {_common.FormatSql("{0}", trimArg1)}{trimArg2})"; if (exp.Method.Name == "TrimStart") left = $"ltrim({left}, {_common.FormatSql("{0}", trimArg1)}{trimArg2})";
if (exp.Method.Name == "TrimEnd") left = $"rtrim({left}, {_common.FormatSql("{0}", trimArg1)}{trimArg2})"; if (exp.Method.Name == "TrimEnd") left = $"rtrim({left}, {_common.FormatSql("{0}", trimArg1)}{trimArg2})";
return left; return left;
case "Replace": return $"replace({left}, {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}, {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Replace": return $"replace({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
case "CompareTo": return $"case when {left} = {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} then 0 when {left} > {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} then 1 else -1 end"; case "CompareTo": return $"case when {left} = {getExp(exp.Arguments[0])} then 0 when {left} > {getExp(exp.Arguments[0])} then 1 else -1 end";
case "Equals": return $"({left} = ({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})::varchar)"; case "Equals": return $"({left} = ({getExp(exp.Arguments[0])})::varchar)";
} }
} }
throw new Exception($"PostgreSQLExpression 未现实函数表达式 {exp} 解析"); throw new Exception($"PostgreSQLExpression 未现实函数表达式 {exp} 解析");
} }
internal override string ExpressionLambdaToSqlCallMath(MethodCallExpression exp, List<SelectTableInfo> _tables, List<SelectColumnInfo> _selectColumnMap, Func<Expression[], string> getSelectGroupingMapString, SelectTableInfoType tbtype, bool isQuoteName) { 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) { switch (exp.Method.Name) {
case "Abs": return $"abs({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Abs": return $"abs({getExp(exp.Arguments[0])})";
case "Sign": return $"sign({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Sign": return $"sign({getExp(exp.Arguments[0])})";
case "Floor": return $"floor({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Floor": return $"floor({getExp(exp.Arguments[0])})";
case "Ceiling": return $"ceiling({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Ceiling": return $"ceiling({getExp(exp.Arguments[0])})";
case "Round": case "Round":
if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") return $"round({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}, {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") return $"round({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
return $"round({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; return $"round({getExp(exp.Arguments[0])})";
case "Exp": return $"exp({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Exp": return $"exp({getExp(exp.Arguments[0])})";
case "Log": return $"log({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Log": return $"log({getExp(exp.Arguments[0])})";
case "Log10": return $"log10({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Log10": return $"log10({getExp(exp.Arguments[0])})";
case "Pow": return $"pow({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}, {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Pow": return $"pow({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
case "Sqrt": return $"sqrt({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Sqrt": return $"sqrt({getExp(exp.Arguments[0])})";
case "Cos": return $"cos({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Cos": return $"cos({getExp(exp.Arguments[0])})";
case "Sin": return $"sin({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Sin": return $"sin({getExp(exp.Arguments[0])})";
case "Tan": return $"tan({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Tan": return $"tan({getExp(exp.Arguments[0])})";
case "Acos": return $"acos({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Acos": return $"acos({getExp(exp.Arguments[0])})";
case "Asin": return $"asin({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Asin": return $"asin({getExp(exp.Arguments[0])})";
case "Atan": return $"atan({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Atan": return $"atan({getExp(exp.Arguments[0])})";
case "Atan2": return $"atan2({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}, {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Atan2": return $"atan2({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
case "Truncate": return $"trunc({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}, 0)"; case "Truncate": return $"trunc({getExp(exp.Arguments[0])}, 0)";
} }
throw new Exception($"PostgreSQLExpression 未现实函数表达式 {exp} 解析"); throw new Exception($"PostgreSQLExpression 未现实函数表达式 {exp} 解析");
} }
internal override string ExpressionLambdaToSqlCallDateTime(MethodCallExpression exp, List<SelectTableInfo> _tables, List<SelectColumnInfo> _selectColumnMap, Func<Expression[], string> getSelectGroupingMapString, SelectTableInfoType tbtype, bool isQuoteName) { 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) { if (exp.Object == null) {
switch (exp.Method.Name) { switch (exp.Method.Name) {
case "Compare": return $"extract(epoch from ({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})::timestamp-({ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})::timestamp)"; case "Compare": return $"extract(epoch from ({getExp(exp.Arguments[0])})::timestamp-({getExp(exp.Arguments[1])})::timestamp)";
case "DaysInMonth": return $"extract(day from ({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} || '-' || {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} || '-01')::timestamp+'1 month'::interval-'1 day'::interval)"; case "DaysInMonth": return $"extract(day from ({getExp(exp.Arguments[0])} || '-' || {getExp(exp.Arguments[1])} || '-01')::timestamp+'1 month'::interval-'1 day'::interval)";
case "Equals": return $"(({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})::timestamp = ({ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})::timestamp)"; case "Equals": return $"(({getExp(exp.Arguments[0])})::timestamp = ({getExp(exp.Arguments[1])})::timestamp)";
case "IsLeapYear": case "IsLeapYear":
var isLeapYearArgs1 = ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var isLeapYearArgs1 = getExp(exp.Arguments[0]);
return $"(({isLeapYearArgs1})::int8%4=0 AND ({isLeapYearArgs1})::int8%100<>0 OR ({isLeapYearArgs1})::int8%400=0)"; return $"(({isLeapYearArgs1})::int8%4=0 AND ({isLeapYearArgs1})::int8%100<>0 OR ({isLeapYearArgs1})::int8%400=0)";
case "Parse": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})::timestamp"; case "Parse": return $"({getExp(exp.Arguments[0])})::timestamp";
case "ParseExact": case "ParseExact":
case "TryParse": case "TryParse":
case "TryParseExact": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})::timestamp"; case "TryParseExact": return $"({getExp(exp.Arguments[0])})::timestamp";
} }
} else { } else {
var left = ExpressionLambdaToSql(exp.Object, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var left = getExp(exp.Object);
var args1 = exp.Arguments.Count == 0 ? null : ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]);
switch (exp.Method.Name) { switch (exp.Method.Name) {
case "Add": return $"(({left})::timestamp+(({args1})||' microseconds')::interval)"; case "Add": return $"(({left})::timestamp+(({args1})||' microseconds')::interval)";
case "AddDays": return $"(({left})::timestamp+(({args1})||' day')::interval)"; case "AddDays": return $"(({left})::timestamp+(({args1})||' day')::interval)";
@ -344,60 +348,62 @@ namespace FreeSql.PostgreSQL {
if (exp.Arguments[0].Type.FullName == "System.TimeSpan" || exp.Arguments[0].Type.GenericTypeArguments.FirstOrDefault()?.FullName == "System.TimeSpan") if (exp.Arguments[0].Type.FullName == "System.TimeSpan" || exp.Arguments[0].Type.GenericTypeArguments.FirstOrDefault()?.FullName == "System.TimeSpan")
return $"(({left})::timestamp-(({args1})||' microseconds')::interval)"; return $"(({left})::timestamp-(({args1})||' microseconds')::interval)";
break; break;
case "Equals": return $"({left} = ({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})::timestamp)"; case "Equals": return $"({left} = ({getExp(exp.Arguments[0])})::timestamp)";
case "CompareTo": return $"extract(epoch from ({left})::timestamp-({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})::timestamp)"; case "CompareTo": return $"extract(epoch from ({left})::timestamp-({getExp(exp.Arguments[0])})::timestamp)";
case "ToString": return $"to_char({left}, 'YYYY-MM-DD HH24:MI:SS.US')"; case "ToString": return $"to_char({left}, 'YYYY-MM-DD HH24:MI:SS.US')";
} }
} }
throw new Exception($"PostgreSQLExpression 未现实函数表达式 {exp} 解析"); throw new Exception($"PostgreSQLExpression 未现实函数表达式 {exp} 解析");
} }
internal override string ExpressionLambdaToSqlCallTimeSpan(MethodCallExpression exp, List<SelectTableInfo> _tables, List<SelectColumnInfo> _selectColumnMap, Func<Expression[], string> getSelectGroupingMapString, SelectTableInfoType tbtype, bool isQuoteName) { 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) { if (exp.Object == null) {
switch (exp.Method.Name) { switch (exp.Method.Name) {
case "Compare": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}-({ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}))"; case "Compare": return $"({getExp(exp.Arguments[0])}-({getExp(exp.Arguments[1])}))";
case "Equals": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} = {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})";
case "FromDays": return $"(({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})*{(long)1000000 * 60 * 60 * 24})"; case "FromDays": return $"(({getExp(exp.Arguments[0])})*{(long)1000000 * 60 * 60 * 24})";
case "FromHours": return $"(({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})*{(long)1000000 * 60 * 60})"; case "FromHours": return $"(({getExp(exp.Arguments[0])})*{(long)1000000 * 60 * 60})";
case "FromMilliseconds": return $"(({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})*1000)"; case "FromMilliseconds": return $"(({getExp(exp.Arguments[0])})*1000)";
case "FromMinutes": return $"(({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})*{(long)1000000 * 60})"; case "FromMinutes": return $"(({getExp(exp.Arguments[0])})*{(long)1000000 * 60})";
case "FromSeconds": return $"(({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})*1000000)"; case "FromSeconds": return $"(({getExp(exp.Arguments[0])})*1000000)";
case "FromTicks": return $"(({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})/10)"; case "FromTicks": return $"(({getExp(exp.Arguments[0])})/10)";
case "Parse": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})::int8"; case "Parse": return $"({getExp(exp.Arguments[0])})::int8";
case "ParseExact": case "ParseExact":
case "TryParse": case "TryParse":
case "TryParseExact": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})::int8"; case "TryParseExact": return $"({getExp(exp.Arguments[0])})::int8";
} }
} else { } else {
var left = ExpressionLambdaToSql(exp.Object, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var left = getExp(exp.Object);
var args1 = exp.Arguments.Count == 0 ? null : ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]);
switch (exp.Method.Name) { switch (exp.Method.Name) {
case "Add": return $"({left}+{args1})"; case "Add": return $"({left}+{args1})";
case "Subtract": return $"({left}-({args1}))"; case "Subtract": return $"({left}-({args1}))";
case "Equals": return $"({left} = {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Equals": return $"({left} = {getExp(exp.Arguments[0])})";
case "CompareTo": return $"({left}-({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}))"; case "CompareTo": return $"({left}-({getExp(exp.Arguments[0])}))";
case "ToString": return $"({left})::varchar"; case "ToString": return $"({left})::varchar";
} }
} }
throw new Exception($"PostgreSQLExpression 未现实函数表达式 {exp} 解析"); throw new Exception($"PostgreSQLExpression 未现实函数表达式 {exp} 解析");
} }
internal override string ExpressionLambdaToSqlCallConvert(MethodCallExpression exp, List<SelectTableInfo> _tables, List<SelectColumnInfo> _selectColumnMap, Func<Expression[], string> getSelectGroupingMapString, SelectTableInfoType tbtype, bool isQuoteName) { 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) { if (exp.Object == null) {
switch (exp.Method.Name) { switch (exp.Method.Name) {
case "ToBoolean": return $"(({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})::varchar not in ('0','false','f','no'))"; case "ToBoolean": return $"(({getExp(exp.Arguments[0])})::varchar not in ('0','false','f','no'))";
case "ToByte": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})::int2"; case "ToByte": return $"({getExp(exp.Arguments[0])})::int2";
case "ToChar": return $"substr(({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})::char, 1, 1)"; case "ToChar": return $"substr(({getExp(exp.Arguments[0])})::char, 1, 1)";
case "ToDateTime": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})::timestamp"; case "ToDateTime": return $"({getExp(exp.Arguments[0])})::timestamp";
case "ToDecimal": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})::numeric"; case "ToDecimal": return $"({getExp(exp.Arguments[0])})::numeric";
case "ToDouble": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})::float8"; case "ToDouble": return $"({getExp(exp.Arguments[0])})::float8";
case "ToInt16": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})::int2"; case "ToInt16": return $"({getExp(exp.Arguments[0])})::int2";
case "ToInt32": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})::int4"; case "ToInt32": return $"({getExp(exp.Arguments[0])})::int4";
case "ToInt64": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})::int8"; case "ToInt64": return $"({getExp(exp.Arguments[0])})::int8";
case "ToSByte": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})::int2"; case "ToSByte": return $"({getExp(exp.Arguments[0])})::int2";
case "ToSingle": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})::float4"; case "ToSingle": return $"({getExp(exp.Arguments[0])})::float4";
case "ToString": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})::varchar"; case "ToString": return $"({getExp(exp.Arguments[0])})::varchar";
case "ToUInt16": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})::int2"; case "ToUInt16": return $"({getExp(exp.Arguments[0])})::int2";
case "ToUInt32": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})::int4"; case "ToUInt32": return $"({getExp(exp.Arguments[0])})::int4";
case "ToUInt64": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})::int8"; case "ToUInt64": return $"({getExp(exp.Arguments[0])})::int8";
} }
} }
throw new Exception($"PostgreSQLExpression 未现实函数表达式 {exp} 解析"); throw new Exception($"PostgreSQLExpression 未现实函数表达式 {exp} 解析");

View File

@ -40,6 +40,7 @@ namespace FreeSql.SqlServer.Curd {
if (a < tbsfrom.Length - 1) sb.Append(", "); if (a < tbsfrom.Length - 1) sb.Append(", ");
} }
foreach (var tb in tbsjoin) { foreach (var tb in tbsjoin) {
if (tb.Type == SelectTableInfoType.Parent) continue;
switch (tb.Type) { switch (tb.Type) {
case SelectTableInfoType.LeftJoin: case SelectTableInfoType.LeftJoin:
sb.Append(" \r\nLEFT JOIN "); sb.Append(" \r\nLEFT JOIN ");
@ -57,6 +58,7 @@ namespace FreeSql.SqlServer.Curd {
var sbqf = new StringBuilder(); var sbqf = new StringBuilder();
foreach (var tb in _tables) { foreach (var tb in _tables) {
if (tb.Type == SelectTableInfoType.Parent) continue;
if (string.IsNullOrEmpty(tb.Table.SelectFilter) == false) if (string.IsNullOrEmpty(tb.Table.SelectFilter) == false)
sbqf.Append(" AND (").Append(tb.Table.SelectFilter.Replace("a.", $"{tb.Alias}.")).Append(")"); sbqf.Append(" AND (").Append(tb.Table.SelectFilter.Replace("a.", $"{tb.Alias}.")).Append(")");
} }

View File

@ -12,6 +12,7 @@ namespace FreeSql.SqlServer {
public SqlServerExpression(CommonUtils common) : base(common) { } public SqlServerExpression(CommonUtils common) : base(common) { }
internal override string ExpressionLambdaToSqlOther(Expression exp, List<SelectTableInfo> _tables, List<SelectColumnInfo> _selectColumnMap, Func<Expression[], string> getSelectGroupingMapString, SelectTableInfoType tbtype, bool isQuoteName) { 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) { switch (exp.NodeType) {
case ExpressionType.Call: case ExpressionType.Call:
var callExp = exp as MethodCallExpression; var callExp = exp as MethodCallExpression;
@ -27,12 +28,12 @@ namespace FreeSql.SqlServer {
} }
if (objType == null) objType = callExp.Method.DeclaringType; if (objType == null) objType = callExp.Method.DeclaringType;
if (objType != null) { if (objType != null) {
var left = objExp == null ? null : ExpressionLambdaToSql(objExp, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var left = objExp == null ? null : getExp(objExp);
if (objType.IsArray == true) { if (objType.IsArray == true) {
switch (callExp.Method.Name) { switch (callExp.Method.Name) {
case "Contains": case "Contains":
//判断 in //判断 in
return $"({ExpressionLambdaToSql(callExp.Arguments[argIndex], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}) in {left}"; return $"({getExp(callExp.Arguments[argIndex])}) in {left}";
} }
} }
} }
@ -43,7 +44,7 @@ namespace FreeSql.SqlServer {
arrSb.Append("("); arrSb.Append("(");
for (var a = 0; a < arrExp.Expressions.Count; a++) { for (var a = 0; a < arrExp.Expressions.Count; a++) {
if (a > 0) arrSb.Append(","); if (a > 0) arrSb.Append(",");
arrSb.Append(ExpressionLambdaToSql(arrExp.Expressions[a], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)); arrSb.Append(getExp(arrExp.Expressions[a]));
} }
return arrSb.Append(")").ToString(); return arrSb.Append(")").ToString();
} }
@ -118,19 +119,20 @@ namespace FreeSql.SqlServer {
} }
internal override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, List<SelectTableInfo> _tables, List<SelectColumnInfo> _selectColumnMap, Func<Expression[], string> getSelectGroupingMapString, SelectTableInfoType tbtype, bool isQuoteName) { 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) { if (exp.Object == null) {
switch (exp.Method.Name) { switch (exp.Method.Name) {
case "IsNullOrEmpty": case "IsNullOrEmpty":
var arg1 = ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var arg1 = getExp(exp.Arguments[0]);
return $"({arg1} is null or {arg1} = '')"; return $"({arg1} is null or {arg1} = '')";
} }
} else { } else {
var left = ExpressionLambdaToSql(exp.Object, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var left = getExp(exp.Object);
switch (exp.Method.Name) { switch (exp.Method.Name) {
case "StartsWith": case "StartsWith":
case "EndsWith": case "EndsWith":
case "Contains": case "Contains":
var args0Value = ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var args0Value = getExp(exp.Arguments[0]);
if (args0Value == "NULL") return $"({left}) IS NULL"; if (args0Value == "NULL") return $"({left}) IS NULL";
if (exp.Method.Name == "StartsWith") return $"({left}) LIKE {(args0Value.EndsWith("'") ? args0Value.Insert(args0Value.Length - 1, "%") : $"(cast({args0Value} as nvarchar)+'%')")}"; if (exp.Method.Name == "StartsWith") return $"({left}) LIKE {(args0Value.EndsWith("'") ? args0Value.Insert(args0Value.Length - 1, "%") : $"(cast({args0Value} as nvarchar)+'%')")}";
if (exp.Method.Name == "EndsWith") return $"({left}) LIKE {(args0Value.StartsWith("'") ? args0Value.Insert(1, "%") : $"('%'+cast({args0Value} as nvarchar))")}"; if (exp.Method.Name == "EndsWith") return $"({left}) LIKE {(args0Value.StartsWith("'") ? args0Value.Insert(1, "%") : $"('%'+cast({args0Value} as nvarchar))")}";
@ -139,80 +141,82 @@ namespace FreeSql.SqlServer {
case "ToLower": return $"lower({left})"; case "ToLower": return $"lower({left})";
case "ToUpper": return $"upper({left})"; case "ToUpper": return $"upper({left})";
case "Substring": case "Substring":
var substrArgs1 = ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var substrArgs1 = getExp(exp.Arguments[0]);
if (long.TryParse(substrArgs1, out var testtrylng1)) substrArgs1 = (testtrylng1 + 1).ToString(); if (long.TryParse(substrArgs1, out var testtrylng1)) substrArgs1 = (testtrylng1 + 1).ToString();
else substrArgs1 += "+1"; else substrArgs1 += "+1";
if (exp.Arguments.Count == 1) return $"left({left}, {substrArgs1})"; if (exp.Arguments.Count == 1) return $"left({left}, {substrArgs1})";
return $"substring({left}, {substrArgs1}, {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; return $"substring({left}, {substrArgs1}, {getExp(exp.Arguments[1])})";
case "IndexOf": case "IndexOf":
var indexOfFindStr = ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var indexOfFindStr = getExp(exp.Arguments[0]);
if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") { if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") {
var locateArgs1 = ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var locateArgs1 = getExp(exp.Arguments[1]);
if (long.TryParse(locateArgs1, out var testtrylng2)) locateArgs1 = (testtrylng2 + 1).ToString(); if (long.TryParse(locateArgs1, out var testtrylng2)) locateArgs1 = (testtrylng2 + 1).ToString();
else locateArgs1 += "+1"; else locateArgs1 += "+1";
return $"(charindex({left}, {indexOfFindStr}, {locateArgs1})-1)"; return $"(charindex({left}, {indexOfFindStr}, {locateArgs1})-1)";
} }
return $"(charindex({left}, {indexOfFindStr})-1)"; return $"(charindex({left}, {indexOfFindStr})-1)";
case "PadLeft": case "PadLeft":
if (exp.Arguments.Count == 1) return $"lpad({left}, {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; if (exp.Arguments.Count == 1) return $"lpad({left}, {getExp(exp.Arguments[0])})";
return $"lpad({left}, {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}, {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; return $"lpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
case "PadRight": case "PadRight":
if (exp.Arguments.Count == 1) return $"rpad({left}, {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; if (exp.Arguments.Count == 1) return $"rpad({left}, {getExp(exp.Arguments[0])})";
return $"rpad({left}, {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}, {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; return $"rpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
case "Trim": return $"ltrim(rtrim({left}))"; case "Trim": return $"ltrim(rtrim({left}))";
case "TrimStart": return $"ltrim({left})"; case "TrimStart": return $"ltrim({left})";
case "TrimEnd": return $"rtrim({left})"; case "TrimEnd": return $"rtrim({left})";
case "Replace": return $"replace({left}, {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}, {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Replace": return $"replace({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
case "CompareTo": return $"({left} - {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "CompareTo": return $"({left} - {getExp(exp.Arguments[0])})";
case "Equals": return $"({left} = {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Equals": return $"({left} = {getExp(exp.Arguments[0])})";
} }
} }
throw new Exception($"SqlServerExpression 未现实函数表达式 {exp} 解析"); throw new Exception($"SqlServerExpression 未现实函数表达式 {exp} 解析");
} }
internal override string ExpressionLambdaToSqlCallMath(MethodCallExpression exp, List<SelectTableInfo> _tables, List<SelectColumnInfo> _selectColumnMap, Func<Expression[], string> getSelectGroupingMapString, SelectTableInfoType tbtype, bool isQuoteName) { 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) { switch (exp.Method.Name) {
case "Abs": return $"abs({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Abs": return $"abs({getExp(exp.Arguments[0])})";
case "Sign": return $"sign({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Sign": return $"sign({getExp(exp.Arguments[0])})";
case "Floor": return $"floor({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Floor": return $"floor({getExp(exp.Arguments[0])})";
case "Ceiling": return $"ceiling({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Ceiling": return $"ceiling({getExp(exp.Arguments[0])})";
case "Round": case "Round":
if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") return $"round({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}, {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") return $"round({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
return $"round({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}, 0)"; return $"round({getExp(exp.Arguments[0])}, 0)";
case "Exp": return $"exp({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Exp": return $"exp({getExp(exp.Arguments[0])})";
case "Log": return $"log({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Log": return $"log({getExp(exp.Arguments[0])})";
case "Log10": return $"log10({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Log10": return $"log10({getExp(exp.Arguments[0])})";
case "Pow": return $"power({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}, {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Pow": return $"power({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
case "Sqrt": return $"sqrt({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Sqrt": return $"sqrt({getExp(exp.Arguments[0])})";
case "Cos": return $"cos({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Cos": return $"cos({getExp(exp.Arguments[0])})";
case "Sin": return $"sin({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Sin": return $"sin({getExp(exp.Arguments[0])})";
case "Tan": return $"tan({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Tan": return $"tan({getExp(exp.Arguments[0])})";
case "Acos": return $"acos({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Acos": return $"acos({getExp(exp.Arguments[0])})";
case "Asin": return $"asin({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Asin": return $"asin({getExp(exp.Arguments[0])})";
case "Atan": return $"atan({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Atan": return $"atan({getExp(exp.Arguments[0])})";
case "Atan2": return $"atan2({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}, {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Atan2": return $"atan2({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
case "Truncate": return $"floor({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Truncate": return $"floor({getExp(exp.Arguments[0])})";
} }
throw new Exception($"SqlServerExpression 未现实函数表达式 {exp} 解析"); throw new Exception($"SqlServerExpression 未现实函数表达式 {exp} 解析");
} }
internal override string ExpressionLambdaToSqlCallDateTime(MethodCallExpression exp, List<SelectTableInfo> _tables, List<SelectColumnInfo> _selectColumnMap, Func<Expression[], string> getSelectGroupingMapString, SelectTableInfoType tbtype, bool isQuoteName) { 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) { if (exp.Object == null) {
switch (exp.Method.Name) { switch (exp.Method.Name) {
case "Compare": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} - ({ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}))"; case "Compare": return $"({getExp(exp.Arguments[0])} - ({getExp(exp.Arguments[1])}))";
case "DaysInMonth": return $"datepart(day, dateadd(day, -1, dateadd(month, 1, cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as varchar) + '-' + cast({ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as varchar) + '-1')))"; case "DaysInMonth": return $"datepart(day, dateadd(day, -1, dateadd(month, 1, cast({getExp(exp.Arguments[0])} as varchar) + '-' + cast({getExp(exp.Arguments[1])} as varchar) + '-1')))";
case "Equals": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} = {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})";
case "IsLeapYear": case "IsLeapYear":
var isLeapYearArgs1 = ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var isLeapYearArgs1 = getExp(exp.Arguments[0]);
return $"(({isLeapYearArgs1})%4=0 AND ({isLeapYearArgs1})%100<>0 OR ({isLeapYearArgs1})%400=0)"; return $"(({isLeapYearArgs1})%4=0 AND ({isLeapYearArgs1})%100<>0 OR ({isLeapYearArgs1})%400=0)";
case "Parse": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as datetime)"; case "Parse": return $"cast({getExp(exp.Arguments[0])} as datetime)";
case "ParseExact": case "ParseExact":
case "TryParse": case "TryParse":
case "TryParseExact": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as datetime)"; case "TryParseExact": return $"cast({getExp(exp.Arguments[0])} as datetime)";
} }
} else { } else {
var left = ExpressionLambdaToSql(exp.Object, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var left = getExp(exp.Object);
var args1 = exp.Arguments.Count == 0 ? null : ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]);
switch (exp.Method.Name) { switch (exp.Method.Name) {
case "Add": return $"dateadd(second, {args1}, {left})"; case "Add": return $"dateadd(second, {args1}, {left})";
case "AddDays": return $"dateadd(day, {args1}, {left})"; case "AddDays": return $"dateadd(day, {args1}, {left})";
@ -229,60 +233,62 @@ namespace FreeSql.SqlServer {
if (exp.Arguments[0].Type.FullName == "System.TimeSpan" || exp.Arguments[0].Type.GenericTypeArguments.FirstOrDefault()?.FullName == "System.TimeSpan") if (exp.Arguments[0].Type.FullName == "System.TimeSpan" || exp.Arguments[0].Type.GenericTypeArguments.FirstOrDefault()?.FullName == "System.TimeSpan")
return $"dateadd(second, {args1}*-1, {left})"; return $"dateadd(second, {args1}*-1, {left})";
break; break;
case "Equals": return $"({left} = {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Equals": return $"({left} = {getExp(exp.Arguments[0])})";
case "CompareTo": return $"(({left}) - ({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}))"; case "CompareTo": return $"(({left}) - ({getExp(exp.Arguments[0])}))";
case "ToString": return $"convert(varchar, {left}, 121)"; case "ToString": return $"convert(varchar, {left}, 121)";
} }
} }
throw new Exception($"SqlServerExpression 未现实函数表达式 {exp} 解析"); throw new Exception($"SqlServerExpression 未现实函数表达式 {exp} 解析");
} }
internal override string ExpressionLambdaToSqlCallTimeSpan(MethodCallExpression exp, List<SelectTableInfo> _tables, List<SelectColumnInfo> _selectColumnMap, Func<Expression[], string> getSelectGroupingMapString, SelectTableInfoType tbtype, bool isQuoteName) { 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) { if (exp.Object == null) {
switch (exp.Method.Name) { switch (exp.Method.Name) {
case "Compare": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}-({ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}))"; case "Compare": return $"({getExp(exp.Arguments[0])}-({getExp(exp.Arguments[1])}))";
case "Equals": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} = {ExpressionLambdaToSql(exp.Arguments[1], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})";
case "FromDays": return $"(({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})*{60 * 60 * 24})"; case "FromDays": return $"(({getExp(exp.Arguments[0])})*{60 * 60 * 24})";
case "FromHours": return $"(({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})*{60 * 60})"; case "FromHours": return $"(({getExp(exp.Arguments[0])})*{60 * 60})";
case "FromMilliseconds": return $"(({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})/1000)"; case "FromMilliseconds": return $"(({getExp(exp.Arguments[0])})/1000)";
case "FromMinutes": return $"(({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})*60)"; case "FromMinutes": return $"(({getExp(exp.Arguments[0])})*60)";
case "FromSeconds": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "FromSeconds": return $"({getExp(exp.Arguments[0])})";
case "FromTicks": return $"(({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})/10000000)"; case "FromTicks": return $"(({getExp(exp.Arguments[0])})/10000000)";
case "Parse": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as bigint)"; case "Parse": return $"cast({getExp(exp.Arguments[0])} as bigint)";
case "ParseExact": case "ParseExact":
case "TryParse": case "TryParse":
case "TryParseExact": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as bigint)"; case "TryParseExact": return $"cast({getExp(exp.Arguments[0])} as bigint)";
} }
} else { } else {
var left = ExpressionLambdaToSql(exp.Object, _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var left = getExp(exp.Object);
var args1 = exp.Arguments.Count == 0 ? null : ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName); var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]);
switch (exp.Method.Name) { switch (exp.Method.Name) {
case "Add": return $"({left}+{args1})"; case "Add": return $"({left}+{args1})";
case "Subtract": return $"({left}-({args1}))"; case "Subtract": return $"({left}-({args1}))";
case "Equals": return $"({left} = {ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)})"; case "Equals": return $"({left} = {getExp(exp.Arguments[0])})";
case "CompareTo": return $"({left}-({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)}))"; case "CompareTo": return $"({left}-({getExp(exp.Arguments[0])}))";
case "ToString": return $"cast({left} as varchar)"; case "ToString": return $"cast({left} as varchar)";
} }
} }
throw new Exception($"SqlServerExpression 未现实函数表达式 {exp} 解析"); throw new Exception($"SqlServerExpression 未现实函数表达式 {exp} 解析");
} }
internal override string ExpressionLambdaToSqlCallConvert(MethodCallExpression exp, List<SelectTableInfo> _tables, List<SelectColumnInfo> _selectColumnMap, Func<Expression[], string> getSelectGroupingMapString, SelectTableInfoType tbtype, bool isQuoteName) { 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) { if (exp.Object == null) {
switch (exp.Method.Name) { switch (exp.Method.Name) {
case "ToBoolean": return $"({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} not in ('0','false'))"; case "ToBoolean": return $"({getExp(exp.Arguments[0])} not in ('0','false'))";
case "ToByte": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as tinyint)"; case "ToByte": return $"cast({getExp(exp.Arguments[0])} as tinyint)";
case "ToChar": return $"substring(cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as nvarchar),1,1)"; case "ToChar": return $"substring(cast({getExp(exp.Arguments[0])} as nvarchar),1,1)";
case "ToDateTime": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as datetime)"; case "ToDateTime": return $"cast({getExp(exp.Arguments[0])} as datetime)";
case "ToDecimal": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as decimal(36,18))"; case "ToDecimal": return $"cast({getExp(exp.Arguments[0])} as decimal(36,18))";
case "ToDouble": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as decimal(32,16))"; case "ToDouble": return $"cast({getExp(exp.Arguments[0])} as decimal(32,16))";
case "ToInt16": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as smallint)"; case "ToInt16": return $"cast({getExp(exp.Arguments[0])} as smallint)";
case "ToInt32": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as int)"; case "ToInt32": return $"cast({getExp(exp.Arguments[0])} as int)";
case "ToInt64": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as bigint)"; case "ToInt64": return $"cast({getExp(exp.Arguments[0])} as bigint)";
case "ToSByte": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as tinyint)"; case "ToSByte": return $"cast({getExp(exp.Arguments[0])} as tinyint)";
case "ToSingle": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as decimal(14,7))"; case "ToSingle": return $"cast({getExp(exp.Arguments[0])} as decimal(14,7))";
case "ToString": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as nvarchar)"; case "ToString": return $"cast({getExp(exp.Arguments[0])} as nvarchar)";
case "ToUInt16": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as smallint)"; case "ToUInt16": return $"cast({getExp(exp.Arguments[0])} as smallint)";
case "ToUInt32": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as int)"; case "ToUInt32": return $"cast({getExp(exp.Arguments[0])} as int)";
case "ToUInt64": return $"cast({ExpressionLambdaToSql(exp.Arguments[0], _tables, _selectColumnMap, getSelectGroupingMapString, tbtype, isQuoteName)} as bigint)"; case "ToUInt64": return $"cast({getExp(exp.Arguments[0])} as bigint)";
} }
} }
throw new Exception($"SqlServerExpression 未现实函数表达式 {exp} 解析"); throw new Exception($"SqlServerExpression 未现实函数表达式 {exp} 解析");