Showing posts with label Autonomous JSON Database. Show all posts
Showing posts with label Autonomous JSON Database. Show all posts

Wednesday, April 24, 2024

Performance Tuning in the Oracle Autonomous Database: Creating Indexes for JSON Collections

The Oracle Database and in particular the Oracle Autonomous Database offers multiple technologies to accelerate queries and improve database performance over JSON data, including indexes, materialized views, in-memory column storage, and Exadata storage-cell pushdown.

Simple Oracle Document Access (SODA) is a NoSQL query language for storing, editing and deleting JSON documents. A SODA collection is a set of documents (in particular JSON) that is backed by an Oracle Database table or view. By default, creating a SODA document collection creates the following in the Oracle Database:

◉ Persistent default collection metadata.
◉ A table for storing the collection, in the database schema to which your SODA client is connected.

If the init.ora parameter compatible is at least 20, then SODA uses JSON data type by default for JSON content, and the version method is UUID. If the init.ora parameter compatible is less than 20, then SODA uses BLOB textual data by default for JSON content and the data is character data. 

Collection metadata is composed of multiple components. The kind of database you use determines the collection metadata that is used by default, and which of its field values you can modify for custom metadata.

Let us consider a collection of movies within the ADMIN schema in a 19c Oracle Autonomous JSON Database (think of one JSON file per movie). After opening JSON from Database Actions, we will create an index on the MOVIES colection:

Performance Tuning in the Oracle Autonomous Database: Creating Indexes for JSON Collections

Performance Tuning in the Oracle Autonomous Database: Creating Indexes for JSON Collections

Creating an index for a JSON collection requires the name and the type. The different options are Functional, Spatial and Search.

Before creating a functional index on the runtime field (we will be running order-by queries against it), let us see what are the field needed (fields to enter):

  • For a functional type index, the fields to enter are:
    • Unique: make all indexed values unique
    • Index Nulls: use the index in order-by queries
    • Path Required: the path must select a scalar value, even a JSON null value
    • Properties: select the property that you want to index on, or easier is to just type * to display all available document properties in the collection
    • Composite Index: use more than one property
    • Advanced: change the storage properties of the indexed property
  • For search index, the options are:
    • Dataguide off-on: create JSON data guide for collection
    • Text Search off-on: index all properties in documents to support full-text search based on string equality
    • Range Search off-on: choose on to support range search when string-range search or temporal search (equality or range) is required
  • Spatial index is used to index GeoJSON geographic data. The selected property should be of GeoJSON type.
    • Path Required: the path must select a value, even if it is a JSON null value
    • Lax: the targeted field does not need to be present or does not have a GeoJSON geometry object as its value

Performance Tuning in the Oracle Autonomous Database: Creating Indexes for JSON Collections

The properties of the selected index appear in JSON format below the listed indexes:

Performance Tuning in the Oracle Autonomous Database: Creating Indexes for JSON Collections

We can also index a singleton scalar field using SQL, here is how:

CREATE INDEX YEAR_NDX ON movies (json_value(data, '$.year.number()' ERROR ON ERROR));

Item method numberOnly() is used in the path expression that identifies the field to index, to ensure that the field value is numeric. As I have the year field in one of the JSON files as a string, I am getting the following error if I use the method numberOnly(): ORA-01722: invalid number. Method numberOnly() is used instead of method number(), because number() allows also for conversion of non-numeric fields to numbers. Clearly as some moview are produced during the same year I cannot make the index unique: ORA-01452: cannot CREATE UNIQUE INDEX; duplicate keys found.

Creating a collection relational views of JSON documents is simple, select the columns we need, say title, year and runtime:

Performance Tuning in the Oracle Autonomous Database: Creating Indexes for JSON Collections

In SQL, we can use the view and order the movies by runtime:

Performance Tuning in the Oracle Autonomous Database: Creating Indexes for JSON Collections

Regardless of your database release you can create whatever Oracle Database indexes you need directly, using:

(1) the JSON Page of Using Oracle Database Actions, check Creating Indexes for JSON Collections

(2) Simple Oracle Document Access (SODA)

(3) SQL — see Indexes for JSON Data in Oracle Database JSON Developer’s Guide.

Using the JSON page in ADB is perhaps the easiest approach to indexing JSON data.

The static data dictionary views USER_SODA_COLLECTIONS lists the basic features of all of your SODA collections. Correspondently, you have also DBA_SODA_COLLECTIONS and ALL_SODA_COLLECTIONS. Collection metadata, expressed in JavaScript Object Notation (JSON) can be obtained from the last column, called JSON_DESCRIPTOR.

Users will typically work with JSON collections using native language drivers, for example, SODA for Java or SODA for Python. SODA native language drivers generally provide more throughput (operations per second) than the REST driver (SODA for REST). It is recommended to configure the SODA drivers as follows:

  • Enable SODA Metadata Cache: The SODA driver needs to know the metadata of each JSON collection (the column names, types, etc.). By enabling the metadata cache, roundtrips to the database can be saved, improving latency and throughput.
  • Enable Statement Cache: Statement caching improves performance by caching executable statements that are used repeatedly, such as in a loop or in a method that is called repeatedly. For Java, the statement cache is enabled using JDBC.
  • For load-balanced systems: turn off DNS caching: Load balancing allows to distribute SODA operations across different nodes. If DNS caching is turned on, then all connections are likely to use the same node and nullifying the load balancing. For Java, the following system property should be set: inet.addr.ttl=0

The database performance tuning techniques also apply to SODA: for example, SODA collections can be partitioned or sharded, and queries can be accelerated using indexes and/or materialized views.

Performance Tuning in the Oracle Autonomous Database: Creating Indexes for JSON Collections

