Sub topic 12
Inserting, updating, and reading documents through a duality view
This chapter assumes you have read the previous chapter on defining a duality view and that department, employee, and department_dv exist as defined there. It also assumes you are on Oracle Database 23ai and know basic transactions (COMMIT, ROLLBACK). Here you use the view to write documents, read them back, and change them. You also check the result in the underlying tables.
How a document write becomes row writes
A duality view has no storage of its own. Each document is assembled from rows when you read it, and taken apart into rows when you write it. The view exposes one JSON-type column named data. Every read returns it, and every write supplies it.
When you insert or update a document, Oracle compares it with the rows that the view definition maps. It then runs ordinary INSERT and UPDATE statements on the tables. Those statements fire constraints and triggers as usual.
Inserting a document
Insert a JSON text literal into the view. You do not name columns, because the view has only the data column.
INSERT INTO department_dv VALUES (
'{"_id": 10,
"departmentName": "Research",
"employees": [
{"employeeId": 100, "name": "Grace"},
{"employeeId": 101, "name": "Alan"}
]}'
);
COMMIT;Oracle makes these changes:
- It inserts one
departmentrow withdepartment_id = 10andname = 'Research'. - It inserts two
employeerows. - It fills in
employee.department_idwith 10 from the join condition in the view (e.department_id = d.department_id). The document never contains that foreign key.
The employees array was declared WITH INSERT UPDATE in the view, so inserting children is allowed. If the array's table had no INSERT permission, a document that contained children would be rejected.
A document that breaks a table rule fails like any other insert. For example, omitting departmentName violates the NOT NULL constraint on department.name, and reusing _id 10 violates the primary key. In both cases the whole insert is rolled back.
Reading documents
The view behaves like a table with one JSON column, so you query it with the functions from earlier chapters.
SELECT json_serialize(data PRETTY)
FROM department_dv
WHERE json_value(data, '$._id' RETURNING NUMBER) = 10;The result looks like this. The etag and asof values will differ on your system:
{
"_id" : 10,
"_metadata" :
{
"etag" : "B6A1F3C0D2E94A7F8C5B1E0A9D3F6C21",
"asof" : "0000000000A1B2C3"
},
"departmentName" : "Research",
"employees" :
[
{
"employeeId" : 100,
"name" : "Grace"
},
{
"employeeId" : 101,
"name" : "Alan"
}
]
}Oracle adds the _metadata object to every document. The etag is a hash of the document content, used to detect concurrent changes. The asof value is the system change number (SCN) at which the document was read. The next chapter covers the ETag.
Because data is a JSON column, dot notation and JSON_TABLE also work. Dot notation needs a table alias:
SELECT d.data.departmentName
FROM department_dv d
WHERE json_value(d.data, '$._id' RETURNING NUMBER) = 10;
SELECT d.data."_id".number() AS dept_id, jt.emp_id, jt.emp_name
FROM department_dv d,
JSON_TABLE(d.data, '$.employees[*]'
COLUMNS (
emp_id NUMBER PATH '$.employeeId',
emp_name VARCHAR2(50) PATH '$.name'
)) jt;This is the normal way to report on documents with SQL. The data is stored relationally, so a JSON_TABLE over the view and a join of the two tables give the same rows. The join is usually simpler and gives the optimizer more to work with.
Updating a document
There are three ways to change data. Each ends up as row changes in the tables.
Replace the whole document
Assign a complete new document to data:
UPDATE department_dv d
SET d.data = '{"_id": 10,
"departmentName": "Research and Development",
"employees": [
{"employeeId": 100, "name": "Grace"},
{"employeeId": 101, "name": "Alan"}
]}'
WHERE json_value(d.data, '$._id' RETURNING NUMBER) = 10;Oracle compares the new document with the current one. It updates only the columns whose values differ, here department.name. The two employee rows are not touched, because their values are unchanged.
The new document must be complete. If you omit an element of the employees array, the update treats that employee as removed from the document. The view as defined grants only INSERT UPDATE on employee, not DELETE. Do not rely on array removal unless you add DELETE to that table's WITH clause. Test the behavior on your own data first.
Change part of a document
JSON_TRANSFORM and JSON_MERGEPATCH also work on the data column. You do not have to read, edit, and resend the whole document.
UPDATE department_dv d
SET d.data = JSON_TRANSFORM(d.data,
SET '$.departmentName' = 'Research and Development',
APPEND '$.employees' = '{"employeeId": 102, "name": "Edsger"}' FORMAT JSON)
WHERE json_value(d.data, '$._id' RETURNING NUMBER) = 10;This renames the department and adds a third employee row with department_id = 10. Use JSON_MERGEPATCH instead when you want to send a small patch document. Remember that a merge patch replaces arrays as a whole rather than merging their elements.
Write through the tables
The tables remain ordinary tables, so relational writes are allowed:
UPDATE employee SET name = 'Grace Hopper' WHERE employee_id = 100;
COMMIT;The next read of document 10 shows "name" : "Grace Hopper" and a different etag. This is the "duality": one copy of the data, two ways to reach it. Nothing is synchronized or copied, so the two views of the data cannot drift apart.
Checking the result in the tables
After the insert, the relational side shows the foreign key that the view filled in:
SELECT employee_id, name, department_id
FROM employee
ORDER BY employee_id;| EMPLOYEE_ID | NAME | DEPARTMENT_ID |
|---|---|---|
| 100 | Grace | 10 |
| 101 | Alan | 10 |
What the view allows and rejects
The WITH clauses in the view definition decide which writes succeed. The table below uses the view from this chapter.
| Operation | Allowed by the view | Reason |
|---|---|---|
| Insert a document with new employees | Yes | `employee` has `WITH INSERT` |
| Change a department name | Yes | `department` has `WITH UPDATE` |
| Change an employee name | Yes | `employee` has `WITH UPDATE` |
| Delete a whole department document | Yes | `department` has `WITH DELETE` |
| Add a field the view does not define, such as `"floor": 3` | No | Every field must map to a column |
| Send `employees` with a missing `employeeId` key | Depends on the table | The primary key must be supplied for a new row |
Common mistakes
- Reading
dataas text.datais the JSON type. Usejson_serialize,json_value, or dot notation with an alias, as shown above. - Comparing
_idwithout a type.json_valuereturnsVARCHAR2by default, so addRETURNING NUMBERwhen the key is numeric. - Sending a partial document in a whole-document update. Missing fields are treated as missing values, not as "leave unchanged". Use
JSON_TRANSFORMfor partial changes. - Forgetting the commit. Document writes are normal DML, and other sessions see nothing until you commit.
Exercise
Starting from the state after the first insert (department 10 with Grace and Alan), write one statement that renames Alan to "Alan Turing" through the duality view without resending the whole document. Then write a query on employee that shows the change.
Show answer
UPDATE departmentdv d SET d.data = JSONTRANSFORM(d.data, SET '$.employees[1].name' = 'Alan Turing') WHERE jsonvalue(d.data, '$.id' RETURNING NUMBER) = 10; COMMIT; Then run SELECT employeeid, name FROM employee WHERE employeeid = 101; The row shows the name "Alan Turing". The array index 1 is the second element, so check the order first with a read, because JSON_TRANSFORM addresses the array by position.
Exercise
A client sends an insert for a department document whose employees array contains an employee with employeeId 100, which already exists in the employee table. What do you expect, and what should you check before writing the application code?
Show answer
Because employee_id is the primary key of employee, the insert tries to create a row that already exists, so expect a unique constraint error and a full rollback of the statement. Before relying on any other behavior, test it in your own schema. To change an existing employee, update the document or the table instead of inserting a new one.