Skip to content

Commit

Permalink
v1.8.30 1. 数据库连接池优化 2. 修改SqlString以方便和Dapper结合使用 3. 优化where条件拼接,去除多余的括号
Browse files Browse the repository at this point in the history
  • Loading branch information
0611163 committed May 28, 2023
1 parent 5a116b6 commit e5a9c22
Show file tree
Hide file tree
Showing 9 changed files with 154 additions and 27 deletions.
10 changes: 6 additions & 4 deletions Dapper.Lite/Dapper.Lite/Dapper.Lite.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
<Nullable>disable</Nullable>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<Title>Dapper.Lite</Title>
<AssemblyVersion>1.8.29</AssemblyVersion>
<FileVersion>1.8.29</FileVersion>
<Version>1.8.29</Version>
<AssemblyVersion>1.8.30</AssemblyVersion>
<FileVersion>1.8.30</FileVersion>
<Version>1.8.30</Version>
<PackageId>Dapper.Lite</PackageId>
<PackageProjectUrl>https://github.com/0611163/Dapper.Lite</PackageProjectUrl>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
Expand All @@ -17,7 +17,9 @@
<Copyright>Copyright @ 2022</Copyright>
<Description>一款同时支持原生SQL和Lambda表达式的轻量级ORM,支持Oracle、MSSQL、MySQL、PostgreSQL、SQLite、Access数据库,以及任意ADO.NET支持的数据库。</Description>
<PackageReleaseNotes>
字段类型支持Guid
1. 数据库连接池优化
2. 修改SqlString以方便和Dapper结合使用
3. 优化where条件拼接,去除多余的括号
</PackageReleaseNotes>
</PropertyGroup>

Expand Down
20 changes: 20 additions & 0 deletions Dapper.Lite/Dapper.Lite/Session/DbSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,26 @@ public Task<DbConnectionExt> GetConnectionAsync(DbTransactionExt tran = null)
{
return _connFactory.GetConnectionAsync(tran);
}

/// <summary>
/// 从连接池池获取连接,已经Open
/// </summary>
public DbConnectionExt GetOpenedConnection(DbTransactionExt tran = null)
{
var connEx = _connFactory.GetConnection(tran);
if (connEx.Conn.State == ConnectionState.Closed) connEx.Conn.Open();
return connEx;
}

/// <summary>
/// 从连接池池获取连接,已经Open
/// </summary>
public async Task<DbConnectionExt> GetOpenedConnectionAsync(DbTransactionExt tran = null)
{
var connEx = _connFactory.GetConnection(tran);
if (connEx.Conn.State == ConnectionState.Closed) await connEx.Conn.OpenAsync();
return connEx;
}
#endregion

}
Expand Down
10 changes: 10 additions & 0 deletions Dapper.Lite/Dapper.Lite/Session/IDbSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,16 @@ public partial interface IDbSession
/// 从连接池池获取连接
/// </summary>
Task<DbConnectionExt> GetConnectionAsync(DbTransactionExt tran = null);

/// <summary>
/// 从连接池池获取连接,已经Open
/// </summary>
DbConnectionExt GetOpenedConnection(DbTransactionExt tran = null);

/// <summary>
/// 从连接池池获取连接,已经Open
/// </summary>
Task<DbConnectionExt> GetOpenedConnectionAsync(DbTransactionExt tran = null);
#endregion

#region 设置 数据库字段名与实体类属性名映射
Expand Down
10 changes: 5 additions & 5 deletions Dapper.Lite/Dapper.Lite/SqlString/SqlQueryable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public ISqlQueryable<T> Queryable(string alias = null)
PropertyInfo propertyInfo = propertyInfoEx.PropertyInfo;
if (propertyInfo.GetCustomAttribute<ColumnAttribute>() != null)
{
_sqlString.Sql.AppendFormat("{0}.{1}{2}{3},", alias, _provider.OpenQuote, propertyInfoEx.FieldName, _provider.CloseQuote);
_sqlString.Sql.AppendFormat(" {0}.{1}{2}{3},", alias, _provider.OpenQuote, propertyInfoEx.FieldName, _provider.CloseQuote);
}
}

