aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/github.com/ClickHouse/ch-go/proto/block.go
blob: 345480671a6b2bedf51c044bc0340bda46c117ed (plain) (blame)
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package proto

import (
	"fmt"
	"strconv"
	"strings"

	"github.com/go-faster/errors"
)

// BlockInfo describes block.
type BlockInfo struct {
	Overflows bool
	BucketNum int
}

func (i BlockInfo) String() string {
	return fmt.Sprintf("overflows: %v, buckets: %d", i.Overflows, i.BucketNum)
}

const endField = 0 // end of field pairs

// fields of BlockInfo.
const (
	blockInfoOverflows = 1
	blockInfoBucketNum = 2
)

// Encode to Buffer.
func (i BlockInfo) Encode(b *Buffer) {
	b.PutUVarInt(blockInfoOverflows)
	b.PutBool(i.Overflows)

	b.PutUVarInt(blockInfoBucketNum)
	b.PutInt32(int32(i.BucketNum))

	b.PutUVarInt(endField)
}

func (i *BlockInfo) Decode(r *Reader) error {
	for {
		f, err := r.UVarInt()
		if err != nil {
			return errors.Wrap(err, "field id")
		}
		switch f {
		case blockInfoOverflows:
			v, err := r.Bool()
			if err != nil {
				return errors.Wrap(err, "overflows")
			}
			i.Overflows = v
		case blockInfoBucketNum:
			v, err := r.Int32()
			if err != nil {
				return errors.Wrap(err, "bucket number")
			}
			i.BucketNum = int(v)
		case endField:
			return nil
		default:
			return errors.Errorf("unknown field %d", f)
		}
	}
}

// Input of query.
type Input []InputColumn

// Reset all columns that implement proto.Resettable.
func (i Input) Reset() {
	for _, c := range i {
		if col, ok := c.Data.(Resettable); ok {
			col.Reset()
		}
	}
}

// Into returns INSERT INTO table (c0, c..., cn) VALUES query.
func (i Input) Into(table string) string {
	return fmt.Sprintf("INSERT INTO %s %s VALUES", strconv.QuoteToASCII(table), i.Columns())
}

// Columns returns "(foo, bar, baz)" formatted list of Input column names.
func (i Input) Columns() string {
	var (
		b   strings.Builder
		buf [64]byte
	)

	b.WriteRune('(')
	for idx, v := range i {
		escaped := strconv.AppendQuoteToASCII(buf[:0], v.Name)
		b.Write(escaped)
		if idx != len(i)-1 {
			b.WriteRune(',')
		}
	}
	b.WriteRune(')')

	return b.String()
}

type InputColumn struct {
	Name string
	Data ColInput
}

// ResultColumn can be uses as part of Results or as single Result.
type ResultColumn struct {
	Name string    // Name of column. Inferred if not provided.
	Data ColResult // Data of column, required.
}

// DecodeResult implements Result as "single result" helper.
func (c ResultColumn) DecodeResult(r *Reader, version int, b Block) error {
	v := Results{c}
	return v.DecodeResult(r, version, b)
}

// AutoResult is ResultColumn with type inference.
func AutoResult(name string) ResultColumn {
	return ResultColumn{
		Name: name,
		Data: &ColAuto{},
	}
}

func (c InputColumn) EncodeStart(buf *Buffer, version int) {
	buf.PutString(c.Name)
	buf.PutString(string(c.Data.Type()))
	if FeatureCustomSerialization.In(version) {
		buf.PutBool(false) // no custom serialization
	}
}

type Block struct {
	Info    BlockInfo
	Columns int
	Rows    int
}

func (b Block) EncodeAware(buf *Buffer, version int) {
	if FeatureBlockInfo.In(version) {
		b.Info.Encode(buf)
	}

	buf.PutInt(b.Columns)
	buf.PutInt(b.Rows)
}