How to monitor all that? You can turn on performance monitoring of the SQL operations that underlie a SODA read or write operation, by adding a SQL hint to the SODA operation.

Use only hint MONITOR (turn on monitoring) or NO_MONITOR (turn off monitoring). You can use this to pass any SQL hints, but MONITOR and NO_MONITOR are the useful ones for SODA, and an inappropriate hint can cause the optimizer to produce a suboptimal query plan.

Note in addition that when using SODA with Autonomous Database the following restrictions apply:

  • Automatic indexing is not supported for SQL and PL/SQL code that uses the SQL/JSON function json_exists.
  • Automatic indexing is not supported for SODA query-by-example (QBE)

Final note: since Auto Indexing is disabled by default in the Autonomous Database, you can enable it by running: EXEC DBMS_AUTO_INDEX.CONFIGURE('AUTO_INDEX_MODE','IMPLEMENT');

Source: juliandontcheff.wordpress.com

Monday, April 15, 2024

Where is the Complexity?

Where is the Complexity?

One of the common arguments I hear about avoiding XA distributed transactions is due to their complexity. In this series of blog posts I’ll examine that claim by looking at three versions of the same application. The first version of the application ignores data consistency issues and operates as though failures essentially don’t occur. This unfortunately is a pretty common practice due to the perceived complexity of introducing distributed transactions into an application. The second version adopts the saga pattern that is all the rage. It uses Eclipse MicroProfile Long Running Actions to implement the saga. Unlike the toy examples used to illustrate how sagas work, this version will include the necessary logic to actually be able to complete or compensate a transaction. Finally, the third version will use the XA pattern to ensure data consistency.

Basic Problem to Solve


The application I’ll use to illustrate the issues associated with ensuring data consistency is one that provides the transfer of money from one account to another account where each account is serviced by a different microservice. Fundamentally a very simple application if you ignore failures. The flow is basically a Transfer microservice:

1. Accepts a request to transfer an amount of money from one account to another account
2. Makes a request to withdraw the amount from the first account
3. Makes a request to deposit the amount in the second account
4. Returns success

Where is the Complexity?

A very simple application, what could possibly go wrong?

Simplistic Application Without Considering Failures


Let’s look first at a possible simple Transfer microservice. It offers a single service named “transfer”, which transfers money from an account in one microservice (department1) to an account in a different microservice (department2). Here is a simple Spring Boot based teller service that handles transferring the money:

@RestController
@RequestMapping("/transfers")
@RequestScope
public class TransferResource {

    private static final Logger LOG = LoggerFactory.getLogger(TransferResource.class);

    @Autowired
    RestTemplate restTemplate;

    @Value("${departmentOneEndpoint}")
    String departmentOneEndpoint;

    @Value("${departmentTwoEndpoint}")
    String departmentTwoEndpoint;

    @RequestMapping(value = "transfer", method = RequestMethod.POST)
    public ResponseEntity<?> transfer(@RequestBody Transfer transferDetails) throws TransferFailedException {
        ResponseEntity<String> withdrawResponse = null;
        ResponseEntity<String> depositResponse = null;

        LOG.info("Transfer initiated: {}", transferDetails);
        try {
            withdrawResponse = withdraw(transferDetails.getFrom(), transferDetails.getAmount());
            if (!withdrawResponse.getStatusCode().is2xxSuccessful()) {
                LOG.error("Withdraw failed: {} Reason: {}", transferDetails, withdrawResponse.getBody());
                throw new TransferFailedException(String.format("Withdraw failed: %s Reason: %s", transferDetails, withdrawResponse.getBody()));
            }
        } catch (Exception e) {
            LOG.error("Transfer failed as withdraw failed with exception {}", e.getLocalizedMessage());
            throw new TransferFailedException(String.format("Withdraw failed: %s Reason: %s", transferDetails, Objects.nonNull(withdrawResponse) ? withdrawResponse.getBody() : withdrawResponse));
        }

        try {
            depositResponse = deposit(transferDetails.getTo(), transferDetails.getAmount());
            if (!depositResponse.getStatusCode().is2xxSuccessful()) {
                LOG.error("Deposit failed: {} Reason: {} ", transferDetails, depositResponse.getBody());
                LOG.error("Reverting withdrawn amount from account {}, as deposit failed.", transferDetails.getFrom());
                redepositWithdrawnAmount(transferDetails.getFrom(), transferDetails.getAmount());
                throw new TransferFailedException(String.format("Deposit failed: %s Reason: %s ", transferDetails, depositResponse.getBody()));
            }
        } catch (Exception e) {
            LOG.error("Transfer failed as deposit failed with exception {}", e.getLocalizedMessage());
            LOG.error("Reverting withdrawn amount from account {}, as deposit failed.", transferDetails.getFrom());
            redepositWithdrawnAmount(transferDetails.getFrom(), transferDetails.getAmount());
            throw new TransferFailedException(String.format("Deposit failed: %s Reason: %s ", transferDetails, Objects.nonNull(depositResponse) ? depositResponse.getBody() : depositResponse));
        }
        LOG.info("Transfer successful: {}", transferDetails);
        return ResponseEntity
                .ok(new TransferResponse("Transfer completed successfully"));
    }
    
    /**
     * Send an HTTP request to the service to withdraw amount from the provided account identity
     *
     * @param accountId The account Identity
     * @param amount    The amount to be withdrawn
     */
    private void redepositWithdrawnAmount(String accountId, double amount) {
        URI departmentUri = UriComponentsBuilder.fromUri(URI.create(departmentOneEndpoint))
                .path("/accounts")
                .path("/" + accountId)
                .path("/deposit")
                .queryParam("amount", amount)
                .build()
                .toUri();

        ResponseEntity<String> responseEntity = restTemplate.postForEntity(departmentUri, null, String.class);
        LOG.info("Re-Deposit Response: \n" + responseEntity.getBody());
    }

