2025-05-06 07:18:11 +02:00
|
|
|
package database
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Instruction string
|
|
|
|
|
|
|
|
const (
|
|
|
|
NowInstruction Instruction = "NOW()"
|
|
|
|
NullInstruction Instruction = "NULL"
|
|
|
|
)
|
|
|
|
|
2025-05-08 07:42:53 +02:00
|
|
|
// StatementBuilder is a helper to build SQL statement.
|
2025-05-06 07:18:11 +02:00
|
|
|
type StatementBuilder struct {
|
|
|
|
strings.Builder
|
|
|
|
args []any
|
|
|
|
existingArgs map[any]string
|
|
|
|
}
|
|
|
|
|
2025-05-08 07:42:53 +02:00
|
|
|
// WriteArgs adds the argument to the statement and writes the placeholder to the query.
|
2025-05-06 07:18:11 +02:00
|
|
|
func (b *StatementBuilder) WriteArg(arg any) {
|
|
|
|
b.WriteString(b.AppendArg(arg))
|
|
|
|
}
|
|
|
|
|
2025-05-08 07:42:53 +02:00
|
|
|
// AppebdArg adds the argument to the statement and returns the placeholder.
|
2025-05-06 07:18:11 +02:00
|
|
|
func (b *StatementBuilder) AppendArg(arg any) (placeholder string) {
|
|
|
|
if b.existingArgs == nil {
|
|
|
|
b.existingArgs = make(map[any]string)
|
|
|
|
}
|
2025-07-18 15:55:18 +01:00
|
|
|
|
2025-05-06 07:18:11 +02:00
|
|
|
if instruction, ok := arg.(Instruction); ok {
|
|
|
|
return string(instruction)
|
|
|
|
}
|
|
|
|
|
|
|
|
b.args = append(b.args, arg)
|
|
|
|
placeholder = "$" + strconv.Itoa(len(b.args))
|
|
|
|
b.existingArgs[arg] = placeholder
|
|
|
|
return placeholder
|
|
|
|
}
|
|
|
|
|
2025-05-08 07:42:53 +02:00
|
|
|
// AppendArgs adds the arguments to the statement and doesn't return the placeholders.
|
2025-05-06 07:18:11 +02:00
|
|
|
func (b *StatementBuilder) AppendArgs(args ...any) {
|
|
|
|
for _, arg := range args {
|
|
|
|
b.AppendArg(arg)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2025-05-08 07:42:53 +02:00
|
|
|
// Args returns the arguments added to the statement.
|
2025-05-06 07:18:11 +02:00
|
|
|
func (b *StatementBuilder) Args() []any {
|
|
|
|
return b.args
|
|
|
|
}
|