Expand Down Expand Up @@ -128,7 +128,7 @@ public ISqlQueryable<T> Where(Expression<Func<T, object>> expression)
ExpressionHelper<T> condition = new ExpressionHelper<T>(_provider, _sqlString.DbParameterNames, SqlStringMethod.Where);

DbParameter[] dbParameters;
string result = " (" + condition.VisitLambda(expression, out dbParameters) + ")";
string result = condition.VisitLambda(expression, out dbParameters);

if (dbParameters != null)
{
Expand Down Expand Up @@ -165,7 +165,7 @@ public ISqlQueryable<T> Where<U>(Expression<Func<U, object>> expression)
ExpressionHelper<T> condition = new ExpressionHelper<T>(_provider, _sqlString.DbParameterNames, SqlStringMethod.Where);

DbParameter[] dbParameters;
string result = " (" + condition.VisitLambda(expression, out dbParameters) + ")";
string result = condition.VisitLambda(expression, out dbParameters);

if (dbParameters != null)
{
Expand Down Expand Up @@ -202,7 +202,7 @@ public ISqlQueryable<T> Where<U>(Expression<Func<T, U, object>> expression)
ExpressionHelper<T> condition = new ExpressionHelper<T>(_provider, _sqlString.DbParameterNames, SqlStringMethod.Where);

DbParameter[] dbParameters;
string result = " (" + condition.VisitLambda(expression, out dbParameters) + ")";
string result = condition.VisitLambda(expression, out dbParameters);

if (dbParameters != null)
{
Expand Down Expand Up @@ -239,7 +239,7 @@ public ISqlQueryable<T> Where<U, D>(Expression<Func<T, U, D, object>> expression
ExpressionHelper<T> condition = new ExpressionHelper<T>(_provider, _sqlString.DbParameterNames, SqlStringMethod.Where);

DbParameter[] dbParameters;
string result = " (" + condition.VisitLambda(expression, out dbParameters) + ")";
string result = condition.VisitLambda(expression, out dbParameters);

if (dbParameters != null)
{
Expand Down
2 changes: 1 addition & 1 deletion Dapper.Lite/Dapper.Lite/SqlString/SqlString.cs
Original file line number Diff line number Diff line change
Expand Up @@ -706,7 +706,7 @@ internal string ParamsAddRange(DbParameter[] cmdParams, string sql)
}
else
{
sql = regex3.Replace(sql, newParamName + " ", 1);
sql = regex3.Replace(sql, newParamName + ",", 1);
}
}
}
Expand Down
23 changes: 19 additions & 4 deletions Dapper.Lite/Dapper.Lite/Utils/ExpressionHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,14 @@ public ExpValue VisitCondition(Expression exp)
else if (exp.NodeType == ExpressionType.Not) //支持 not in
{
UnaryExpression unaryExp = exp as UnaryExpression;
result = VisitMethodCall(unaryExp.Operand as MethodCallExpression, exp);
if (unaryExp.Operand is MethodCallExpression)
{
result = VisitMethodCall(unaryExp.Operand as MethodCallExpression, exp);
}
else
{
throw new Exception("不支持");
}
}
else
{
Expand All @@ -140,7 +147,15 @@ public ExpValue VisitBinaryConditionArray(BinaryExpression exp) //例:t.`remar
ExpValue left = VisitConditions(exp.Left);
ExpValue right = VisitConditions(exp.Right);

result.Sql = string.Format(" ({0} {1} {2}) ", left.Sql, ToSqlOperator(exp.NodeType), right.Sql);
var sqlOperator = ToSqlOperator(exp.NodeType);
if (sqlOperator == "AND")
{
result.Sql = string.Format(" {0} {1} {2} ", left.Sql, ToSqlOperator(exp.NodeType), right.Sql);
}
else
{
result.Sql = string.Format(" ({0} {1} {2}) ", left.Sql, ToSqlOperator(exp.NodeType), right.Sql);
}
result.Type = ExpValueType.SqlAndDbParameter;

result.DbParameters.AddRange(left.DbParameters);
Expand Down Expand Up @@ -207,13 +222,13 @@ public ExpValue VisitBinaryCondition(BinaryExpression exp) //例:t.`status` =
string markKey = _provider.GetParameterName(left.MemberAliasName, parameterType);

result.DbParameters.Add(_provider.GetDbParameter(left.MemberAliasName, right.Value));
result.Sql = string.Format(" ({0}.{1} {2} {3}) ", left.MemberParentName, left.MemberDBField, ToSqlOperator(exp.NodeType), sqlValue.Sql.Replace("{0}", markKey));
result.Sql = string.Format(" {0}.{1} {2} {3} ", left.MemberParentName, left.MemberDBField, ToSqlOperator(exp.NodeType), sqlValue.Sql.Replace("{0}", markKey));
}
else
{
string markKey = _provider.GetParameterName(left.MemberAliasName, right.Value.GetType());
result.DbParameters.Add(_provider.GetDbParameter(left.MemberAliasName, right.Value));
result.Sql = string.Format(" ({0}.{1} {2} {3}) ", left.MemberParentName, left.MemberDBField, ToSqlOperator(exp.NodeType), markKey);
result.Sql = string.Format(" {0}.{1} {2} {3} ", left.MemberParentName, left.MemberDBField, ToSqlOperator(exp.NodeType), markKey);
}
}
}
Expand Down
67 changes: 58 additions & 9 deletions Dapper.Lite/Dapper.LiteTest/DapperTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,8 @@
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DAL;
using Models;
using Utils;
using Dapper;
using static Dapper.SqlMapper;
using System.Data.Common;
using System.Threading;