    /**
     * Send an HTTP request to the service to withdraw amount from the provided account identity
     *
     * @param accountId The account Identity
     * @param amount    The amount to be withdrawn
     * @return HTTP Response from the service
     */
    private ResponseEntity<String> withdraw(String accountId, double amount) {
        URI departmentUri = UriComponentsBuilder.fromUri(URI.create(departmentOneEndpoint))
                .path("/accounts")
                .path("/" + accountId)
                .path("/withdraw")
                .queryParam("amount", amount)
                .build()
                .toUri();

        ResponseEntity<String> responseEntity = restTemplate.postForEntity(departmentUri, null, String.class);
        LOG.info("Withdraw Response: \n" + responseEntity.getBody());
        return responseEntity;
    }

    /**
     * Send an HTTP request to the service to deposit amount into the provided account identity
     *
     * @param accountId The account Identity
     * @param amount    The amount to be deposited
     * @return HTTP Response from the service
     */
    private ResponseEntity<String> deposit(String accountId, double amount) {
        URI departmentUri = UriComponentsBuilder.fromUri(URI.create(departmentTwoEndpoint))
                .path("/accounts")
                .path("/" + accountId)
                .path("/deposit")
                .queryParam("amount", amount)
                .build()
                .toUri();

        ResponseEntity<String> responseEntity = restTemplate.postForEntity(departmentUri, null, String.class);
        LOG.info("Deposit Response: \n" + responseEntity.getBody());
        return responseEntity;
    }

}

Note that this simplistic implementation of the transfer service at least considers the possibility that the deposit service fails and if so attempts to redeposit the withdrawn amount back into the source account.  However as should be obvious, it’s possible that the redeposit fails thus leaving the funds in limbo.

Here is the code providing the REST service interface for withdraw for Department1:

@RequestMapping(value = "/{accountId}/withdraw", method = RequestMethod.POST)
    public ResponseEntity<?> withdraw(@PathVariable("accountId") String accountId, @RequestParam("amount") double amount) {
        try {
            this.accountOperationService.withdraw(accountId, amount);
            return ResponseEntity.ok("Amount withdrawn from the account");
        } catch (NotFoundException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage());
        } catch (UnprocessableEntityException e) {
            LOG.error(e.getLocalizedMessage());
            return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(e.getMessage());
        } catch (Exception e) {
            LOG.error(e.getLocalizedMessage());
            return ResponseEntity.internalServerError().body(e.getLocalizedMessage());
        }
    }

The withdraw service calls the withdraw method on the accountOperationService, Here is the code providing the withdraw method used by the above REST service. It uses an injected EntityManager for JPA:

/**
 * Service that connects to the accounts database and provides methods to interact with the account
 */
@Component
@RequestScope
@Transactional
public class AccountOperationService implements IAccountOperationService {

    private static final Logger LOG = LoggerFactory.getLogger(AccountOperationService.class);

    @Autowired
    EntityManager entityManager;

    @Autowired
    IAccountQueryService accountQueryService;

    @Override
    public void withdraw(String accountId, double amount) throws UnprocessableEntityException, NotFoundException {
        Account account = accountQueryService.getAccountDetails(accountId);
        if (account.getAmount() < amount) {
            throw new UnprocessableEntityException("Insufficient balance in the account");
        }
        LOG.info("Current Balance: " + account.getAmount());
        account.setAmount(account.getAmount() - amount);
        account = entityManager.merge(account);
        entityManager.flush();
        LOG.info("New Balance: " + account.getAmount());
        LOG.info(amount + " withdrawn from account: " + accountId);
    }

    @Override
    public void deposit(String accountId, double amount) throws NotFoundException {
        Account account = accountQueryService.getAccountDetails(accountId);
        LOG.info("Current Balance: " + account.getAmount());
        account.setAmount(account.getAmount() + amount);
        account = entityManager.merge(account);
        entityManager.flush();
        LOG.info("New Balance: " + account.getAmount());
        LOG.info(amount + " deposited to account: " + accountId);
    }
}

The withdraw method gets the current account balance and checks for sufficient funds and throws an exception if insufficient funds. Otherwise it updates the account balance and saves the account. We can also see the deposit method which gets the current account balance, adds the amount to deposit and saves the updated account information.

What About Failures?


The developer of this teller service realizes there might be some failure scenarios to handle. For example, what happens if the deposit request fails? The developer solved that by having the teller service takes the corrective measure of redepositing the money back into the first account. Problem solved. But what happens if between the time of the withdrawal request and the request to redeposit the funds the teller microservice dies? What happens to the funds that were withdrawn? As it stands, they’re lost!

The developer could solve this problem by creating a table of pending operations that could be examined when the teller microservice starts up. But that would also mean that the deposit service must be idempotent as the only thing the teller service can do is retry the deposit request until it succeeds at which point it would remove the entry from its pending operations table. Until the deposit succeeds, the funds are basically in limbo and inaccessible to the account owner or anyone else.

So far, the developer has only handled some of the possible failures by adding error recovery logic into their microservice. And this is only for a trivial microservice. As more state information is updated, more complex recovery mechanisms may need to be added to the microservice. In the next post, we’ll look at how we can apply the saga pattern to solve this data consistency problem using Eclipse MicroProfile Long Running Actions, coordinated by MicroTx.

Source: oracle.com

Friday, April 5, 2024

Disaster Recovery for the Oracle Autonomous JSON Database

Backup-Based Disaster Recovery is a low-cost DR option for databases with higher RTO tolerance.

