Tutorial

Overwriting Records

Existing records can be overwritten with two APIs: ups_cursor_overwrite or ups_db_insert.

ups_cursor_overwrite has a small performance advantage over ups_db_insert because it does not require a traversal of the B-Tree - but only if your cursor is already positioned on the record which is about to be overwritten. A common use case is to check whether a key already exists; if yes then fetch the record, modify it and write it back. The combination of ups_cursor_find and ups_cursor_overwrite is more efficient than ups_db_find and ups_db_insert.

Overwriting with a cursor

To overwrite a record with a cursor, you must first make sure that the cursor is positioned on that record. This can be performed i.e. with ups_cursor_find or ups_cursor_move. Afterwards, simply call ups_cursor_overwrite with a new record.

UPS_EXPORT ups_status_t UPS_CALLCONV
ups_cursor_overwrite(ups_cursor_t *cursor, ups_record_t *record,
            uint32_t flags);

The following snippet overwrites the current record. It assumes that the cursor is positioned on a valid key/record pair.

// positioning cursor is not shown here

ups_status_t st;
ups_record_t new_record = ups_make_record((void *)"a new record", 13);

st = ups_cursor_overwrite(cursor, &new_record, 0);
if (st) {
    // handle error
}

Overwriting without a cursor

The alternative is to call ups_db_insert with the flag UPS_OVERWRITE. However, be aware that ups_db_insert will create a new key/value pair if the key does not yet exist. It performs like an "UPSERT" statement.

The following code shows how to use the UPS_OVERWRITE flag.

ups_status_t st;
ups_key_t key = ups_make_key((void *)"key", 3);
ups_record_t new_record = ups_make_record((void *)"a new record", 13);

st = ups_db_insert(db, 0, &key, &new_record, UPS_OVERWRITE);
if (st) {
    // handle error
}