func (b Block) EncodeBlock(buf *Buffer, version int, input []InputColumn) error {
	if FeatureBlockInfo.In(version) {
		b.Info.Encode(buf)
	}
	if err := b.EncodeRawBlock(buf, version, input); err != nil {
		return errors.Wrap(err, "raw block")
	}
	return nil
}

func (b Block) EncodeRawBlock(buf *Buffer, version int, input []InputColumn) error {
	buf.PutInt(b.Columns)
	buf.PutInt(b.Rows)
	for _, col := range input {
		if r := col.Data.Rows(); r != b.Rows {
			return errors.Errorf("%q has %d rows, expected %d", col.Name, r, b.Rows)
		}
		col.EncodeStart(buf, version)
		if v, ok := col.Data.(Preparable); ok {
			if err := v.Prepare(); err != nil {
				return errors.Wrapf(err, "prepare %q", col.Name)
			}
		}
		if col.Data.Rows() == 0 {
			continue
		}
		if v, ok := col.Data.(StateEncoder); ok {
			v.EncodeState(buf)
		}
		col.Data.EncodeColumn(buf)
	}
	return nil
}

// This constrains can prevent accidental OOM and allow early detection
// of erroneous column or row count.
//
// Just empirical values, there are no such limits in spec or in ClickHouse,
// so is subject to change if false-positives occur.
const (
	maxColumnsInBlock = 1_000_000
	maxRowsInBLock    = 100_000_000
)

func checkRows(n int) error {
	if n < 0 {
		return errors.New("negative")
	}
	if n > maxRowsInBLock {
		// Most blocks should be less than 100M values, but technically
		// there is no limit (can be several billions).
		// 1B rows is too big and probably several gigabytes in RSS.
		//
		// The 100M UInt64 block is ~655MB RSS, should be pretty safe and
		// protect from accidental (e.g. cosmic rays) rows count corruption.
		return errors.Errorf("%d is suspiciously big, maximum is %d (preventing possible OOM)", n, maxRowsInBLock)
	}
	return nil
}

func (b *Block) End() bool {
	return b.Columns == 0 && b.Rows == 0
}

func (b *Block) DecodeRawBlock(r *Reader, version int, target Result) error {
	{
		v, err := r.Int()
		if err != nil {
			return errors.Wrap(err, "columns")
		}
		if v > maxColumnsInBlock || v < 0 {
			return errors.Errorf("invalid columns number %d", v)
		}
		b.Columns = v
	}
	{
		v, err := r.Int()
		if err != nil {
			return errors.Wrap(err, "rows")
		}
		if err := checkRows(v); err != nil {
			return errors.Wrap(err, "rows count")
		}
		b.Rows = v
	}
	if b.End() {
		// End of data, special case.
		return nil
	}
	if target == nil && b.Rows > 0 {
		return errors.New("got rows without target")
	}
	if target == nil {
		// Just skipping rows and types.
		for i := 0; i < b.Columns; i++ {
			// Name.
			if _, err := r.Str(); err != nil {
				return errors.Wrapf(err, "column [%d] name", i)
			}
			// Type.
			if _, err := r.Str(); err != nil {
				return errors.Wrapf(err, "column [%d] type", i)
			}
			if FeatureCustomSerialization.In(version) {
				// Custom serialization flag.
				v, err := r.Bool()
				if err != nil {
					return errors.Wrapf(err, "column [%d] custom serialization flag", i)
				}
				if v {
					return errors.Errorf("column [%d] has custom serialization (not supported)", i)
				}
			}
		}
		return nil
	}
	if err := target.DecodeResult(r, version, *b); err != nil {
		return errors.Wrap(err, "target")
	}

	return nil
}

func (b *Block) DecodeBlock(r *Reader, version int, target Result) error {
	if FeatureBlockInfo.In(version) {
		if err := b.Info.Decode(r); err != nil {
			return errors.Wrap(err, "info")
		}
	}
	if err := b.DecodeRawBlock(r, version, target); err != nil {
		return errors.Wrap(err, "raw block")
	}

	return nil
}