As Autonomous Data Guard is currently not supported for Autonomous JSON Database workloads, the natural questions is what are the alternatives:

Disaster Recovery for the Oracle Autonomous JSON Database

Option 1. The backup-based Disaster Recovery solution is one alternative. Backup-based DR uses database backups to instantiate a peer database at the time of switchover or failover. This enables you to have a lower cost and higher Recovery Time Objective (RTO) disaster recovery option for your Autonomous Database, as compared with Autonomous Data Guard.

Disaster recovery for AJD provides a peer database instance in a different availability domain (or different Exadata if there is only 1 AD in the region) or in a different region around the world. With a peer database, if the primary database becomes unavailable, disaster recovery switches to role of the peer database to primary and begins recreating a new peer database. For backup-based disaster recovery with a cross-region peer, backups are copied to the remote region. 

Disaster Recovery for the Oracle Autonomous JSON Database

For local backup-based disaster recovery, existing local backups are utilized. You can edit the automatic backup retention period and the long-term backup schedule. Check that the backup state is “Active” and when last automatic backup went through. Your local peer will be in a different Availability Domain (AD) than the primary database in regions with multiple ADs, or a different Exadata machine in regions with only one AD.

There is no additional cost for local Backup-Based Disaster Recovery! And AJD already takes local backups automatically for you, so there is no additional cost to enable a local backup copy.

Disaster Recovery for the Oracle Autonomous JSON Database

Backup-Based Disaster Recovery RTO and RPO numbers are:

Backup-Based Disaster Recovery Configuration RTO  RPO 
Local backup copy one (1) hour + 1 hour per 5 TB 10 seconds
Cross-region (remote) backup copy  one (1) hour + 1 hour per 5 TB  1 min 

When you have a local peer and the switchover is not successful, the Oracle Cloud Infrastructure console shows a banner with information about why the switchover was not successful and the Oracle Cloud Infrastructure console shows a failover link in the Role field that you can click to initiate a failover to the local peer. The failover link only shows when the Primary database is unavailable and a peer is available. That is, the Primary database Lifecycle State field shows Unavailable and the local peer is available.

You may have also one additional backup copy, in another region. Here is one I added to the Swiss region:


Disaster Recovery for the Oracle Autonomous JSON Database

I also enabled cross region backup replication from Germany to Switzerland. Check the 2 informational boxes below (cost and replication of backups):

Disaster Recovery for the Oracle Autonomous JSON Database

By default, automatic backups are created and maintained at the current Primary database and are not replicated to a cross-region peer. Optionally, you can enable replication of the automatic backups to the cross region peer (as I have done above). A cross-region Backup-Based Disaster Recovery peer can be converted to a snapshot standby. This converts the peer to a read-write database for up to two days.

Note that Backup-Based Disaster Recovery is not available with Always Free Autonomous Database.

Option 2. For having a copy of the Autonomous JSON Database in a different region (and not just in another AD), an option to consider is Refreshable Clones.

When you create a refreshable clone for an Autonomous Database instance the system clones the source database to the refreshable clone. After you create a refreshable clone you can refresh the clone with changes from the source database.

As you can see my refreshable clone is in Switzerland (while the source JSON Database is in Germany):

Disaster Recovery for the Oracle Autonomous JSON Database

When you disconnect a refreshable clone the refreshable clone is disassociated from the source database. This converts the database from a refreshable clone to a regular database. Following the disconnect operation you are allowed to reconnect the disconnected database to the source database. The reconnect operation is limited to a 24 hour period.

Refreshable clones are billed based on their base ECPU count and any additional ECPU usage if compute auto scaling is enabled; they do not get billed additionally for the ECPUs of the source database. A refreshable clone in a different region than its source database is billed for twice the amount of storage that the source database is billed for.

You can check the main features of refreshable clones but it is most important to know that refreshable clones have a one week refresh age limit. If you do not perform a refresh within a week, then the refreshable clone is no longer refreshable. After a refreshable clone passes the refresh time limit, you can use the instance as a read only database or you can disconnect from the source to make the database a read/write (standard) database.

Note the important limitations on refreshable clones but these are the main ones:

  • Always Free Autonomous Databases do not support refreshable clones
  • You cannot create a cascading series of refreshable clones
  • You cannot backup or restore a refreshable clone

For the Oracle Autonomous JSON Database, note the following when reconnecting to the source database:

  • If, after you disconnect the refreshable clone, you promote both the clone and the source to Oracle Autonomous Transaction Processing (workload type Transaction Processing), you can reconnect the database to the source.
  • If after you disconnect the refreshable clone, you promote the source database to Oracle Autonomous Transaction Processing (workload type Transaction Processing) and do not promote the disconnected clone, the disconnected clone must also be promoted to Oracle Autonomous Transaction Processing (workload type Transaction Processing) before you perform the reconnect operation.
  • If after you disconnect the refreshable clone, you promote the disconnected database to Oracle Autonomous Transaction Processing (workload type Transaction Processing), you can still reconnect to the source but the reconnected database remains in the promoted state.

Option 3. Oracle GoldenGate is another way to replicate your data do another region. You can add a replicat for Autonomous JSON Database. It is even possible to use Oracle GoldenGate to replicate MongoDB to AJD, good for use case of migrating out of MongoDB to Oracle.

Source: juliandontcheff.wordpress.com

Monday, December 4, 2023

Loading JSON Data using External Tables in Oracle Database 23c

Loading JSON Data using External Tables in Oracle Database 23c

It was possible to load JSON documents using external tables in previous versions of the database, but they had to be loaded as CLOBs, and depending on the format it might require some creative external table definitions. In Oracle database 23c loading JSON data using external tables got much simpler.

◉ Directory Object


We create a directory object pointing to the "/tmp" directory on the database server. We make sure our test user can access this directory object.

