Skip to content

Commit

Permalink
Improve CSV value formatting.
Browse files Browse the repository at this point in the history
  • Loading branch information
cube2222 committed Oct 15, 2022
1 parent 6644557 commit 2e6b0cd
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 3 deletions.
2 changes: 0 additions & 2 deletions octosql/values.go
Original file line number Diff line number Diff line change
Expand Up @@ -424,8 +424,6 @@ func (value Value) append(builder *strings.Builder) {
}

func (value Value) ToRawGoValue(t Type) interface{} {
// TODO: Add complex types.
// TODO: Fix union handling.
switch value.TypeID {
case TypeIDNull:
return nil
Expand Down
28 changes: 27 additions & 1 deletion outputs/formats/csv_format.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import (
"encoding/csv"
"fmt"
"io"
"strconv"
"strings"
"time"

"github.com/cube2222/octosql/octosql"
"github.com/cube2222/octosql/physical"
Expand Down Expand Up @@ -33,13 +36,36 @@ func (t *CSVFormatter) SetSchema(schema physical.Schema) {
}

func (t *CSVFormatter) Write(values []octosql.Value) error {
var builder strings.Builder
row := make([]string, len(values))
for i := range values {
row[i] = fmt.Sprintf("%v", values[i].ToRawGoValue(t.fields[i].Type))
FormatCSVValue(&builder, values[i])
row[i] = builder.String()
builder.Reset()
}
return t.writer.Write(row)
}

func FormatCSVValue(builder *strings.Builder, value octosql.Value) {
switch value.TypeID {
case octosql.TypeIDNull:
case octosql.TypeIDInt:
builder.WriteString(strconv.FormatInt(int64(value.Int), 10))
case octosql.TypeIDFloat:
builder.WriteString(strconv.FormatFloat(value.Float, 'f', -1, 64))
case octosql.TypeIDBoolean:
builder.WriteString(strconv.FormatBool(value.Boolean))
case octosql.TypeIDString:
builder.WriteString(value.Str)
case octosql.TypeIDTime:
builder.WriteString(value.Time.Format(time.RFC3339))
case octosql.TypeIDDuration:
builder.WriteString(fmt.Sprint(value.Duration))
default:
panic("invalid value type to print in CSV: " + value.TypeID.String())
}
}

func (t *CSVFormatter) Close() error {
t.writer.Flush()
return nil
Expand Down
Empty file.
6 changes: 6 additions & 0 deletions tests/scenarios/outputs/csv/types.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
octosql "SELECT 42,
42.42, 42.42424242424242, float(42),
true, false,
null,
'test' as hello,
INTERVAL 5 HOURS + INTERVAL 32 MINUTES + INTERVAL 42 SECONDS" -ocsv
2 changes: 2 additions & 0 deletions tests/scenarios/outputs/csv/types.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
col_0,col_1,col_2,col_3,col_4,col_5,col_6,hello,col_8
42,42.42,42.42424242424242,42,true,false,,test,5h32m42s

0 comments on commit 2e6b0cd

Please sign in to comment.