Repository: genjidb/genji (go)

Issue:
UPDATE ... SET updates the wrong array indexes
when we add a field into a document which contains an array with multiple indexes,  the field is added but the first index is replaced by the next.

`
INSERT INTO users (a) VALUES ([1, 0, 0]), ([2, 0]);
UPDATE users set min = 0;
select * from users;
{  "a": [ 1, 0, 0]}
{"a": [ 2, 0]}
`
The result is this:
`
{  "a": [ 2, 0], "min":  0}
{  "a": [ 2, 0], "min":  0}`

We can see the first index replaced by the next.

instead of 
`
{  "a": [ 1, 0, 0], "min":  0}
{"a": [ 2, 0], "min":  0}
`

I probably do the correction with the issue #92 



Pull request description:
Deep copy documents in Replacement node
This PR fixes #107 by doing a deep copy of the document instead of a shallow copy.
Nodes reuse memory between each iteration and the Replacement Node was storing each document in a buffer before writing them into the table, which caused it to write corrupted docs.


Patch:
diff --git a/sql/planner/replacement.go b/sql/planner/replacement.go
index 605e47b0..3409bb1a 100644
--- a/sql/planner/replacement.go
+++ b/sql/planner/replacement.go
@@ -66,7 +66,7 @@ func (n *replacementNode) toResult(st document.Stream) (res query.Result, err er
 			}
 
 			docs[i].Reset()
-			err := docs[i].ScanDocument(d)
+			err := docs[i].Copy(d)
 			if err != nil {
 				return err
 			}


Test patch:
diff --git a/sql/query/update_test.go b/sql/query/update_test.go
index 96b68e18..21734232 100644
--- a/sql/query/update_test.go
+++ b/sql/query/update_test.go
@@ -75,4 +75,24 @@ func TestUpdateStmt(t *testing.T) {
 			require.JSONEq(t, test.expected, buf.String())
 		})
 	}
+
+	t.Run("with arrays", func(t *testing.T) {
+		db, err := genji.Open(":memory:")
+		require.NoError(t, err)
+		defer db.Close()
+
+		res, err := db.Query(`
+			CREATE TABLE foo;
+			INSERT INTO foo (a) VALUES ([1, 0, 0]), ([2, 0]);
+			UPDATE foo set b = 0;
+			SELECT * FROM foo; 
+		`)
+		require.NoError(t, err)
+		defer res.Close()
+
+		var buf bytes.Buffer
+		err = document.IteratorToJSONArray(&buf, res)
+		require.NoError(t, err)
+		require.JSONEq(t, `[{"a": [1, 0, 0], "b": 0}, {"a": [2, 0], "b": 0}]`, buf.String())
+	})
 }