Writes¶
Overview¶
Realm Database uses a highly efficient storage engine to persist objects. You can create objects in a realm, update objects in a realm, and eventually delete objects from a realm. Because these operations modify the state of the realm, we call them writes.
Realm Database handles writes in terms of transactions. A transaction is a list of read and write operations that Realm Database treats as a single indivisible operation. In other words, a transaction is all or nothing: either all of the operations in the transaction succeed or none of the operations in the transaction take effect.
All writes must happen in a transaction.
A realm allows only one open transaction at a time. Realm Database blocks other writes on other threads until the open transaction is complete. Consequently, there is no race condition when reading values from the realm within a transaction.
When you are done with your transaction, Realm Database either commits it or cancels it:
- When Realm Database commits a transaction, Realm Database writes all changes to disk. For synced realms, Realm Database queues the change for synchronization with MongoDB Realm.
- When Realm Database cancels a write transaction or an operation in the transaction causes an error, all changes are discarded (or "rolled back").
Realm is ACID Compliant¶
Realm Database guarantees that transactions are ACID compliant. This means that all committed write operations are guaranteed to be valid and that clients don't see transient states in the event of a system crash.
- Realm Database establishes atomicity by grouping operations in transactions and rolling back all operations in a transaction if any of them fail.
- Realm Database establishes consistency and avoids data corruption by validating changes against the schema. If the result of any write operation is not valid, Realm Database cancels and rolls back the entire transaction.
- Realm Database establishes isolation by allowing only one writer at a time. This ensures thread safety between transactions.
- Finally, Realm Database establishes durability by writing to disk immediately when a transaction is committed. In the event of an app crash, for example, the changes are not lost or corrupted.
Run a Transaction¶
Realm Database represents each transaction as a callback function
that contains zero or more read and write operations. To run
a transaction, define a transaction callback and pass it to
the realm's write
method. Within this callback, you are
free to create, read, update, and delete on the realm. If
the code in the callback throws an exception when Realm Database runs
it, Realm Database cancels the transaction. Otherwise, Realm Database commits
the transaction immediately after the callback.
Since transactions block each other, it is best to avoid opening transactions on both the UI thread and a background thread. If you are using Sync, avoid opening transactions on the UI thread altogether, as Realm Database processes synchronizations on a background thread. If a background transaction blocks your UI thread's transaction, your app may appear unresponsive.
The following code shows how to run a transaction with the realm's write method. If the code in the callback throws an exception, Realm Database cancels the transaction. Otherwise, Realm Database commits the transaction.
realm.write(() => { // Create someone to take care of some dogs. const ali = realm.create("Person", { id: 1, name: "Ali" }); // Find dogs younger than 2. const puppies = realm.objects("Dog").filtered("age < 2"); // Loop through to update. puppies.forEach(puppy => { // Give all puppies to Ali. puppy.owner = ali; }); });
Create an Object¶
In general, instantiate Realm objects as you would any other object. In a transaction, you can add the object to the realm if the realm's schema includes the object type. When you add an instance to the realm, it becomes managed by that realm.
With the Java and JavaScript SDKs, instead use the realm's factory method in a transaction to instantiate your class. This automatically inserts the instance into the realm.
This code demonstrates how to create an object with Realm Database:
// Declare the instance. let dog; // Open a transaction. realm.write(() => { // Assign a newly-created instance to the variable. dog = realm.create("Dog", { name: "Max", age: 5 }); });
Upsert an Object¶
An upsert is a write operation that either inserts a new object with a given primary key or updates an existing object that already has that primary key. We call this an upsert because it is an "update or insert" operation. This is useful when an object may or may not already exist, such as when bulk importing a dataset into an existing realm. Upserting is an elegant way to update existing entries while adding any new entries.
This code demonstrates how to upsert an object with realm. We create a new user named "Drew" and then update their name to "Andy" via upsert:
realm.write(() => { // Add a new person to the realm. Since nobody with ID 1234 // has been added yet, this adds the instance to the realm. const drew = realm.create("Person", { id: 1234, name: "Drew" }, "modified"); // Judging by the ID, it's the same person, just with a different name. // If an object exists, setting the third parameter (`updateMode`) to // "modified" only updates properties that have changed, resulting in // faster operations. const andy = realm.create("Person", { id: 1234, name: "Andy" }, "modified"); });
Update an Object¶
Within a transaction, you can update a Realm object the same way you would update any other object in your language of choice: just assign a new value to the property or update the property.
This code changes the dog's name to "Wolfie" and increments the age by 1:
// Open a transaction. realm.write(() => { // Get a dog to update. const dog = realm.objects("Dog")[0]; // Update some properties on the instance. // These changes are saved to the realm. dog.name = "Wolfie"; dog.age += 1; });
Update a Collection¶
Realm Database supports collection-wide updates. A collection update applies the same update to specific properties of several objects in a collection at once.
The following code demonstrates how to update a
collection. Thanks to the implicit inverse
relationship between the Dog's
owner
property and the Person's dogs
property,
Realm Database automatically updates Ali's list of dogs.
realm.write(() => { // Create someone to take care of some dogs. const ali = realm.create("Person", { id: 1, name: "Ali" }); // Find dogs younger than 2. const puppies = realm.objects("Dog").filtered("age < 2"); // Loop through to update. puppies.forEach(puppy => { // Give all puppies to Ali. puppy.owner = ali; }); });
Delete an Object¶
In general, to delete an object from a realm, pass the instance to the delete method of the realm within a transaction.
With the Java SDK, call deleteFromRealm()
on the
instance itself.
Realm Database throws an error if you try to use an object after it has been deleted.
The following code shows how to delete one object from its realm:
realm.write(() => { // Delete the dog from the realm. realm.delete(dog); // Discard the reference. dog = null; });
Delete a Collection¶
In general, to delete a collection of objects from a realm, pass the collection to the delete method of the realm within a transaction.
With the Java SDK, call deleteFromRealm()
on the
collection itself.
The following code demonstrates how to delete a collection from a realm:
realm.write(() => { // Find dogs younger than 2 years old. const puppies = realm.objects("Dog").filtered("age < 2"); // Delete the collection from the realm. realm.delete(puppies); });
Manually Delete An Object with a Relationship¶
When you delete a non-embedded object with a relationship to a child object, Realm does not automatically delete the child object.
If you would like to automatically delete an object, you must make the object an Embedded Object. When you delete a Realm object, Realm automatically deletes any embedded objects referenced by that object.
In the following example, Ali is a Person
who is the owner
of many
dogs. The code block demonstrates how to delete an object that is related to
another object by first deleting all of Ali’s dogs, then deleting Ali:
realm.write(() => { // Delete all of Ali's dogs. realm.delete(ali.dogs); // Delete Ali. realm.delete(ali); });
Delete All Instances of a Type¶
Realm Database supports deleting all instances of a Realm type from a realm.
The following code demonstrates how to delete all Dog instances from a realm:
realm.write(() => { // Delete all instances of Dog from the realm. realm.deleteModel("Dog"); });
Delete Everything¶
It is possible to delete all objects from the realm. This does not affect the schema of the realm. This is useful for quickly clearing out your realm while prototyping.
The following code demonstrates how to delete everything from a realm:
realm.write(() => { // Delete all objects from the realm. realm.deleteAll(); });
Summary¶
- Realm Database handles writes in terms of transactions. All writes must occur in a transaction.
- Realm Database transactions are ACID compliant.
- To write to Realm Database, define the transaction in a callback function that you pass to the realm's
write
method.