namespace Dapper.LiteTest
Expand Down Expand Up @@ -58,7 +54,7 @@ from sys_user
[TestMethod]
public void TestUseDapper2()
{
ThreadPool.SetMinThreads(50, 50);
ThreadPool.SetMinThreads(200, 200);

Console.WriteLine("开始");
List<Task> tasks = new List<Task>();
Expand Down Expand Up @@ -156,10 +152,7 @@ public void TestUseDapper4()

using (var conn = db.GetConnection()) //此处从连接池获取连接,用完一定要释放,也可以不使用连接池,直接new MySqlConnection
{
var sql = db.Sql<SysUser>(@"
select *
from sys_user
where id < @id", 20);
var sql = db.Queryable<SysUser>().Where(t => t.Id < 20 && t.RealName.Contains("管理员"));

var list = conn.Conn.Query<SysUser>(sql.SQL, sql.DynamicParameters).ToList();

Expand Down Expand Up @@ -217,5 +210,61 @@ public void TestUseDapper5()
}
#endregion

#region 测试直接使用Dapper6
[TestMethod]
public void TestUseDapper6()
{
ThreadPool.SetMinThreads(50, 50);
List<Task> tasks = new List<Task>();
for (int i = 0; i < 50; i++)
{
int index = i;
var task = Task.Run(() =>
{
Random rnd = new Random();
var remark1 = $"测试修改用户{rnd.Next(1, 10000)}";
var remark2 = $"测试修改用户{rnd.Next(1, 10000)}";

var session = DapperLiteFactory.GetSession();

session.SetTypeMap<SysUser>(); //设置数据库字段名与实体类属性名映射

using (var connEx = session.GetOpenedConnection()) //此处从连接池获取连接,用完一定要释放,也可以不使用连接池,直接new MySqlConnection
{
var conn = connEx.Conn;
var trans = conn.BeginTransaction();

try
{
var sql1 = session.Sql<SysUser>(@"update sys_user set remark=@Remark where id=@Id", new { Remark = remark1, Id = 1 });
var sql2 = session.Sql<SysUser>(@"update sys_user set remark=@Remark where id=@Id", new { Remark = remark2, Id = 2 });
conn.Execute(sql1.SQL, sql1.DynamicParameters, trans);
conn.Execute(sql2.SQL, sql2.DynamicParameters, trans);

trans.Commit();
}
catch
{
trans.Rollback();
throw;
}

var sql3 = session.Queryable<SysUser>().Where(t => t.Id == 1);
var user1 = conn.QuerySingleOrDefault<SysUser>(sql3.SQL, sql3.DynamicParameters);
var sql4 = session.Queryable<SysUser>().Where(t => t.Id == 2);
var user2 = conn.QuerySingleOrDefault<SysUser>(sql4.SQL, sql4.DynamicParameters);

Assert.IsTrue(user1 != null);
Assert.IsTrue(user2 != null);
Console.WriteLine("完成" + index);
}
});
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray());

}
#endregion

}
}
34 changes: 34 additions & 0 deletions Dapper.Lite/Dapper.LiteTest/SqlStringTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Utils;

