Skip to content

Commit 2e6b0cd

Browse files
committed
Improve CSV value formatting.
1 parent 6644557 commit 2e6b0cd

File tree

5 files changed

+35
-3
lines changed

5 files changed

+35
-3
lines changed

octosql/values.go

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -424,8 +424,6 @@ func (value Value) append(builder *strings.Builder) {
424424
}
425425

426426
func (value Value) ToRawGoValue(t Type) interface{} {
427-
// TODO: Add complex types.
428-
// TODO: Fix union handling.
429427
switch value.TypeID {
430428
case TypeIDNull:
431429
return nil

outputs/formats/csv_format.go

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@ import (
44
"encoding/csv"
55
"fmt"
66
"io"
7+
"strconv"
8+
"strings"
9+
"time"
710

811
"github.com/cube2222/octosql/octosql"
912
"github.com/cube2222/octosql/physical"
@@ -33,13 +36,36 @@ func (t *CSVFormatter) SetSchema(schema physical.Schema) {
3336
}
3437

3538
func (t *CSVFormatter) Write(values []octosql.Value) error {
39+
var builder strings.Builder
3640
row := make([]string, len(values))
3741
for i := range values {
38-
row[i] = fmt.Sprintf("%v", values[i].ToRawGoValue(t.fields[i].Type))
42+
FormatCSVValue(&builder, values[i])
43+
row[i] = builder.String()
44+
builder.Reset()
3945
}
4046
return t.writer.Write(row)
4147
}
4248

49+
func FormatCSVValue(builder *strings.Builder, value octosql.Value) {
50+
switch value.TypeID {
51+
case octosql.TypeIDNull:
52+
case octosql.TypeIDInt:
53+
builder.WriteString(strconv.FormatInt(int64(value.Int), 10))
54+
case octosql.TypeIDFloat:
55+
builder.WriteString(strconv.FormatFloat(value.Float, 'f', -1, 64))
56+
case octosql.TypeIDBoolean:
57+
builder.WriteString(strconv.FormatBool(value.Boolean))
58+
case octosql.TypeIDString:
59+
builder.WriteString(value.Str)
60+
case octosql.TypeIDTime:
61+
builder.WriteString(value.Time.Format(time.RFC3339))
62+
case octosql.TypeIDDuration:
63+
builder.WriteString(fmt.Sprint(value.Duration))
64+
default:
65+
panic("invalid value type to print in CSV: " + value.TypeID.String())
66+
}
67+
}
68+
4369
func (t *CSVFormatter) Close() error {
4470
t.writer.Flush()
4571
return nil

tests/scenarios/outputs/csv/types.err

Whitespace-only changes.
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
octosql "SELECT 42,
2+
42.42, 42.42424242424242, float(42),
3+
true, false,
4+
null,
5+
'test' as hello,
6+
INTERVAL 5 HOURS + INTERVAL 32 MINUTES + INTERVAL 42 SECONDS" -ocsv
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
col_0,col_1,col_2,col_3,col_4,col_5,col_6,hello,col_8
2+
42,42.42,42.42424242424242,42,true,false,,test,5h32m42s

0 commit comments

Comments
 (0)