summaryrefslogtreecommitdiff
path: root/vendor/github.com/uptrace/bun/dialect/pgdialect/parser.go
blob: 08f4727db4d21722169b476bdc727bd5c125eab7 (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
package pgdialect

import (
	"bytes"
	"encoding/hex"

	"github.com/uptrace/bun/internal/parser"
)

type pgparser struct {
	parser.Parser
	buf []byte
}

func newParser(b []byte) *pgparser {
	p := new(pgparser)
	p.Reset(b)
	return p
}

func (p *pgparser) ReadLiteral(ch byte) []byte {
	p.Unread()
	lit, _ := p.ReadSep(',')
	return lit
}

func (p *pgparser) ReadUnescapedSubstring(ch byte) ([]byte, error) {
	return p.readSubstring(ch, false)
}

func (p *pgparser) ReadSubstring(ch byte) ([]byte, error) {
	return p.readSubstring(ch, true)
}

func (p *pgparser) readSubstring(ch byte, escaped bool) ([]byte, error) {
	ch, err := p.ReadByte()
	if err != nil {
		return nil, err
	}

	p.buf = p.buf[:0]
	for {
		if ch == '"' {
			break
		}

		next, err := p.ReadByte()
		if err != nil {
			return nil, err
		}

		if ch == '\\' {
			switch next {
			case '\\', '"':
				p.buf = append(p.buf, next)

				ch, err = p.ReadByte()
				if err != nil {
					return nil, err
				}
			default:
				p.buf = append(p.buf, '\\')
				ch = next
			}
			continue
		}

		if escaped && ch == '\'' && next == '\'' {
			p.buf = append(p.buf, next)
			ch, err = p.ReadByte()
			if err != nil {
				return nil, err
			}
			continue
		}

		p.buf = append(p.buf, ch)
		ch = next
	}

	if bytes.HasPrefix(p.buf, []byte("\\x")) && len(p.buf)%2 == 0 {
		data := p.buf[2:]
		buf := make([]byte, hex.DecodedLen(len(data)))
		n, err := hex.Decode(buf, data)
		if err != nil {
			return nil, err
		}
		return buf[:n], nil
	}

	return p.buf, nil
}

func (p *pgparser) ReadRange(ch byte) ([]byte, error) {
	p.buf = p.buf[:0]
	p.buf = append(p.buf, ch)

	for p.Valid() {
		ch = p.Read()
		p.buf = append(p.buf, ch)
		if ch == ']' || ch == ')' {
			break
		}
	}

	return p.buf, nil
}