0

If I replace a document with itself in a collection, the document seems to be altered. My data becomes unusable because of this problem. What am I doing wrong?

<?php

$login = '***removed***';
$pass = '***removed***';
$schema_name = 'dev';
$collection_name = 'test';

$session    = mysql_xdevapi\getSession("mysqlx://$login:$pass@localhost");
$schema     = $session->getSchema($schema_name);
$collection = $schema->getCollection($collection_name);

// Delete all documents in the collection.
$collection->remove('true')->execute();

// Add one document and get its ID.
$result = $collection->add('{ "accent": "\u00e8" }')->execute();
$ids = $result->getGeneratedIds();
$doc_id = $ids[0];

// Read the document from the database.
$row = $collection->getOne($doc_id);
print "1st getOne() : " . $row['accent'] . "\n";

// Replace the document with itself.
$collection->replaceOne($doc_id, $row);

// Read the document from the database again.
$row = $collection->getOne($doc_id);
print "2nd getOne() : " . $row['accent'] . "\n";

// One more time.
$collection->replaceOne($doc_id, $row);

$row = $collection->getOne($doc_id);
print "3rd getOne() : " . $row['accent'] . "\n";

?>

Output of the above script:

$ php test.php 
1st getOne() : è
2nd getOne() : \u00e8
3rd getOne() : \\u00e8

I am using PHP v7.3.19, and mysql_xdevapi v8.0.22.

Geoffroy
  • 1
  • 1

1 Answers1

0

Probably a conversion problems. As you can see in the documentation, the add and replaceOne methods accept collection Object or JSON document:

https://www.php.net/manual/en/mysql-xdevapi-collection.add.php https://www.php.net/manual/en/mysql-xdevapi-collection.replaceone.php

In your sample you use a JSON document in the add method, but when you retrieve that document using the getOne method the result is a collection Object: https://www.php.net/manual/en/mysql-xdevapi-collection.getone.php

And finally when you try to update it you use the previous generated collection object, and the collection object and JSON object they behavior different.

To achieve what do you want, I suggest you to create the first registry using a Collection Object instead of a JSON object, this should avoid charset or conversion problems when retrieving the dada. Good look!

Example: [ 'accent' => '\u00e8']

Bruno Morais
  • 1,029
  • 11
  • 12
  • 1
    Thank you. Unfortunately, using a Collection Object instead of a JSON string leads to the same result. The documentation shows an example that does exactly what I did (add a document with a JSON string, retrieve it as a Collection Object, and use this Collection Object in replaceOne). – Geoffroy Dec 20 '20 at 12:43