-
Notifications
You must be signed in to change notification settings - Fork 1
/
args.go
89 lines (75 loc) · 2.18 KB
/
args.go
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
81
82
83
84
85
86
87
88
89
// Copyright 2020 xgfone
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package sqlx
import (
"database/sql"
"sync"
)
var argspool = sync.Pool{
New: func() any {
args := make([]any, 0, DefaultArgsCap)
return &ArgsBuilder{pool: true, args: args}
},
}
func getargs() *ArgsBuilder { return argspool.Get().(*ArgsBuilder) }
func putargs(a *ArgsBuilder) { a.Reset(); argspool.Put(a) }
// DefaultArgsCap is the default capacity to be allocated for ArgsBuilder.
var DefaultArgsCap = 32
// ArgsBuilder is used to build the arguments.
type ArgsBuilder struct {
Dialect
args []any
pool bool
}
// GetArgsBuilderFromPool acquires an ArgsBuilder with the dialect from pool.
func GetArgsBuilderFromPool(dialect Dialect) *ArgsBuilder {
a := getargs()
a.Dialect = dialect
return a
}
// WithDialect sets the dialect and returns itself.
func (a *ArgsBuilder) WithDialect(dialect Dialect) *ArgsBuilder {
a.Dialect = dialect
return a
}
// Release puts itself into the pool if it is acquired from the pool.
func (a *ArgsBuilder) Release() {
if a != nil && a.pool {
putargs(a)
}
}
// Reset resets the args to empty.
func (a *ArgsBuilder) Reset() {
clear(a.args)
a.args = a.args[:0]
}
// Add appends the argument and returns the its placeholder.
//
// If arg is the type of sql.NamedArg, it will use @arg.Name as the placeholder
// and arg.Value as the value.
func (a *ArgsBuilder) Add(arg any) (placeholder string) {
if na, ok := arg.(sql.NamedArg); ok {
a.args = append(a.args, na.Value)
return "@" + na.Name
}
a.args = append(a.args, arg)
return a.Placeholder(len(a.args))
}
// Args returns the added arguments.
func (a *ArgsBuilder) Args() (args []any) {
if a != nil {
args = a.args
}
return
}