1package clause
2
3import "strconv"
4
5// Limit limit clause
6type Limit struct {
7	Limit  int
8	Offset int
9}
10
11// Name where clause name
12func (limit Limit) Name() string {
13	return "LIMIT"
14}
15
16// Build build where clause
17func (limit Limit) Build(builder Builder) {
18	if limit.Limit > 0 {
19		builder.WriteString("LIMIT ")
20		builder.WriteString(strconv.Itoa(limit.Limit))
21	}
22	if limit.Offset > 0 {
23		if limit.Limit > 0 {
24			builder.WriteString(" ")
25		}
26		builder.WriteString("OFFSET ")
27		builder.WriteString(strconv.Itoa(limit.Offset))
28	}
29}
30
31// MergeClause merge order by clauses
32func (limit Limit) MergeClause(clause *Clause) {
33	clause.Name = ""
34
35	if v, ok := clause.Expression.(Limit); ok {
36		if limit.Limit == 0 && v.Limit != 0 {
37			limit.Limit = v.Limit
38		}
39
40		if limit.Offset == 0 && v.Offset > 0 {
41			limit.Offset = v.Offset
42		} else if limit.Offset < 0 {
43			limit.Offset = 0
44		}
45	}
46
47	clause.Expression = limit
48}
49