- 修复 SqlServer2005/2008 Skip 问题(未设置 Take 时);

This commit is contained in:
2881099 2022-07-14 14:01:40 +08:00
parent 9088da180c
commit 50b7d5307d
6 changed files with 103 additions and 26 deletions

View File

@ -16,6 +16,7 @@ using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Numerics; using System.Numerics;
using System.Reflection; using System.Reflection;
using System.Text;
using System.Text.Encodings.Web; using System.Text.Encodings.Web;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
@ -301,7 +302,7 @@ namespace base_entity
var fsql = new FreeSql.FreeSqlBuilder() var fsql = new FreeSql.FreeSqlBuilder()
.UseAutoSyncStructure(true) .UseAutoSyncStructure(true)
.UseNoneCommandParameter(true) .UseNoneCommandParameter(true)
.UseGenerateCommandParameterWithLambda(true)
.UseConnectionString(FreeSql.DataType.Sqlite, "data source=test1.db;max pool size=5") .UseConnectionString(FreeSql.DataType.Sqlite, "data source=test1.db;max pool size=5")
//.UseSlave("data source=test1.db", "data source=test2.db", "data source=test3.db", "data source=test4.db") //.UseSlave("data source=test1.db", "data source=test2.db", "data source=test3.db", "data source=test4.db")
@ -311,7 +312,7 @@ namespace base_entity
//.UseConnectionString(FreeSql.DataType.Firebird, @"database=localhost:D:\fbdata\EXAMPLES.fdb;user=sysdba;password=123456;max pool size=5") //.UseConnectionString(FreeSql.DataType.Firebird, @"database=localhost:D:\fbdata\EXAMPLES.fdb;user=sysdba;password=123456;max pool size=5")
//.UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=2") .UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=2")
//.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=3;TrustServerCertificate=true") //.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=3;TrustServerCertificate=true")
@ -339,11 +340,17 @@ namespace base_entity
.UseMonitorCommand(null, (umcmd, log) => Console.WriteLine(umcmd.Connection.ConnectionString + ":" + umcmd.CommandText + "\r\n")) .UseMonitorCommand(null, (umcmd, log) => Console.WriteLine(umcmd.Connection.ConnectionString + ":" + umcmd.CommandText + "\r\n"))
.UseLazyLoading(true) .UseLazyLoading(true)
.UseGenerateCommandParameterWithLambda(true) //.UseGenerateCommandParameterWithLambda(true)
.Build(); .Build();
BaseEntity.Initialization(fsql, () => _asyncUow.Value); BaseEntity.Initialization(fsql, () => _asyncUow.Value);
#endregion #endregion
Dictionary<string, object> dic22 = new Dictionary<string, object>();
dic22.Add("id", 1);
dic22.Add("name", "xxxx");
dic22.Add("bytes", Encoding.UTF8.GetBytes("我是中国人"));
var sqlBytes = fsql.InsertDict(dic22).AsTable("table1").ToSql();
var sqlToYear = fsql.Select<User1>().ToSql(a => a.CreateTime.Year); var sqlToYear = fsql.Select<User1>().ToSql(a => a.CreateTime.Year);
TestExp(fsql); TestExp(fsql);

View File

