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 55c71d94 fix(arrow/csv): keep list items equal to the null value 
distinct from nulls (#1508)
55c71d94 is described below

commit 55c71d940c9d5164f23b10cdec9c23b80e75bc03
Author: Matt Topol <[email protected]>
AuthorDate: Thu Nov 12 11:40:30 2026 -0500

    fix(arrow/csv): keep list items equal to the null value distinct from nulls 
(#1508)
    
    ### Rationale for this change
    
    Inside a CSV list value, a null item is written as the writer's null
    string, so a non-null item equal to that string reads back as null. For
    example, with `WithNullWriter("null")` and `WithNullReader(true,
    "null")`, `["null"]` and `[null]` both write as `{null}`. The same
    happens for empty strings when the null string is empty.
    
    ### What changes are included in this PR?
    
    - The writer quotes non-null list items equal to the null string, so
    `["null", null]` writes as `{"null",null}`.
    - The reader never treats a quoted list item as null.
    - Unquoted items keep their current behavior, so existing files read the
    same.
    
    ### Are these changes tested?
    
    Yes.
    
    ### Are there any user-facing changes?
    
    Yes. CSV output quotes list items that equal the null string, and
    readers treat quoted list items as non-null. With an empty null string,
    a list whose only item is null still reads back as an empty list; the
    `WithNullWriter` docs note this.
---
 arrow/csv/common.go      |  9 ++++++
 arrow/csv/reader.go      | 52 ++++++++++++++++++++++++++-----
 arrow/csv/transformer.go | 10 ++++--
 arrow/csv/writer_test.go | 80 ++++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 141 insertions(+), 10 deletions(-)

diff --git a/arrow/csv/common.go b/arrow/csv/common.go
index 8f7eaccd..2e408b08 100644
--- a/arrow/csv/common.go
+++ b/arrow/csv/common.go
@@ -36,6 +36,9 @@ type Option func(config)
 type config interface{}
 
 // WithComma specifies the fields separation character used while parsing CSV 
files.
+//
+// It does not apply inside list values, whose items are always separated by
+// commas.
 func WithComma(c rune) Option {
        return func(cfg config) {
                switch cfg := cfg.(type) {
@@ -142,6 +145,8 @@ var DefaultNullValues = []string{"", "NULL", "null"}
 // defaults set in NewReader() will be kept.
 //
 // When no NULL values is given, the default set is taken from 
DefaultNullValues.
+//
+// Quoted items inside a list value are never interpreted as NULL.
 func WithNullReader(stringsCanBeNull bool, nullValues ...string) Option {
        return func(cfg config) {
                switch cfg := cfg.(type) {
@@ -161,6 +166,10 @@ func WithNullReader(stringsCanBeNull bool, nullValues 
...string) Option {
 
 // WithNullWriter sets the null string written for NULL values. The default is
 // set in NewWriter().
+//
+// Inside list values, non-null items equal to the null string are quoted so
+// they are not read back as NULL. A list whose only item is NULL is written
+// as an empty list when the null string is empty.
 func WithNullWriter(null string) Option {
        return func(cfg config) {
                switch cfg := cfg.(type) {
diff --git a/arrow/csv/reader.go b/arrow/csv/reader.go
index dab0df65..bfba66d2 100644
--- a/arrow/csv/reader.go
+++ b/arrow/csv/reader.go
@@ -65,6 +65,9 @@ type Reader struct {
 
        stringsCanBeNull bool
        nulls            []string
+       // quotedListItem is set while converting a quoted list item, which is
+       // never null.
+       quotedListItem bool
 }
 
 // NewInferringReader creates a CSV reader that attempts to infer the types
@@ -406,6 +409,9 @@ func (r *Reader) validate(recs []string) {
 }
 
 func (r *Reader) isNull(val string) bool {
+       if r.quotedListItem {
+               return false
+       }
        for _, v := range r.nulls {
                if v == val {
                        return true
@@ -868,10 +874,7 @@ func (r *Reader) parseListLike(field 
array.ListLikeBuilder, str string) {
                return
        }
        r.appendListValue(field, len(items))
-       valueBldr := field.ValueBuilder()
-       for _, str := range items {
-               r.initFieldConverter(valueBldr)(str)
-       }
+       r.appendListItems(field.ValueBuilder(), str, items)
 }
 
 func (r *Reader) appendListValue(field array.ListLikeBuilder, size int) {
@@ -904,7 +907,6 @@ func (r *Reader) parseFixedSizeList(field 
*array.FixedSizeListBuilder, str strin
                field.Append(true)
                return
        }
-       valueBldr := field.ValueBuilder()
        reader := csv.NewReader(strings.NewReader(str))
        items, err := reader.Read()
        if err != nil {
@@ -919,9 +921,45 @@ func (r *Reader) parseFixedSizeList(field 
*array.FixedSizeListBuilder, str strin
        }
 
        field.Append(true)
-       for _, str := range items {
-               r.initFieldConverter(valueBldr)(str)
+       r.appendListItems(field.ValueBuilder(), str, items)
+}
+
+// appendListItems converts the items split from a list body. Quoted items
+// are never null, so a string equal to a null value can be preserved.
+func (r *Reader) appendListItems(bldr array.Builder, body string, items 
[]string) {
+       convert := r.initFieldConverter(bldr)
+       quoted := listItemsQuoted(body, len(items))
+       for i, item := range items {
+               r.quotedListItem = quoted[i]
+               convert(item)
+       }
+       r.quotedListItem = false
+}
+
+// listItemsQuoted reports which of the first n fields of a list body are
+// quoted. body must already have been parsed by encoding/csv, so quotes
+// appear only within quoted fields.
+func listItemsQuoted(body string, n int) []bool {
+       quoted := make([]bool, n)
+       field, atStart, inQuotes := 0, true, false
+       for i := 0; i < len(body) && field < n; i++ {
+               c := body[i]
+               if atStart {
+                       atStart = false
+                       if c == '"' {
+                               quoted[field], inQuotes = true, true
+                               continue
+                       }
+               }
+               switch {
+               case c == '"':
+                       inQuotes = !inQuotes
+               case c == ',' && !inQuotes:
+                       field++
+                       atStart = true
+               }
        }
+       return quoted
 }
 
 func (r *Reader) parseBinaryType(field array.Builder, str string) {
diff --git a/arrow/csv/transformer.go b/arrow/csv/transformer.go
index 4a9f2a9e..45e9235d 100644
--- a/arrow/csv/transformer.go
+++ b/arrow/csv/transformer.go
@@ -248,7 +248,7 @@ func (w *Writer) transformColToStringArr(typ 
arrow.DataType, col arrow.Array, st
                                list.Release()
                                return nil, err
                        }
-                       res[i] = encodeListItems(values)
+                       res[i] = encodeListItems(values, list, w.nullValue)
                        list.Release()
                }
        case *arrow.BinaryType:
@@ -302,14 +302,18 @@ func (w *Writer) transformColToStringArr(typ 
arrow.DataType, col arrow.Array, st
 // 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 {
+//
+// A quoted item is never read back as null, so null items are written as the
+// null value unquoted, and non-null items equal to it are quoted. With an
+// empty null value, a list whose only item is null is written as {}.
+func encodeListItems(values []string, list arrow.Array, nullValue string) 
string {
        var b strings.Builder
        b.WriteByte('{')
        for i, v := range values {
                if i > 0 {
                        b.WriteByte(',')
                }
-               if !listItemNeedsQuotes(v) {
+               if list.IsNull(i) || (!listItemNeedsQuotes(v) && v != 
nullValue) {
                        b.WriteString(v)
                        continue
                }
diff --git a/arrow/csv/writer_test.go b/arrow/csv/writer_test.go
index e265d77d..d82eafde 100644
--- a/arrow/csv/writer_test.go
+++ b/arrow/csv/writer_test.go
@@ -924,3 +924,83 @@ func TestCSVWriteListItemsNeedingQuotes(t *testing.T) {
        got := r.RecordBatch().Column(0)
        assert.Truef(t, array.Equal(input, got), "expected %s, got %s", input, 
got)
 }
+
+func TestCSVListNullValueStrings(t *testing.T) {
+       strList := arrow.ListOf(arrow.BinaryTypes.String)
+       tests := []struct {
+               name      string
+               typ       arrow.DataType
+               nullValue string
+               data      string
+               want      string
+       }{
+               {"named marker", strList, "null",
+                       `[["null"], [null], ["null", null, "x"], ["NULL"], 
null]`,
+                       
"\"{\"\"null\"\"}\"\n{null}\n\"{\"\"null\"\",null,x}\"\n{NULL}\nnull\n"},
+               {"empty marker", strList, "",
+                       `[["", null], [""], ["a", ""], [null, null]]`,
+                       
"\"{\"\"\"\",}\"\n\"{\"\"\"\"}\"\n\"{a,\"\"\"\"}\"\n\"{,}\"\n"},
+               {"ints", arrow.ListOf(arrow.PrimitiveTypes.Int64), "null",
+                       `[[1, null], [null]]`,
+                       "\"{1,null}\"\n{null}\n"},
+               {"nested", arrow.ListOf(strList), "null",
+                       `[[["null", null]], [null, ["null"]]]`,
+                       
"\"{\"\"{\"\"\"\"null\"\"\"\",null}\"\"}\"\n\"{null,\"\"{\"\"\"\"null\"\"\"\"}\"\"}\"\n"},
+       }
+       for _, tc := range tests {
+               t.Run(tc.name, func(t *testing.T) {
+                       mem := 
memory.NewCheckedAllocator(memory.DefaultAllocator)
+                       defer mem.AssertSize(t, 0)
+
+                       input, _, err := array.FromJSON(mem, tc.typ, 
strings.NewReader(tc.data))
+                       require.NoError(t, err)
+                       defer input.Release()
+                       schema := arrow.NewSchema([]arrow.Field{{Name: "value", 
Type: tc.typ, Nullable: true}}, nil)
+                       record := array.NewRecordBatch(schema, 
[]arrow.Array{input}, int64(input.Len()))
+                       defer record.Release()
+
+                       var buf bytes.Buffer
+                       w := csv.NewWriter(&buf, schema, 
csv.WithNullWriter(tc.nullValue))
+                       require.NoError(t, w.Write(record))
+                       require.NoError(t, w.Flush())
+                       assert.Equal(t, tc.want, buf.String())
+
+                       r := csv.NewReader(&buf, schema, 
csv.WithAllocator(mem), csv.WithChunk(-1),
+                               csv.WithNullReader(true, tc.nullValue))
+                       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)
+               })
+       }
+}
+
+// List items are always separated by commas, whatever WithComma sets for the
+// fields, and an item is quoted by what it contains, not by the field 
separator.
+func TestCSVListWithCustomComma(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;b"], 
["c,d", "e"], ["f", null]]`))
+       require.NoError(t, err)
+       defer input.Release()
+       schema := arrow.NewSchema([]arrow.Field{{Name: "value", Type: typ, 
Nullable: true}}, nil)
+       record := array.NewRecordBatch(schema, []arrow.Array{input}, 
int64(input.Len()))
+       defer record.Release()
+
+       var buf bytes.Buffer
+       w := csv.NewWriter(&buf, schema, csv.WithComma(';'), 
csv.WithNullWriter("null"))
+       require.NoError(t, w.Write(record))
+       require.NoError(t, w.Flush())
+       assert.Equal(t, `"{a;b}"`+"\n"+`"{""c,d"",e}"`+"\n"+`{f,null}`+"\n", 
buf.String())
+
+       r := csv.NewReader(&buf, schema, csv.WithAllocator(mem), 
csv.WithChunk(-1),
+               csv.WithComma(';'), csv.WithNullReader(true, "null"))
+       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)
+}

Reply via email to