MCPcopy Create free account
hub / github.com/documentdb/documentdb / InsertOrReplaceDocument

Function InsertOrReplaceDocument

pg_documentdb/src/commands/insert.c:1347–1439  ·  view source on GitHub ↗

* Inserts a document with the given shardKeyValue and object_id, and on conflict * with the _id index, reapplies the update on the conflicting document (Similar to upsert behavior) */

Source from the content-addressed store, hash-verified

1345 * with the _id index, reapplies the update on the conflicting document (Similar to upsert behavior)
1346 */
1347bool
1348InsertOrReplaceDocument(uint64 collectionId, const char *shardTableName, int64
1349 shardKeyValue,
1350 pgbson *objectId, pgbson *document,
1351 const bson_value_t *updateSpecValue)
1352{
1353 StringInfoData query;
1354 const int argCount = 4;
1355 Oid argTypes[4];
1356 Datum argValues[4];
1357 int spiStatus PG_USED_FOR_ASSERTS_ONLY = 0;
1358 uint64 planId;
1359
1360 SPI_connect();
1361
1362 pgbson *updateSpecDoc = BsonValueToDocumentPgbson(updateSpecValue);
1363
1364 initStringInfo(&query);
1365 appendStringInfo(&query, "INSERT INTO %s.", ApiDataSchemaName);
1366
1367 if (shardTableName != NULL && shardTableName[0] != '\0')
1368 {
1369 appendStringInfoString(&query, shardTableName);
1370 }
1371 else
1372 {
1373 appendStringInfo(&query, "documents_" UINT64_FORMAT, collectionId);
1374 }
1375
1376 appendStringInfo(&query, " (shard_key_value, object_id, document) "
1377 " VALUES ($1, %s.bson_from_bytea($2), "
1378 "%s.bson_from_bytea($3))",
1379 CoreSchemaName, CoreSchemaName);
1380
1381 planId = QUERY_ID_INSERT_OR_REPLACE;
1382
1383 const char *additionalArgs = "";
1384 if (IsClusterVersionAtleast(DocDB_V0, 111, 0))
1385 {
1386 additionalArgs = ", ctid, tableoid";
1387 }
1388
1389 if (shardTableName != NULL && shardTableName[0] != '\0')
1390 {
1391 /* Direct shard - we need to extract tableId_shardId as a suffix */
1392 /* Prefix length is the length of documents_ */
1393 const int prefixLength = 10;
1394 const char *shardSuffix = shardTableName + prefixLength;
1395 appendStringInfo(&query, " ON CONFLICT ON CONSTRAINT collection_pk_%s"
1396 " DO UPDATE SET document ="
1397 " COALESCE(%s.update_bson_document("
1398 " %s.documents_%s.document, %s.bson_from_bytea($4), '{}'::%s.bson, NULL::%s.bson, NULL::%s.bson, NULL::TEXT%s),"
1399 " %s.documents_%s.document)",
1400 shardSuffix, ApiInternalSchemaNameV2, ApiDataSchemaName,
1401 shardSuffix, CoreSchemaName, CoreSchemaName, CoreSchemaName,
1402 CoreSchemaName, additionalArgs,
1403 ApiDataSchemaName, shardSuffix);
1404 }

Callers 1

DoInsertForUpdateFunction · 0.85

Calls 4

IsClusterVersionAtleastFunction · 0.85
CastPgbsonToByteaFunction · 0.85

Tested by

no test coverage detected