conn sys/SysPassword1@//localhost:1521/freepdb1 as sysdba

create or replace directory tmp_dir as '/tmp';
grant read, write on directory tmp_dir to testuser1;

conn testuser1/testuser1@//localhost:1521/freepdb1

◉ Array of JSON Objects


We create a file called "fruit_array.json" containing an array of JSON documents.

cat > /tmp/fruit_array.json <<EOF
[
  {"fruit":"apple", "quantity": 20},
  {"fruit":"orange", "quantity": 10},
  {"fruit":"banana", "quantity": 15}
]
EOF

We create an external table pointing at the "fruit_array.json" file. Notice the type is "oracle_bigdata" and the access parameters are set to "com.oracle.bigdata.fileformat = jsondoc". This access type understands JSON documents, which means we don't need to figure out how to describe the contents of the file so they can be loaded accurately.

drop table if exists json_ext;

create table json_ext (
  data json
)
  organization external
    (type oracle_bigdata
     access parameters (com.oracle.bigdata.fileformat = jsondoc)
     location (tmp_dir:'fruit_array.json'))
  parallel
  reject limit unlimited;

We query the data from the "fruit_array.json" file and we see the data is loaded as one JSON document. We use JSON_SERIALIZE to pretty print it.

select json_serialize(data pretty)
from   json_ext;

JSON_SERIALIZE(DATAPRETTY)
--------------------------------------------------------------------------------
[
  {
    "fruit" : "apple",
    "quantity" : 20
  },
  {
    "fruit" : "orange",
    "quantity" : 10
  },
  {
    "fruit" : "banana",
    "quantity" : 15
  }
]


1 row selected.

SQL>

If we wanted to see each document in the array as a separate row, we just indicate the JSON Path of the array in our external table definition.

drop table if exists json_ext;

create table json_ext (
  data json
)
  organization external
    (type oracle_bigdata
     access parameters (
                         com.oracle.bigdata.json.path = '$[*]'
                         com.oracle.bigdata.fileformat = jsondoc
                       )
     location (tmp_dir:'fruit_array.json'))
  parallel
  reject limit unlimited;

Now when we query the data we see each array element presented as a separate row.

select json_serialize(data pretty)
from   json_ext;

JSON_SERIALIZE(DATAPRETTY)
--------------------------------------------------------------------------------
{
  "fruit" : "apple",
  "quantity" : 20
}

{
  "fruit" : "orange",
  "quantity" : 10
}

{
  "fruit" : "banana",
  "quantity" : 15
}


3 rows selected.

SQL>

Alternatively we may see the array wrapped up in a document as follows. As long as we set the JSON path to the array correctly, we can still unpack this array.

cat > /tmp/fruit_array2.json <<EOF
{
  "rows": [
    {"fruit":"apple", "quantity": 20},
    {"fruit":"orange", "quantity": 10},
    {"fruit":"banana", "quantity": 15}
  ]
}
EOF

We recreate the external table using the new JSON path.

drop table if exists json_ext;

create table json_ext (
  data json
)
  organization external
    (type oracle_bigdata
     access parameters (
                         com.oracle.bigdata.json.path = '$.rows[*]'
                         com.oracle.bigdata.fileformat = jsondoc
                       )
     location (tmp_dir:'fruit_array2.json'))
  parallel
  reject limit unlimited;

We query the external table and see the array elements as separate rows.

select json_serialize(data pretty)
from   json_ext;

JSON_SERIALIZE(DATAPRETTY)
--------------------------------------------------------------------------------
{
  "fruit" : "apple",
  "quantity" : 20
}

{
  "fruit" : "orange",
  "quantity" : 10
}

{
  "fruit" : "banana",
  "quantity" : 15
}


3 rows selected.

SQL>

◉ JSON Document Per File


We create three files called "fruit_file{n}.json", each with a single JSON document.

cat > /tmp/fruit_file1.json <<EOF
{"fruit":"apple", "quantity": 20}
EOF

cat > /tmp/fruit_file2.json <<EOF
{"fruit":"orange", "quantity": 10}
EOF

cat > /tmp/fruit_file3.json <<EOF
{"fruit":"banana", "quantity": 15}
EOF

We recreate the external table with the location parameter pointing to multiple "fruit_file*.json" files using a wildcard. This time each document is loaded as a separate row.

drop table if exists json_ext;

create table json_ext (
  data json
)
  organization external
    (type oracle_bigdata
     access parameters (com.oracle.bigdata.fileformat = jsondoc)
     location (tmp_dir:'fruit_file*.json'))
  parallel
  reject limit unlimited;

SELECT json_serialize(data pretty)
FROM   json_ext;

JSON_SERIALIZE(DATAPRETTY)
--------------------------------------------------------------------------------
{
  "fruit" : "apple",
  "quantity" : 20
}

{
  "fruit" : "orange",
  "quantity" : 10
}

{
  "fruit" : "banana",
  "quantity" : 15
}

3 rows selected.

SQL>

◉ Multiple JSON Documents Per File


We create a file called "fruit_multidoc.json" containing several JSON documents, with each document on a new line.

cat > /tmp/fruit_multidoc.json <<EOF
{"fruit":"apple", "quantity": 20}
{"fruit":"orange", "quantity": 10}
{"fruit":"banana", "quantity": 15}
EOF

We could recreate the external table, but this time we will override the location in the query. We point the table to the "fruit_multidoc.json" file. Even though the documents are read from a single file, they are loaded as a separate row per document.

SELECT json_serialize(data pretty)
FROM   json_ext external modify (
                   location (tmp_dir:'fruit_multidoc.json') 
                 );