@ -29,21 +29,21 @@ namespace FreeSql.Tests.DataContext.SqlServer
private void ClearDataBase() private void ClearDataBase()
{ {
var dataTables = SqlServer.DbFirst.GetTablesByDatabase(); //var dataTables = SqlServer.DbFirst.GetTablesByDatabase();
if (dataTables.Any(item => item.Name == "TopicAddField" && item.Schema == "dbo2")) //if (dataTables.Any(item => item.Name == "TopicAddField" && item.Schema == "dbo2"))
{ //{
SqlServer.Ado.ExecuteNonQuery("TRUNCATE TABLE dbo2.TopicAddField "); // SqlServer.Ado.ExecuteNonQuery("TRUNCATE TABLE dbo2.TopicAddField ");
SqlServer.Ado.ExecuteNonQuery("DROP TABLE dbo2.TopicAddField"); // SqlServer.Ado.ExecuteNonQuery("DROP TABLE dbo2.TopicAddField");
SqlServer.Ado.ExecuteNonQuery("DROP SCHEMA dbo2"); // SqlServer.Ado.ExecuteNonQuery("DROP SCHEMA dbo2");
} //}
var tempTables = new string[] { "cccccdddwww", "song", "tag", "Song_tag", "tb_alltype", "tb_topic", "tb_topic22", //var tempTables = new string[] { "cccccdddwww", "song", "tag", "Song_tag", "tb_alltype", "tb_topic", "tb_topic22",
"tb_topic22211", "tb_topic111333", "TestTypeInfo", "TestTypeInfo333", "TestTypeParentInfo", // "tb_topic22211", "tb_topic111333", "TestTypeInfo", "TestTypeInfo333", "TestTypeParentInfo",
"TestTypeParentInfo23123", "xxdkdkdk1222", "xxx"}; // "TestTypeParentInfo23123", "xxdkdkdk1222", "xxx"};
foreach (var tempTable in tempTables) //foreach (var tempTable in tempTables)
{ //{
//DeleteTmpTable(dataTables, tempTable); // //DeleteTmpTable(dataTables, tempTable);
} //}
} }
private void DeleteTmpTable(List<DatabaseModel.DbTableInfo> dbTables, string deleteTableName, string schemaName = "dbo") private void DeleteTmpTable(List<DatabaseModel.DbTableInfo> dbTables, string deleteTableName, string schemaName = "dbo")

View File

@ -1,4 +1,4 @@
using FreeSql.DataAnnotations; using FreeSql.DataAnnotations;
using FreeSql.Tests.DataContext.SqlServer; using FreeSql.Tests.DataContext.SqlServer;
using SaleIDO.Entity.Storeage; using SaleIDO.Entity.Storeage;
using System; using System;
@ -79,6 +79,7 @@ namespace FreeSql.Tests.SqlServer
dicRet = fsql.InsertDict(diclist).AsTable("table1dict").NoneParameter().ExecuteInserted(); dicRet = fsql.InsertDict(diclist).AsTable("table1dict").NoneParameter().ExecuteInserted();
dicRet = fsql.DeleteDict(diclist).AsTable("table1dict").ExecuteDeleted(); dicRet = fsql.DeleteDict(diclist).AsTable("table1dict").ExecuteDeleted();
var sss = fsql.InsertOrUpdateDict(dic).AsTable("table1");
sql1 = fsql.InsertOrUpdateDict(dic).AsTable("table1").WherePrimary("id").ToSql(); sql1 = fsql.InsertOrUpdateDict(dic).AsTable("table1").WherePrimary("id").ToSql();
sql2 = fsql.InsertOrUpdateDict(diclist).AsTable("table1").WherePrimary("id").ToSql(); sql2 = fsql.InsertOrUpdateDict(diclist).AsTable("table1").WherePrimary("id").ToSql();

View File

