Sub topic 11
Defining a JSON-relational duality view
This chapter assumes you can write joins and foreign keys, and that you know how JSON_VALUE and JSON_TABLE read documents. It also assumes you have Oracle Database 23ai or later, because duality views do not exist in 21c.
What a duality view is
A JSON-relational duality view is a database object that presents rows from normalized tables as JSON documents. It stores no data. Each document is built on demand from the underlying tables, and writing a document changes those tables.
The data lives once, in ordinary tables with primary keys, foreign keys, and constraints. The view is a second way to see and change it. Relational code can keep querying the tables while document-oriented code reads and writes whole documents.
The tables behind the view
The running example uses two tables joined by a foreign key. A department has many employees.
CREATE TABLE department (
department_id NUMBER PRIMARY KEY,
name VARCHAR2(50) NOT NULL
);
CREATE TABLE employee (
employee_id NUMBER PRIMARY KEY,
name VARCHAR2(50) NOT NULL,
department_id NUMBER REFERENCES department (department_id)
);Define the tables first. The view depends on their columns, keys, and constraints.
The view definition
CREATE 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 INSERT UPDATE DELETE;The statement has four parts.
- The root table. The outer
FROM department dnames the table that each document is based on. One row of this table produces one document. - The document shape.
SELECT JSON { ... }lists each key and the column that supplies its value. Key names do not have to match column names.departmentNamecomes fromd.name. - The nested subquery. The square brackets around a
SELECT JSONsubquery make a JSON array. Each qualifyingemployeerow becomes one array element. - The
WITHclauses. They state which operations the view allows on each table.
The `_id` field
The root object must contain a field named _id. It is the document identifier and it must map to the primary key of the root table. If the primary key has several columns, _id becomes an object with one field per column. The key you map to _id is how Oracle finds the row again when you update or delete a document.
How nesting maps to relationships
The shape of the nested part tells Oracle what kind of relationship you mean.
| JSON construct in the view | Relationship | Example |
|---|---|---|
| Subquery in `[ ... ]` | One-to-many, child rows as an array | A department's employees |
| Subquery in `( ... )` | Many-to-one or one-to-one, a single nested object | An employee's department |
| Plain `table.column` value | A scalar field of the current row | `'departmentName' : d.name` |
The WHERE clause of a nested subquery must equate the child's foreign key columns with the parent's key columns. This is how Oracle learns the join. Here it is e.department_id = d.department_id. A free-form predicate such as e.name LIKE 'A%' is not a valid join condition for a duality view.
Many-to-one: an employee view
The same tables can back a second view with a different root. Here each document is an employee and the department is a single nested object.
CREATE JSON RELATIONAL DUALITY VIEW employee_dv AS
SELECT JSON {
'_id' : e.employee_id,
'name' : e.name,
'department' : ( SELECT JSON {
'departmentId' : d.department_id,
'departmentName' : d.name
}
FROM department d WITH NOUPDATE
WHERE d.department_id = e.department_id )
}
FROM employee e WITH INSERT UPDATE DELETE;WITH NOUPDATE on department means a client can read the department inside an employee document but cannot change it through this view. Several views can sit on the same tables. Each view gives a different document shape, and all of them stay consistent because the rows are stored once.
Controlling what a view allows
Each table in the view takes a list of operations in its WITH clause.
| Keyword | Meaning |
|---|---|
| `INSERT` or `NOINSERT` | Whether a document write may create rows in this table |
| `UPDATE` or `NOUPDATE` | Whether a document write may change rows in this table |
| `DELETE` or `NODELETE` | Whether a document write may delete rows in this table |
In department_dv, the department table allows all three operations, so a client can create or remove a whole department document. The employee table allows only INSERT UPDATE. Removing an employee from the employees array in an update does not delete the row, because DELETE is not granted for that table. Oracle rejects the change instead.
Inspecting the result
Each row of a duality view has a DATA column of type JSON. You query it like any other JSON column.
SELECT json_serialize(data PRETTY)
FROM department_dv
WHERE json_value(data, '$._id') = 10;The document contains the fields you defined, plus a generated _metadata object. That object carries an etag and an asof value, which later chapters use for concurrency control. You do not declare them in the view.
The data dictionary lists duality views. You can query USER_JSON_DUALITY_VIEWS to see what you have defined and USER_JSON_DUALITY_VIEW_TABS to see which tables each view uses and which operations are allowed. The view itself can also be described with DESCRIBE department_dv.
Rules that commonly cause errors
- A missing
_id. The statement fails if the root object has no_idfield tied to the primary key. - A join that is not on the foreign key. The nested
WHEREmust be an equality between key columns, as shown above. - Expecting a read-only default to allow writes. Writes fail with an error saying the operation is not allowed on the table. Check the
WITHclause before looking elsewhere. - Using a pre-23ai database.
CREATE JSON RELATIONAL DUALITY VIEWis not valid syntax in 21c or earlier. NativeJSONcolumns work in 21c, but duality views need 23ai. - Duplicate key names in one object. Each key inside a single JSON object must be unique, as in any JSON object.
Duality view or `JSON_TABLE` over a JSON column
JSON_TABLE flattens documents that are stored as JSON. A duality view does the reverse: it assembles documents from rows that are stored relationally. With JSON_TABLE, the document is the source of truth and the relational shape is a projection. With a duality view, the tables are the source of truth and the document is the projection.
That difference affects design. Duality views give you foreign-key integrity and normalized storage with no duplicated customer or department data. The cost is that the document shape must follow the table structure. You cannot store arbitrary fields that have no column behind them.
Exercise
You need a duality view where each document is a customer with an array of their orders. The tables are customer(customerid PK, name) and orders(orderid PK, customer_id FK, total). Customers may be created and updated through the view, orders may be created, but nothing may be deleted. Write the view.
Show answer
CREATE JSON RELATIONAL DUALITY VIEW customerdv AS
SELECT JSON {
'id' : c.customerid,
'name' : c.name,
'orders': [ SELECT JSON {
'orderId' : o.orderid,
'total' : o.total
}
FROM orders o WITH INSERT
WHERE o.customerid = c.customerid ]
}
FROM customer c WITH INSERT UPDATE;
The root table is customer, and _id maps to its primary key. The bracketed subquery creates the one-to-many array, and its WHERE clause joins on the foreign key. Omitting DELETE on both tables, and omitting UPDATE on orders, makes those operations unavailable.