summaryrefslogtreecommitdiff
path: root/vendor/github.com/ncruces/go-sqlite3/quote.go
blob: d1cd6fa8756e2fcd78002f195ad14c674590445e (plain)
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package sqlite3

import (
	"bytes"
	"math"
	"strconv"
	"strings"
	"time"
	"unsafe"

	"github.com/ncruces/go-sqlite3/internal/util"
)

// Quote escapes and quotes a value
// making it safe to embed in SQL text.
func Quote(value any) string {
	switch v := value.(type) {
	case nil:
		return "NULL"
	case bool:
		if v {
			return "1"
		} else {
			return "0"
		}

	case int:
		return strconv.Itoa(v)
	case int64:
		return strconv.FormatInt(v, 10)
	case float64:
		switch {
		case math.IsNaN(v):
			return "NULL"
		case math.IsInf(v, 1):
			return "9.0e999"
		case math.IsInf(v, -1):
			return "-9.0e999"
		}
		return strconv.FormatFloat(v, 'g', -1, 64)
	case time.Time:
		return "'" + v.Format(time.RFC3339Nano) + "'"

	case string:
		if strings.IndexByte(v, 0) >= 0 {
			break
		}

		buf := make([]byte, 2+len(v)+strings.Count(v, "'"))
		buf[0] = '\''
		i := 1
		for _, b := range []byte(v) {
			if b == '\'' {
				buf[i] = b
				i += 1
			}
			buf[i] = b
			i += 1
		}
		buf[i] = '\''
		return unsafe.String(&buf[0], len(buf))

	case []byte:
		buf := make([]byte, 3+2*len(v))
		buf[0] = 'x'
		buf[1] = '\''
		i := 2
		for _, b := range v {
			const hex = "0123456789ABCDEF"
			buf[i+0] = hex[b/16]
			buf[i+1] = hex[b%16]
			i += 2
		}
		buf[i] = '\''
		return unsafe.String(&buf[0], len(buf))

	case ZeroBlob:
		if v > ZeroBlob(1e9-3)/2 {
			break
		}

		buf := bytes.Repeat([]byte("0"), int(3+2*int64(v)))
		buf[0] = 'x'
		buf[1] = '\''
		buf[len(buf)-1] = '\''
		return unsafe.String(&buf[0], len(buf))
	}

	panic(util.ValueErr)
}

// QuoteIdentifier escapes and quotes an identifier
// making it safe to embed in SQL text.
func QuoteIdentifier(id string) string {
	if strings.IndexByte(id, 0) >= 0 {
		panic(util.ValueErr)
	}

	buf := make([]byte, 2+len(id)+strings.Count(id, `"`))
	buf[0] = '"'
	i := 1
	for _, b := range []byte(id) {
		if b == '"' {
			buf[i] = b
			i += 1
		}
		buf[i] = b
		i += 1
	}
	buf[i] = '"'
	return unsafe.String(&buf[0], len(buf))
}