JSON_SERIALIZE(DATAPRETTY)
--------------------------------------------------------------------------------
{
  "fruit" : "apple",
  "quantity" : 20
}

{
  "fruit" : "orange",
  "quantity" : 10
}

{
  "fruit" : "banana",
  "quantity" : 15
}


3 rows selected.

SQL>

◉ Multiline JSON Documents


We create a file called "fruit_multidoc_multiline.json" containing three JSON documents. Each document is spread across multiple lines.

cat > /tmp/fruit_multidoc_multiline.json <<EOF
{
  "fruit":"apple",
  "quantity": 20,
  "extra_info": {"val1": "one",
                 "val2": "two"}
}
{
  "fruit":"orange",
  "quantity": 10,
  "extra_info": {"val1": "three",
                 "val2": "four"}
}
{
  "fruit":"banana",
  "quantity": 15,
  "extra_info": {"val1": "five",
                 "val2": "six"}
}
EOF

We point the table to the "fruit_multidoc_multiline.json" file. The "jsondoc" format is smart enough to understand JSON, so we can have JSON documents that span multiple lines, and they will still be loaded correctly.

Once again we have one row per document. The external table recognized each document was spread across multiple lines, and loaded it correctly.

SELECT json_serialize(data pretty)
FROM   json_ext external modify (
                   location (tmp_dir:'fruit_multidoc_multiline.json') 
                 );

JSON_SERIALIZE(DATAPRETTY)
--------------------------------------------------------------------------------
{
  "fruit" : "apple",
  "quantity" : 20,
  "extra_info" :
  {
    "val1" : "one",
    "val2" : "two"
  }
}

{
  "fruit" : "orange",
  "quantity" : 10,
  "extra_info" :
  {
    "val1" : "three",
    "val2" : "four"
  }
}

{
  "fruit" : "banana",
  "quantity" : 15,
  "extra_info" :
  {
    "val1" : "five",
    "val2" : "six"
  }
}

3 rows selected.

SQL>

◉ Loading JSON Data From External Tables


Now we can read the data using external tables, loading the data into our database can take one of two forms.

- We load the JSON data directly into JSON columns.
- We use the built JSON functions to convert the JSON data into rows and columns in relation tables.

Here are examples of each method.

-- JSON column
drop table if exists json_data_table;

create table json_data_table (
  id        number generated always as identity,
  json_data json
);


insert into json_data_table (json_data)
select data from json_ext;
commit;

-- Relational table.
drop table if exists relational_data_table;

create table relational_data_table (
  id        number generated always as identity,
  fruit     varchar2(10),
  quantity  number
);

-- Dot Notation
insert into relational_data_table(fruit, quantity)
select je.data.fruit,
       je.data.quantity
from   json_ext je;

-- JSON_VALUE
insert into relational_data_table(fruit, quantity)
select json_value(data, '$.fruit'),
       json_value(data, '$.quantity')
from   json_ext;
commit;

Source: oracle-base.com

Friday, December 1, 2023

How to migrate textual JSON data into the new JSON data type

Oracle Database (20c and later) supports JSON natively with all relational database features: transactions, indexing, declarative querying, views, etc.

How to migrate textual JSON data into the new JSON data type

Oracle’s native binary JSON format called OSON is the Oracle extension of the JSON format by adding scalar types (date and double) which are not part of the JSON standard. The SQL data type JSON uses format OSON.

OSON means Oracle’s optimized binary JSON format and is based on a tree encoding. Here is the OSON encoding of a JSON document as a serialized OSON byte array having tree pointers represented as jump navigation offsets:

How to migrate textual JSON data into the new JSON data type

Oracle recommends that you use native binary JSON data (type JSON), rather than textual JSON data (type VARCHAR2, CLOB, or BLOB).

If your database has been migrated from an older version or not yet using JSON format, then it makes sense to migrate the existing textual JSON data to the JSON type. This is a 3-step process:

  1. Run pre-upgrade check using the PL/SQL procedure DBMS_JSON.json_type_convertible_check
  2. Migrate the data (CTAS, DataPump, DBMS_REDEFINITION or add/drop column)
  3. Fix the dependent database objects

Let us implement the migration using the 4th method above for the following simple table:

How to migrate textual JSON data into the new JSON data type

The INFO column contains textual JSON data stored as CLOB data type:

How to migrate textual JSON data into the new JSON data type

First, let us run the pre-migration check:

How to migrate textual JSON data into the new JSON data type

Note the newly created table CAR_OWNERS_PRECHECK. Querying the status column of that new table, we can confirm that there are no errors:

How to migrate textual JSON data into the new JSON data type

Next, we add the new temporary column, update the column data, drop the original column and rename the temp column to its original name:

How to migrate textual JSON data into the new JSON data type

… gives the same output as in the beginning:

How to migrate textual JSON data into the new JSON data type

Finally, we can confirm that the data type is JSON:

How to migrate textual JSON data into the new JSON data type

For the last 3rd step, for all JSON data type data that replaced the original textual JSON data you need to re-create any database objects that depend on that original data.

Source: juliandontcheff.wordpress.com

Monday, May 15, 2023

Precheck Constraints using JSON Schema in Oracle Database 23c

JSON Schema, Oracle Database 23c, Oracle Database Career, Oracle Database Skills, Oracle Database Jobs, Oracle Database Prep, Oracle Database Preparation, Oracle Database Tutorial and Materials, Oracle Database Guides, Oracle Database Certification

In Oracle database 23c we can use the PRECHECK keyword to mark check constraints as being validated externally by an application. The DBMS_JSON_SCHEMA package allows us to describe objects in the form of a JSON schema, which can be passed to an application to define how the data should be presented to the database so it is processed without errors.

◉ Basic Check Constraints


