Sub topic 13
ETags and updatability annotations
This chapter assumes you can create a duality view and read and write documents through it, as covered in the previous two chapters. You should also know what a transaction is and what a lost update is. Here you will see how a duality view detects conflicting edits without holding locks, and how annotations limit which tables and fields a document write can change.
The problem: lost updates
A duality view hands documents to applications, often over REST or through a driver, where the read and the write happen in separate requests. Between those requests another client can change the same data.
Suppose two clients read department 10:
- Client A reads the document and renames the department.
- Client B reads the same document and adds an employee.
- Client A writes its document back.
- Client B writes its document back. Because B's document was built from the old data, it silently undoes A's rename.
Locking rows from the first read to the final write would stop this. That is impractical when the client may take minutes to respond. Duality views use optimistic concurrency instead. Nothing is locked while the client thinks. At write time the database checks whether the data changed since the client read it.
What an ETag is
Every document read from a duality view carries a _metadata object with two fields:
etagis a hash computed from the document's contents. If any checked value changes, the ETag changes.asofis the system change number (SCN) at which the document was read.
Read the department from the previous chapter:
SELECT json_serialize(data PRETTY) AS doc
FROM department_dv
WHERE json_value(data, '$._id') = 10;The result looks like this. Your etag and asof values will differ.
{
"_id": 10,
"departmentName": "Research",
"employees": [
{ "employeeId": 100, "name": "Grace" },
{ "employeeId": 101, "name": "Alan" }
],
"_metadata": {
"etag": "B0E5C2A41F3D9A7E6C21D8F0A94B7753",
"asof": "00000000002B5A1C"
}
}The database does not store the ETag in a column. It computes the hash from the current row values each time the document is generated. The hash covers the whole document, including the rows of nested arrays such as employees. A change to one employee's name therefore changes the department document's ETag.
How the check works on write
When you replace a document, you include the ETag you received when you read it. Before applying the change, the database regenerates the stored document, recomputes its ETag, and compares the two.
- If they match, nobody changed the checked data since your read, and the write proceeds.
- If they differ, the write is rejected with an error, and the transaction can be retried.
The following block shows the pattern in PL/SQL. It reads the current ETag, then replaces the document and sends that ETag back in _metadata:
DECLARE
v_etag VARCHAR2(100);
BEGIN
SELECT json_value(data, '$._metadata.etag')
INTO v_etag
FROM department_dv
WHERE json_value(data, '$._id') = 10;
UPDATE department_dv
SET data = json_object(
'_metadata' VALUE json_object('etag' VALUE v_etag),
'_id' VALUE 10,
'departmentName' VALUE 'Research and Development',
'employees' VALUE json_array(
json_object('employeeId' VALUE 100, 'name' VALUE 'Grace'),
json_object('employeeId' VALUE 101, 'name' VALUE 'Alan')))
WHERE json_value(data, '$._id') = 10;
COMMIT;
END;
/In a real application the read and the write happen in different requests, so the ETag travels through the client. The client keeps the _metadata it received and sends it back unchanged. If another session changes the department between the two statements, the UPDATE fails with an ETag mismatch error (ORA-42699 in current releases). The usual response is to read the document again, reapply the user's change, and retry.
Two details are easy to miss:
- An update replaces the whole document. Rows that existed before but are missing from the new document are deleted if the view allows it. If the view does not allow it, the write fails.
- The ETag protects against stale data in the fields the check covers. It does not serialize writers. Two non-overlapping transactions with matching ETags still succeed in order.
Updatability annotations
Annotations are the WITH clauses on the tables in the view definition. They answer a different question from ETags. ETags ask whether the data is still what the client saw. Annotations ask whether this kind of change is allowed at all.
Each table in the view can carry these table-level annotations:
| Annotation | Effect on the underlying table's rows |
|---|---|
| `INSERT` / `NOINSERT` | A document write may or may not create rows |
| `UPDATE` / `NOUPDATE` | A document write may or may not change column values in existing rows |
| `DELETE` / `NODELETE` | A document write may or may not remove rows |
If you give no annotation, the table is read-only through the view, which is the same as NOINSERT NOUPDATE NODELETE.
The view from the earlier chapter used these annotations:
department d WITH INSERT UPDATE DELETElets a document write create, change, and delete department rows.employee e WITH INSERT UPDATElets a document write create and change employee rows. BecauseDELETEis not listed, a write cannot remove an employee by leaving it out of theemployeesarray.
You can change the rules by redefining the view. This version lets department documents change names and add employees, but keeps department rows from being created or deleted through the view:
CREATE OR REPLACE JSON RELATIONAL DUALITY VIEW department_dv AS
SELECT JSON {
'_id' : d.department_id,
'departmentName' : d.name,
'employees' : [ SELECT JSON {
'employeeId' : e.employee_id,
'name' : e.name
}
FROM employee e WITH INSERT UPDATE
WHERE e.department_id = d.department_id ]
}
FROM department d WITH UPDATE NOINSERT NODELETE;The relational tables are not affected by these annotations. A direct DELETE FROM department is still governed only by ordinary privileges and constraints. Annotations restrict writes that arrive as documents.
Field-level annotations
Annotations can also be placed on individual fields, not only on tables. Two are relevant here:
NOUPDATEon a field makes that value immutable through the view. A document write that changes it is rejected.NOCHECKon a field removes that value from the ETag calculation.
NOCHECK is useful for fields that change often and where overwriting would do little harm, such as a "last viewed" timestamp or a counter. Without it, every change to such a field changes the ETag, and unrelated writers collide with each other. The trade-off is that a stale client can overwrite a NOCHECK field without being detected. Reserve it for fields where a lost update is acceptable.
Check the field-level syntax in the Oracle JSON-Relational Duality Developer's Guide for your release, because the exact placement of the clause has changed between releases.
Putting the two controls together
| Question | Mechanism | Failure when violated |
|---|---|---|
| Is my copy still current? | ETag in `_metadata` | ETag mismatch error |
| Is this kind of change allowed? | `INSERT`, `UPDATE`, `DELETE` and their `NO` forms | Error naming the disallowed operation |
| Should this field take part in conflict detection? | `NOCHECK` | No error. Stale writes to that field succeed |
A practical set of rules for new views:
- Grant only the operations the application needs. Omit
DELETEon child tables unless removing a child through a document is a real use case. - Leave ETag checking on for every field a user edits deliberately.
- Use
NOCHECKonly on high-churn fields, and note the decision where the view is defined. - Always pass
_metadataback on replacement. Omitting it gives up the lost-update protection.
Exercise
Two clients read the same department document, which has ETag e1. Client A renames the department and succeeds. Client B then replaces the document with an added employee, still sending e1. What happens, and what should client B do?
Show answer
Client B's write fails with an ETag mismatch, because the stored document now hashes to a new ETag (e2) and e1 no longer matches. Client B should read the document again, reapply its change (adding the employee) to the current version, and write it back with e2.
Exercise
A view defines employee e WITH INSERT UPDATE. A client sends a replacement department document that leaves out one existing employee from the employees array. Why does the write fail, and which change to the annotation would allow it?
Show answer
Leaving the employee out means the employee row would have to be deleted, and DELETE is not among the annotations on employee. Changing the annotation to WITH INSERT UPDATE DELETE would allow the removal.
Exercise
A document includes a lastViewed field that many clients update frequently, which causes constant ETag mismatches on unrelated edits. What annotation fits, and what risk does it add?
Show answer
Annotate the field NOCHECK so it no longer contributes to the ETag. The risk is that a client holding a stale copy can overwrite lastViewed without being detected.