@ -1,9 +1,13 @@
using FreeSql.DataAnnotations; using FreeSql.DataAnnotations;
using FreeSql.Internal.CommonProvider;
using FreeSql.SqlServer;
using FreeSql.Tests.DataContext.SqlServer; using FreeSql.Tests.DataContext.SqlServer;
using NetTaste; using NetTaste;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Threading;
using Xunit; using Xunit;
namespace FreeSql.Tests.SqlServer namespace FreeSql.Tests.SqlServer
@ -967,8 +971,61 @@ ORDER BY newid()", t1);
[Fact] [Fact]
public void Skip_Offset() public void Skip_Offset()
{ {
var sql = select.Offset(10).Limit(10).ToList(); var list = select.Offset(10).Limit(10).ToList();
var sqlSkip = select.Skip(10).ToSql();
Assert.Equal(@"SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime]
FROM [tb_topic22] a
ORDER BY a.[Id]
OFFSET 10 ROW", sqlSkip);
list = select.Skip(10).ToList();
using (var fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=3;TrustServerCertificate=true")
.UseAutoSyncStructure(true)
.UseMonitorCommand(
cmd => Trace.WriteLine("\r\n线程" + Thread.CurrentThread.ManagedThreadId + ": " + cmd.CommandText) //监听SQL命令对象在执行前
//, (cmd, traceLog) => Console.WriteLine(traceLog)
)
.Build())
{
var commUtils = (fsql.Select<object>() as Select0Provider)._commonUtils as SqlServerUtils;
commUtils.ServerVersion = 9;
sqlSkip = fsql.Select<Topic>().Skip(10).ToSql();
Assert.Equal(@"WITH t AS ( SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime], ROW_NUMBER() OVER(ORDER BY a.[Id]) AS __rownum__
FROM [tb_topic22] a ) SELECT t.* FROM t where __rownum__ > 10", sqlSkip);
list = fsql.Select<Topic>().Skip(10).ToList();
sqlSkip = fsql.Select<Topic>().Limit(10).ToSql();
Assert.Equal(@"SELECT TOP 10 a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime]
FROM [tb_topic22] a
ORDER BY a.[Id]", sqlSkip);
list = fsql.Select<Topic>().Limit(10).ToList();
sqlSkip = fsql.Select<Topic>().Skip(10).Limit(10).ToSql();
Assert.Equal(@"WITH t AS ( SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime], ROW_NUMBER() OVER(ORDER BY a.[Id]) AS __rownum__
FROM [tb_topic22] a ) SELECT t.* FROM t where __rownum__ between 11 and 20", sqlSkip);
list = fsql.Select<Topic>().Skip(10).Limit(10).ToList();
sqlSkip = fsql.Select<Topic>().Skip(10).OrderBy(a => a.Title).ToSql();
Assert.Equal(@"WITH t AS ( SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime], ROW_NUMBER() OVER(ORDER BY a.[Title]) AS __rownum__
FROM [tb_topic22] a ) SELECT t.* FROM t where __rownum__ > 10", sqlSkip);
list = fsql.Select<Topic>().Skip(10).OrderBy(a => a.Title).ToList();
sqlSkip = fsql.Select<Topic>().Limit(10).OrderBy(a => a.Title).ToSql();
Assert.Equal(@"SELECT TOP 10 a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime]
FROM [tb_topic22] a
ORDER BY a.[Title]", sqlSkip);
list = fsql.Select<Topic>().Limit(10).OrderBy(a => a.Title).ToList();
sqlSkip = fsql.Select<Topic>().Skip(10).Limit(10).OrderBy(a => a.Title).ToSql();
Assert.Equal(@"WITH t AS ( SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime], ROW_NUMBER() OVER(ORDER BY a.[Title]) AS __rownum__
FROM [tb_topic22] a ) SELECT t.* FROM t where __rownum__ between 11 and 20", sqlSkip);
list = fsql.Select<Topic>().Skip(10).Limit(10).OrderBy(a => a.Title).ToList();
} }
}
[Fact] [Fact]
public void Take_Limit() public void Take_Limit()
{ {

View File

@ -42,7 +42,7 @@ namespace FreeSql.Odbc.SqlServer
if (_skip <= 0 && _limit > 0) sb.Append("TOP ").Append(_limit).Append(" "); if (_skip <= 0 && _limit > 0) sb.Append("TOP ").Append(_limit).Append(" ");
sb.Append(field); sb.Append(field);
if (_limit > 0) if (_limit > 0 || _skip > 0)
{ {
if (string.IsNullOrEmpty(_orderby)) if (string.IsNullOrEmpty(_orderby))
{ {
@ -56,7 +56,7 @@ namespace FreeSql.Odbc.SqlServer
_orderby = _groupby.Replace("GROUP BY ", "ORDER BY "); _orderby = _groupby.Replace("GROUP BY ", "ORDER BY ");
} }
if (_skip > 0) // 注意这个判断,大于 0 才使用 ROW_NUMBER ,否则属于第一页直接使用 TOP if (_skip > 0) // 注意这个判断,大于 0 才使用 ROW_NUMBER ,否则属于第一页直接使用 TOP
sb.Append(", ROW_NUMBER() OVER(").Append(_orderby).Append(") AS __rownum__"); sb.Append(", ROW_NUMBER() OVER(").Append(_orderby.Trim('\r', '\n', ' ')).Append(") AS __rownum__");
} }
sb.Append(" \r\nFROM "); sb.Append(" \r\nFROM ");
var tbsjoin = _tables.Where(a => a.Type != SelectTableInfoType.From).ToArray(); var tbsjoin = _tables.Where(a => a.Type != SelectTableInfoType.From).ToArray();
@ -133,7 +133,13 @@ namespace FreeSql.Odbc.SqlServer
if (_skip <= 0) if (_skip <= 0)
sb.Append(_orderby); sb.Append(_orderby);
else else
sb.Insert(0, "WITH t AS ( ").Append(" ) SELECT t.* FROM t where __rownum__ between ").Append(_skip + 1).Append(" and ").Append(_skip + _limit); {
sb.Insert(0, "WITH t AS ( ").Append(" ) SELECT t.* FROM t where __rownum__");
if (_limit > 0)
sb.Append(" between ").Append(_skip + 1).Append(" and ").Append(_skip + _limit);
else
sb.Append(" > ").Append(_skip);
}
sbnav.Clear(); sbnav.Clear();
if (tbUnionsGt0) sb.Append(") ftb"); if (tbUnionsGt0) sb.Append(") ftb");

View File

@ -42,7 +42,7 @@ namespace FreeSql.SqlServer.Curd
if (_skip <= 0 && _limit > 0) sb.Append("TOP ").Append(_limit).Append(" "); if (_skip <= 0 && _limit > 0) sb.Append("TOP ").Append(_limit).Append(" ");
sb.Append(field); sb.Append(field);
if (_limit > 0) if (_limit > 0 || _skip > 0)
{ {
if (string.IsNullOrEmpty(_orderby)) if (string.IsNullOrEmpty(_orderby))
{ {
@ -56,7 +56,7 @@ namespace FreeSql.SqlServer.Curd
_orderby = _groupby.Replace("GROUP BY ", "ORDER BY "); _orderby = _groupby.Replace("GROUP BY ", "ORDER BY ");
} }
if (_skip > 0) // 注意这个判断,大于 0 才使用 ROW_NUMBER ,否则属于第一页直接使用 TOP if (_skip > 0) // 注意这个判断,大于 0 才使用 ROW_NUMBER ,否则属于第一页直接使用 TOP
sb.Append(", ROW_NUMBER() OVER(").Append(_orderby).Append(") AS __rownum__"); sb.Append(", ROW_NUMBER() OVER(").Append(_orderby.Trim('\r', '\n', ' ')).Append(") AS __rownum__");
} }
sb.Append(" \r\nFROM "); sb.Append(" \r\nFROM ");
var tbsjoin = _tables.Where(a => a.Type != SelectTableInfoType.From).ToArray(); var tbsjoin = _tables.Where(a => a.Type != SelectTableInfoType.From).ToArray();
@ -133,7 +133,13 @@ namespace FreeSql.SqlServer.Curd
if (_skip <= 0) if (_skip <= 0)
sb.Append(_orderby); sb.Append(_orderby);
else else
sb.Insert(0, "WITH t AS ( ").Append(" ) SELECT t.* FROM t where __rownum__ between ").Append(_skip + 1).Append(" and ").Append(_skip + _limit); {
sb.Insert(0, "WITH t AS ( ").Append(" ) SELECT t.* FROM t where __rownum__");
if (_limit > 0)
sb.Append(" between ").Append(_skip + 1).Append(" and ").Append(_skip + _limit);
else
sb.Append(" > ").Append(_skip);
}
sbnav.Clear(); sbnav.Clear();
if (tbUnionsGt0) sb.Append(") ftb"); if (tbUnionsGt0) sb.Append(") ftb");