Skip to content

Commit

Permalink
feat: add input helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
ernado committed Dec 25, 2021
1 parent 4a0bef9 commit c86f7ec
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 1 deletion.
18 changes: 18 additions & 0 deletions proto/block.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package proto

import (
"fmt"
"strings"

"github.com/go-faster/errors"
)
Expand Down Expand Up @@ -62,6 +63,23 @@ func (i *BlockInfo) Decode(r *Reader) error {
}
}

// Input of query.
type Input []InputColumn

// 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", table, i.Columns())
}

// Columns returns "(foo, bar, baz)" formatted list of Input column names.
func (i Input) Columns() string {
var names []string
for _, v := range i {
names = append(names, v.Name)
}
return fmt.Sprintf("(%s)", strings.Join(names, ", "))
}

type InputColumn struct {
Name string
Data ColInput
Expand Down
2 changes: 1 addition & 1 deletion query.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ type Query struct {
QuotaKey string

// Input columns for INSERT operations.
Input []proto.InputColumn
Input proto.Input
// OnInput is called to allow ingesting more data to Input.
//
// The io.EOF reports that no more input should be ingested.
Expand Down
31 changes: 31 additions & 0 deletions query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,37 @@ func TestClient_Query(t *testing.T) {
require.Len(t, data, 4)
require.Equal(t, data, gotData)
})
t.Run("InsertHelper", func(t *testing.T) {
t.Parallel()
conn := Conn(t)

// Create table, no data fetch.
createTable := Query{
Body: "CREATE TABLE test_table (id UInt8) ENGINE = MergeTree ORDER BY id",
}
require.NoError(t, conn.Query(ctx, createTable), "create table")

data := proto.ColUInt8{1, 2, 3, 4}
input := proto.Input{
{Name: "id", Data: &data},
}
insertQuery := Query{
Body: input.Into("test_table"),
Input: input,
}
require.NoError(t, conn.Query(ctx, insertQuery), "insert")

var gotData proto.ColUInt8
selectData := Query{
Body: "SELECT * FROM test_table",
Result: proto.Results{
{Name: "id", Data: &gotData},
},
}
require.NoError(t, conn.Query(ctx, selectData), "select")
require.Len(t, data, 4)
require.Equal(t, data, gotData)
})
t.Run("InsertEnum8", func(t *testing.T) {
t.Parallel()
conn := Conn(t)
Expand Down

0 comments on commit c86f7ec

Please sign in to comment.