Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CSV Writer: Allow different types in output #4889

Merged
merged 2 commits into from
Nov 22, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions zio/csvio/writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"io"
"slices"
"strings"

"github.com/brimdata/zed"
Expand All @@ -19,6 +20,7 @@ type Writer struct {
writer io.WriteCloser
encoder *csv.Writer
flattener *expr.Flattener
types map[int]struct{}
first *zed.TypeRecord
strings []string
}
Expand All @@ -32,6 +34,7 @@ func NewWriter(w io.WriteCloser) *Writer {
writer: w,
encoder: csv.NewWriter(w),
flattener: expr.NewFlattener(zed.NewContext()),
types: make(map[int]struct{}),
}
}

Expand Down Expand Up @@ -62,8 +65,11 @@ func (w *Writer) Write(rec *zed.Value) error {
if err := w.encoder.Write(hdr); err != nil {
return err
}
} else if rec.Type != w.first {
return ErrNotDataFrame
} else if _, ok := w.types[rec.Type.ID()]; !ok {
if !fieldsEqual(w.first.Fields, rec.Fields()) {
return ErrNotDataFrame
}
w.types[rec.Type.ID()] = struct{}{}
}
w.strings = w.strings[:0]
fields := rec.Fields()
Expand Down Expand Up @@ -96,3 +102,9 @@ func formatValue(typ zed.Type, bytes zcode.Bytes) string {
}
return zson.FormatValue(zed.NewValue(typ, bytes))
}

func fieldsEqual(a, b []zed.Field) bool {
mattnibs marked this conversation as resolved.
Show resolved Hide resolved
return slices.EqualFunc(a, b, func(a, b zed.Field) bool {
return a.Name == b.Name
})
}
14 changes: 14 additions & 0 deletions zio/csvio/ztests/different-types.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
zed: '*'

input: |
{a:0}
{a:"foo"}
{a:127.0.0.1}

output-flags: -f csv

output: |
a
0
foo
127.0.0.1