-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathMsSqlSelectStatementVisitor.cs
80 lines (70 loc) · 2.72 KB
/
MsSqlSelectStatementVisitor.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
* _____ ______
* /_ / ____ ____ ____ _________ / __/ /_
* / / / __ \/ __ \/ __ \/ ___/ __ \/ /_/ __/
* / /__/ /_/ / / / / /_/ /\_ \/ /_/ / __/ /_
* /____/\____/_/ /_/\__ /____/\____/_/ \__/
* /____/
*
* Authors:
* 钟峰(Popeye Zhong) <[email protected]>
*
* Copyright (C) 2010-2020 Zongsoft Studio <http://www.zongsoft.com>
*
* This file is part of Zongsoft.Data.MsSql library.
*
* The Zongsoft.Data.MsSql is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3.0 of the License,
* or (at your option) any later version.
*
* The Zongsoft.Data.MsSql is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the Zongsoft.Data.MsSql library. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using Zongsoft.Data.Common;
using Zongsoft.Data.Common.Expressions;
namespace Zongsoft.Data.MsSql
{
public class MsSqlSelectStatementVisitor : SelectStatementVisitor
{
#region 单例字段
public static readonly MsSqlSelectStatementVisitor Instance = new MsSqlSelectStatementVisitor();
#endregion
#region 构造函数
private MsSqlSelectStatementVisitor() { }
#endregion
#region 重写方法
protected override void OnVisit(ExpressionVisitorContext context, SelectStatement statement)
{
//由于分页子句必须依赖于排序(OrderBy)子句,所以在没有指定排序子句的情况下默认以主键进行排序
if(statement.Paging != null && statement.Paging.PageSize > 0 && statement.OrderBy == null && statement.Table != null)
{
statement.OrderBy = new OrderByClause();
foreach(var key in statement.Table.Entity.Key)
statement.OrderBy.Add(statement.Table.CreateField(key));
}
//调用基类同名方法
base.OnVisit(context, statement);
if(statement.Paging != null && statement.Paging.PageSize > 0 && statement.OrderBy != null)
this.VisitPaging(context, statement.Paging);
}
#endregion
#region 虚拟方法
protected virtual void VisitPaging(ExpressionVisitorContext context, Paging paging)
{
if(context.Output.Length > 0)
context.WriteLine();
if(paging.PageIndex > 0)
context.Write($"OFFSET {(paging.PageIndex - 1) * paging.PageSize} ROWS FETCH NEXT {paging.PageSize} ROWS ONLY");
else
context.Write($"OFFSET 0 ROWS FETCH NEXT {paging.PageSize} ROWS ONLY");
}
#endregion
}
}