summaryrefslogtreecommitdiff
path: root/vendor/github.com/uptrace/bun/schema/dialect.go
blob: f015807dc75b0ef1698da1d43217cb06f6814e5b (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
113
114
115
116
117
118
119
120
121
122
package schema

import (
	"database/sql"
	"strconv"
	"time"

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

type Dialect interface {
	Init(db *sql.DB)

	Name() dialect.Name
	Features() feature.Feature

	Tables() *Tables
	OnTable(table *Table)

	IdentQuote() byte

	AppendUint32(b []byte, n uint32) []byte
	AppendUint64(b []byte, n uint64) []byte
	AppendTime(b []byte, tm time.Time) []byte
	AppendBytes(b []byte, bs []byte) []byte
	AppendJSON(b, jsonb []byte) []byte
}

//------------------------------------------------------------------------------

type BaseDialect struct{}

func (BaseDialect) AppendUint32(b []byte, n uint32) []byte {
	return strconv.AppendUint(b, uint64(n), 10)
}

func (BaseDialect) AppendUint64(b []byte, n uint64) []byte {
	return strconv.AppendUint(b, n, 10)
}

func (BaseDialect) AppendTime(b []byte, tm time.Time) []byte {
	b = append(b, '\'')
	b = tm.UTC().AppendFormat(b, "2006-01-02 15:04:05.999999-07:00")
	b = append(b, '\'')
	return b
}

func (BaseDialect) AppendBytes(b, bs []byte) []byte {
	return dialect.AppendBytes(b, bs)
}

func (BaseDialect) AppendJSON(b, jsonb []byte) []byte {
	b = append(b, '\'')

	p := parser.New(jsonb)
	for p.Valid() {
		c := p.Read()
		switch c {
		case '"':
			b = append(b, '"')
		case '\'':
			b = append(b, "''"...)
		case '\000':
			continue
		case '\\':
			if p.SkipBytes([]byte("u0000")) {
				b = append(b, `\\u0000`...)
			} else {
				b = append(b, '\\')
				if p.Valid() {
					b = append(b, p.Read())
				}
			}
		default:
			b = append(b, c)
		}
	}

	b = append(b, '\'')

	return b
}

//------------------------------------------------------------------------------

type nopDialect struct {
	BaseDialect

	tables   *Tables
	features feature.Feature
}

func newNopDialect() *nopDialect {
	d := new(nopDialect)
	d.tables = NewTables(d)
	d.features = feature.Returning
	return d
}

func (d *nopDialect) Init(*sql.DB) {}

func (d *nopDialect) Name() dialect.Name {
	return dialect.Invalid
}

func (d *nopDialect) Features() feature.Feature {
	return d.features
}

func (d *nopDialect) Tables() *Tables {
	return d.tables
}

func (d *nopDialect) OnField(field *Field) {}

func (d *nopDialect) OnTable(table *Table) {}

func (d *nopDialect) IdentQuote() byte {
	return '"'
}