This is an automated email from the ASF dual-hosted git repository.
zeroshade pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-go.git
The following commit(s) were added to refs/heads/main by this push:
new be922ec5 fix(arrow/csv): preserve lists holding a single empty string
(#1505)
be922ec5 is described below
commit be922ec557c08b06d9f8243023b08e192eaeaa1d
Author: Matt Topol <[email protected]>
AuthorDate: Wed Nov 11 15:09:19 2026 -0500
fix(arrow/csv): preserve lists holding a single empty string (#1505)
### Rationale for this change
The CSV writer formats a list holding one empty string as `{}`, because
`encoding/csv` writes a record with a single empty field as an empty
line. The reader then parses `{}` as an empty list, so `[""]`
round-trips to `[]`.
### What changes are included in this PR?
The list writer formats items itself instead of going through
`encoding/csv`. It quotes an item using CSV rules when it is empty or
contains a brace, comma, quote, line break or leading blank. So `[""]`
writes as `{""}`, and empty lists still write `{}`. Quoting braces also
keeps items like `a}` intact for readers that strip every leading and
trailing brace, as this package did before #1499. Existing readers
already parse quoted items.
### Are these changes tested?
Yes.
### Are there any user-facing changes?
Yes. CSV list output quotes empty items and items containing braces, for
example `{""}` instead of `{}` for `[""]`, and `{"a}"}` for `["a}"]`.
---
arrow/csv/transformer.go | 43 +++++++++++++++++++++++++++++++++----------
arrow/csv/writer_test.go | 30 ++++++++++++++++++++++++++++++
2 files changed, 63 insertions(+), 10 deletions(-)
diff --git a/arrow/csv/transformer.go b/arrow/csv/transformer.go
index af4f09c5..4a9f2a9e 100644
--- a/arrow/csv/transformer.go
+++ b/arrow/csv/transformer.go
@@ -17,11 +17,10 @@
package csv
import (
- "bytes"
"encoding/base64"
- "encoding/csv"
"fmt"
"strconv"
+ "strings"
"github.com/apache/arrow-go/v18/arrow"
"github.com/apache/arrow-go/v18/arrow/array"
@@ -244,19 +243,12 @@ func (w *Writer) transformColToStringArr(typ
arrow.DataType, col arrow.Array, st
}
start, end := arr.ValueOffsets(i)
list := array.NewSlice(listVals, start, end)
- var b bytes.Buffer
- b.Write([]byte{'{'})
- writer := csv.NewWriter(&b)
values, err :=
w.transformColToStringArr(list.DataType(), list, stringsReplacer)
if err != nil {
list.Release()
return nil, err
}
- writer.Write(values)
- writer.Flush()
- b.Truncate(b.Len() - 1)
- b.Write([]byte{'}'})
- res[i] = b.String()
+ res[i] = encodeListItems(values)
list.Release()
}
case *arrow.BinaryType:
@@ -304,3 +296,34 @@ func (w *Writer) transformColToStringArr(typ
arrow.DataType, col arrow.Array, st
}
return res, nil
}
+
+// encodeListItems formats list items as {item1,item2,...}, quoting items with
+// CSV rules when they are empty or contain characters that would be ambiguous
+// inside the list, so that the reader can parse them back. An unquoted empty
+// item would be lost: {} is an empty list. Quoting braces keeps the items
+// intact for readers that strip every leading and trailing brace.
+func encodeListItems(values []string) string {
+ var b strings.Builder
+ b.WriteByte('{')
+ for i, v := range values {
+ if i > 0 {
+ b.WriteByte(',')
+ }
+ if !listItemNeedsQuotes(v) {
+ b.WriteString(v)
+ continue
+ }
+ b.WriteByte('"')
+ b.WriteString(strings.ReplaceAll(v, `"`, `""`))
+ b.WriteByte('"')
+ }
+ b.WriteByte('}')
+ return b.String()
+}
+
+func listItemNeedsQuotes(v string) bool {
+ if v == "" || strings.ContainsAny(v, ",\"\r\n{}") {
+ return true
+ }
+ return v[0] == ' ' || v[0] == '\t'
+}
diff --git a/arrow/csv/writer_test.go b/arrow/csv/writer_test.go
index 5d6ff756..e265d77d 100644
--- a/arrow/csv/writer_test.go
+++ b/arrow/csv/writer_test.go
@@ -894,3 +894,33 @@ func TestCSVWriterRejectsInvalidTimestampTimezone(t
*testing.T) {
require.Error(t, err)
assert.ErrorContains(t, err, "invalid timestamp timezone")
}
+
+// Empty items and items containing braces are quoted inside list values: an
+// unquoted lone empty item would read back as an empty list, and quoted
+// braces survive readers that strip every leading and trailing brace.
+func TestCSVWriteListItemsNeedingQuotes(t *testing.T) {
+ mem := memory.NewCheckedAllocator(memory.DefaultAllocator)
+ defer mem.AssertSize(t, 0)
+
+ typ := arrow.ListOf(arrow.BinaryTypes.String)
+ input, _, err := array.FromJSON(mem, typ, strings.NewReader(`[[""], [],
["", ""], ["a"], ["a}"], ["{b", "c"]]`))
+ require.NoError(t, err)
+ defer input.Release()
+ schema := arrow.NewSchema([]arrow.Field{{Name: "value", Type: typ}},
nil)
+ record := array.NewRecordBatch(schema, []arrow.Array{input},
int64(input.Len()))
+ defer record.Release()
+
+ var buf bytes.Buffer
+ w := csv.NewWriter(&buf, schema)
+ require.NoError(t, w.Write(record))
+ require.NoError(t, w.Flush())
+ assert.Equal(t,
`"{""""}"`+"\n"+`{}`+"\n"+`"{"""",""""}"`+"\n"+`{a}`+"\n"+
+ `"{""a}""}"`+"\n"+`"{""{b"",c}"`+"\n", buf.String())
+
+ r := csv.NewReader(&buf, schema, csv.WithAllocator(mem),
csv.WithChunk(-1))
+ defer r.Release()
+ require.True(t, r.Next())
+ require.NoError(t, r.Err())
+ got := r.RecordBatch().Column(0)
+ assert.Truef(t, array.Equal(input, got), "expected %s, got %s", input,
got)
+}