Expand All @@ -16,6 +17,8 @@ public class SqlStringTest
{
private IDapperLiteClient _db;

private Regex _regSpace = new Regex(@"[\s]{2,}");

#region 构造函数
public SqlStringTest()
{
Expand All @@ -36,5 +39,36 @@ public void TestUpdateSql1()
}
#endregion

#region TestQuerySql1
[TestMethod]
public void TestQuerySql1()
{
var sql = _db.Queryable<SysUser>().Where(t => t.Id < 20 && (t.UserName == "admin" || t.UserName == "admin2")).Where(t => t.Id > 10 && t.UserName == "admin3");
Assert.IsTrue(_regSpace.Replace(sql.SQL.Trim(), " ") == "select t.`id`, t.`user_name`, t.`real_name`, t.`password`, t.`remark`, t.`create_userid`, t.`create_time`, t.`update_userid`, t.`update_time` from `sys_user` t where t.`id` < @Id AND ( t.`user_name` = @UserName OR t.`user_name` = @UserName1 ) and t.`id` > @Id1 AND t.`user_name` = @UserName2");
Assert.IsTrue(sql.Params.Length == 5);
var parameters = sql.Params.ToList();
Assert.IsTrue(parameters.Exists(a => a.ParameterName == "Id"));
Assert.IsTrue(parameters.Exists(a => a.ParameterName == "Id1"));
Assert.IsTrue(parameters.Exists(a => a.ParameterName == "UserName"));
Assert.IsTrue(parameters.Exists(a => a.ParameterName == "UserName1"));
Assert.IsTrue(parameters.Exists(a => a.ParameterName == "UserName2"));
}
#endregion

#region TestQuerySql2
[TestMethod]
public void TestQuerySql2()
{
var sql = _db.Queryable<SysUser>().Where(t => t.Remark.Contains("测试") || !t.Remark.Contains("修改")).Where(t => t.Id < 20).Where(t => t.UserName == "admin");
Assert.IsTrue(_regSpace.Replace(sql.SQL.Trim(), " ") == "select t.`id`, t.`user_name`, t.`real_name`, t.`password`, t.`remark`, t.`create_userid`, t.`create_time`, t.`update_userid`, t.`update_time` from `sys_user` t where (t.`remark` like @Remark OR t.`remark` not like @Remark1) and t.`id` < @Id and t.`user_name` = @UserName");
Assert.IsTrue(sql.Params.Length == 4);
var parameters = sql.Params.ToList();
Assert.IsTrue(parameters.Exists(a => a.ParameterName == "Id"));
Assert.IsTrue(parameters.Exists(a => a.ParameterName == "UserName"));
Assert.IsTrue(parameters.Exists(a => a.ParameterName == "Remark"));
Assert.IsTrue(parameters.Exists(a => a.ParameterName == "Remark1"));
}
#endregion

}
}
5 changes: 1 addition & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -879,10 +879,7 @@ session.SetTypeMap<SysUser>(); //设置数据库字段名与实体类属性名
using (var conn = session.GetConnection()) //此处从连接池获取连接,用完一定要释放,也可以不使用连接池,直接new MySqlConnection
{
var sql = session.Sql<SysUser>(@"
select *
from sys_user
where id < @id", 20);
var sql = session.Where(t => t.Id < 20 && t.RealName.Contains("管理员"));

var list = conn.Conn.Query<SysUser>(sql.SQL, sql.DynamicParameters).ToList();

Expand Down

0 comments on commit e5a9c22

Please sign in to comment.