The PRECHECK keyword indicates a check constraint is prechecked by the application before the data it is sent to the database. In its default form, the check constraint is still validated in the database.

In this example we create a table with a check constraint set to PRECHECK. We see invalid JSON data still causes a constraint violation with the PRECHECK option.

drop table if exists t1 purge;

create table t1 (
  id         number,
  valid      varchar2(1),
  constraint t1_pk primary key (id),
  constraint valid_chk check (valid in ('Y','N')) precheck
);

insert into t1 (id, valid) values (1, 'B');
*
ERROR at line 1:
ORA-02290: check constraint (TESTUSER1.VALID_CHK) violated

SQL>

We use the ALTER TABLE command to set the constraint to DISABLE PRECHECK, which means we are totally reliant on the application to validate the data. This means we can insert invalid data if we fail to manually validate it.

alter table t1 modify constraint valid_chk disable precheck;

insert into t1 (id, valid) values (1, 'B');

1 row created.

SQL>

Remember, we can only enable the constraint if the underlying data doesn't violate it, unless we use the ENABLE NOVALIDATE option. In the following example we use the ALTER TABLE command to cycle through various constraint settings.

select status, validated, precheck
from   user_constraints
where  constraint_name = 'VALID_CHK';

STATUS   VALIDATED     PRECHECK
-------- ------------- --------
DISABLED NOT VALIDATED PRECHECK

SQL>

alter table t1 modify constraint valid_chk enable novalidate precheck;

select status, validated, precheck
from   user_constraints
where  constraint_name = 'VALID_CHK';

STATUS   VALIDATED     PRECHECK
-------- ------------- --------
ENABLED  NOT VALIDATED PRECHECK

SQL>

alter table t1 modify constraint valid_chk enable noprecheck;
                                 *
ERROR at line 1:
ORA-02293: cannot validate (TESTUSER1.VALID_CHK) - check constraint
violated

SQL>

truncate table t1;
alter table t1 modify constraint valid_chk enable noprecheck;

select status, validated, precheck
from   user_constraints
where  constraint_name = 'VALID_CHK';

STATUS   VALIDATED     PRECHECK
-------- ------------- --------
ENABLED  VALIDATED

SQL>

◉ JSON Schema Check Constraints


We can use the PRECHECK option for check constraints that validate JSON data against a JSON Schema.

In this example we create a table using the JSON data type, and use a check constraint to validate the JSON data conforms to a specific JSON schema. We are using the PRECHECK option, but even when we insert valid JSON data we get a JSON Schema violation if it doesn't conform to the JSON Schema defintion.

drop table if exists t2 purge;

create table t2 (
  id         number,
  json_data  json,
  constraint t2_pk primary key (id),
  constraint json_data_chk check (json_data is json validate '{
  "type"       : "object",
  "properties" : {"fruit"    : {"type"      : "string",
                                "minLength" : 1,
                                "maxLength" : 10},
                  "quantity" : {"type"      : "number",
                                "minimum"   : 0,
                                "maximum"   : 100}},
  "required"   : ["fruit", "quantity"]
}') precheck
);

insert into t2 (id, json_data) values (2, json('{"fruit":"apple"}'));
            *
ERROR at line 1:
ORA-40875: JSON schema validation error

SQL>

Here we use the ALTER TABLE command to set the constraint to DISABLE PRECHECK, which means we are totally reliant on the application to validate the data matches the JSON Schema. This means we can add valid JSON, which doesn't conform to the JSON Schema definition.

alter table t2 modify constraint json_data_chk disable precheck;

insert into t2 (id, json_data) values (3, json('{"fruit":"apple"}'));

1 row created.

SQL>

We cycle through the various constraint states as before.

select status, validated, precheck
from   user_constraints
where  constraint_name = 'JSON_DATA_CHK';

STATUS   VALIDATED     PRECHECK
-------- ------------- --------
DISABLED NOT VALIDATED PRECHECK

SQL>

alter table t2 modify constraint json_data_chk enable novalidate precheck;

select status, validated, precheck
from   user_constraints
where  constraint_name = 'JSON_DATA_CHK';

STATUS   VALIDATED     PRECHECK
-------- ------------- --------
ENABLED  NOT VALIDATED PRECHECK

SQL>

alter table t2 modify constraint json_data_chk enable noprecheck;
                                 *
ERROR at line 1:
ORA-02293: cannot validate (TESTUSER1.JSON_DATA_CHK) - check constraint violated

SQL>

truncate table t2;
alter table t2 modify constraint json_data_chk enable noprecheck;

select status, validated, precheck
from   user_constraints
where  constraint_name = 'JSON_DATA_CHK';

STATUS   VALIDATED     PRECHECK
-------- ------------- --------
ENABLED  VALIDATED

SQL>

◉ DBMS_JSON_SCHEMA.DESCRIBE


The DESCRIBE function in the DBMS_JSON_SCHEMA package generates a JSON schema describing the referenced object. It supports a variety of objects listed here. The description of the object can be used by an application to validate the data prior to sending it to the database.

We describe the T1 table created earlier. The output includes the table definition, and the check constraint for the VALID column. We've used the JSON_SERIALIZE function to pretty print the output, but this is not necessary.

set long 1000000 pagesize 100
column json_schema format a80

select json_serialize(
         dbms_json_schema.describe(
           object_name => 'T1',
           owner_name  => 'TESTUSER1')
         pretty) as json_schema;

JSON_SCHEMA
--------------------------------------------------------------------------------
{
  "title" : "T1",
  "dbObject" : "TESTUSER1.T1",
  "type" : "object",
  "dbObjectType" : "table",
  "properties" :
  {
    "ID" :
    {
      "extendedType" : "number"
    },
    "VALID" :
    {
      "extendedType" :
      [
        "null",
        "string"
      ],
      "maxLength" : 1,
      "allOf" :
      [
        {
          "enum" :
          [
            "Y",
            "N"
          ]
        }
      ]
    }
  },
  "required" :
  [
    "ID"
  ],
  "dbPrimaryKey" :
  [
    "ID"
  ]
}

