CipherStash
CipherStash Documentation

Inserting and Updating Records

Storing data in CipherStash is done with Collection#insert and Collection#upsert.

Inserting a record is guaranteed to create a new record in the collection, and auto-generates a record ID for you. An “upsert”, in contrast, requires that you specify an ID (a UUID) yourself, and if a record with that ID already exists, its contents will be replaced with the data specified, otherwise a new record will be inserted with the ID you specify.

Insert a Record With an Auto-generated ID

When you insert a new record, the ID of the record is returned to you, as in this example:

id = collection.insert(title: "Forrest Gump", year: 1994, runningTime: 142)

puts "Forrest Gump is now in the collection, with ID #{id}"

If you insert the same data multiple times, multiple records that just happen to have the same contents will be inserted:

10.times do
  id = collection.insert(title: "Forrest Gump", year: 1994, runningTime: 142)
  puts "Forrest Gump is now in the collection, with ID #{id}"
end

This will print out ten IDs, and you’ll have ten copies of Forrest Gump in your collection.

Insert or Update a Record by its ID

If you have a record ID, either because you previously retrieved that record, or because its ID comes from an external system, you can update-or-insert (aka “upsert”) into the collection. You can, for instance, set Jean Doe’s salary (securely stored in CipherStash, to limit snooping) based on their ID in some other database, like this:

id = sql_query("SELECT external_id FROM something WHERE title='Jean Doe'")  #  => "4f829071-a939-49c2-b145-cfb72fcc6744"

salaries.upsert(id, name: "Jean Doe", salary: 100_000)

A Note About Record IDs

Record IDs in CipherStash are always UUIDs. The quickest and easiest way to generate new UUIDs in Ruby is with SecureRandom.uuid (you may need to require "securerandom" first). This gives a cryptographically-secure randomly-generated UUID.

If, for some reason, you need a UUID that is derived from some other identifier, there are ways of doing that, however that is beyond the scope of this document.