SQL>

In this example we restrict the description to the VALID column.

set long 1000000 pagesize 100
column json_schema format a80

select json_serialize(
         dbms_json_schema.describe(
           object_name => 'T1',
           owner_name  => 'TESTUSER1',
           column_name => 'VALID')
         pretty) as json_schema;

JSON_SCHEMA
--------------------------------------------------------------------------------
{
  "dbColumn" : "VALID",
  "extendedType" :
  [
    "null",
    "string"
  ],
  "maxLength" : 1,
  "allOf" :
  [
    {
      "enum" :
      [
        "Y",
        "N"
      ]
    }
  ]
}

SQL>

We describe the T2 table created earlier. The output includes the table definition, and the check constraint for the JSON_DATA column, which itself includes the JSON schema defintion.

set long 1000000 pagesize 100
column json_schema format a80

select json_serialize(
         dbms_json_schema.describe(
           object_name => 'T2',
           owner_name  => 'TESTUSER1')
         pretty) as json_schema;

JSON_SCHEMA
--------------------------------------------------------------------------------
{
  "title" : "T2",
  "dbObject" : "TESTUSER1.T2",
  "type" : "object",
  "dbObjectType" : "table",
  "properties" :
  {
    "ID" :
    {
      "extendedType" : "number"
    },
    "JSON_DATA" :
    {
      "allOf" :
      [
        {
          "type" : "object",
          "properties" :
          {
            "fruit" :
            {
              "type" : "string",
              "minLength" : 1,
              "maxLength" : 10
            },
            "quantity" :
            {
              "type" : "number",
              "minimum" : 0,
              "maximum" : 100
            }
          },
          "required" :
          [
            "fruit",
            "quantity"
          ]
        }
      ]
    }
  },
  "required" :
  [
    "ID"
  ],
  "dbPrimaryKey" :
  [
    "ID"
  ]
}

SQL>

In this example we restrict the description to the JSON_DATA column.

set long 1000000 pagesize 100
column json_schema format a80

select json_serialize(
         dbms_json_schema.describe(
           object_name => 'T2',
           owner_name  => 'TESTUSER1',
           column_name => 'JSON_DATA')
         pretty) as json_schema;

JSON_SCHEMA
--------------------------------------------------------------------------------
{
  "dbColumn" : "JSON_DATA",
  "allOf" :
  [
    {
      "type" : "object",
      "properties" :
      {
        "fruit" :
        {
          "type" : "string",
          "minLength" : 1,
          "maxLength" : 10
        },
        "quantity" :
        {
          "type" : "number",
          "minimum" : 0,
          "maximum" : 100
        }
      },
      "required" :
      [
        "fruit",
        "quantity"
      ]
    }
  ]
}

SQL>

In this example we describe a JSON-relational duality view created in the article here.

set long 1000000 pagesize 200
column json_schema format a80

select json_serialize(
         dbms_json_schema.describe(
           object_name => 'DEPARTMENT_DV',
           owner_name  => 'TESTUSER1')
         pretty) as json_schema;

JSON_SCHEMA
--------------------------------------------------------------------------------
{
  "title" : "DEPARTMENT_DV",
  "dbObject" : "TESTUSER1.DEPARTMENT_DV",
  "dbObjectType" : "dualityView",
  "dbObjectProperties" :
  [
    "insertable",
    "updatable",
    "deletable",
    "check"
  ],
  "type" : "object",
  "properties" :
  {
    "_metadata" :
    {
      "etag" :
      {
        "extendedType" : "string",
        "maxLength" : 200
      },
      "asof" :
      {
        "extendedType" : "string",
        "maxLength" : 20
      }
    },
    "location" :
    {
      "extendedType" :
      [
        "string",
        "null"
      ],
      "maxLength" : 13,
      "dbAnnotations" :
      [
        "update",
        "check"
      ]
    },
    "departmentName" :
    {
      "extendedType" :
      [
        "string",
        "null"
      ],
      "maxLength" : 14,
      "dbAnnotations" :
      [
        "update",
        "check"
      ]
    },
    "departmentNumber" :
    {
      "extendedType" : "number",
      "sqlPrecision" : 2,
      "sqlScale" : 0,
      "dbAnnotations" :
      [
        "check"
      ]
    },
    "employees" :
    {
      "type" : "array",
      "items" :
      {
        "type" : "object",
        "properties" :
        {
          "job" :
          {
            "extendedType" :
            [
              "string",
              "null"
            ],
            "maxLength" : 9,
            "dbAnnotations" :
            [
              "update",
              "check"
            ]
          },
          "salary" :
          {
            "extendedType" :
            [
              "number",
              "null"
            ],
            "sqlPrecision" : 7,
            "sqlScale" : 2,
            "dbAnnotations" :
            [
              "update",
              "check"
            ]
          },
          "employeeNumber" :
          {
            "extendedType" : "number",
            "sqlPrecision" : 4,
            "sqlScale" : 0,
            "dbAnnotations" :
            [
              "check"
            ]
          },
          "employeeName" :
          {
            "extendedType" :
            [
              "string",
              "null"
            ],
            "maxLength" : 10,
            "dbAnnotations" :
            [
              "update",
              "check"
            ]
          }
        },
        "required" :
        [
          "employeeNumber"
        ]
      }
    }
  },
  "required" :
  [
    "departmentNumber"
  ]
}

SQL>

Source: oracle-base.com