Showing posts with label Oracle Database 23ai. Show all posts
Showing posts with label Oracle Database 23ai. Show all posts

Saturday, August 3, 2024

Table Values Constructor in Oracle Database 23ai

Table Values Constructor in Oracle Database 23ai

The table values constructor allows us to define multiple rows using a single constructor for use in SQL statements.

◉ Setup


The following table is required to run the examples in this article.

drop table if exists t1;

create table t1 (
  id number,
  code varchar2(6),
  description varchar(25),
  constraint t1_pk primary key (id)
);

◉ INSERT


The table values constructor allows us to insert multiple rows into a table in a single step.

insert into t1
values (1, 'ONE', 'Description for ONE'),
       (2, 'TWO', 'Description for TWO'),
       (3, 'THREE', 'Description for THREE');

commit;


select * from t1;

        ID CODE   DESCRIPTION
---------- ------ -------------------------
         1   ONE      Description for ONE
         2   TWO     Description for TWO
         3   THREE  Description for THREE

SQL>
That's a single network round trip without having to combine all the insert statements into a PL/SQL block.

◉ SELECT


The same type of table values constructor can be used in the FROM clause of a SELECT statement. Notice we have to alias the column names so they are presented correctly.

select *
from   (values
          (4, 'FOUR', 'Description for FOUR'),
          (5, 'FIVE', 'Description for FIVE'),
          (6, 'SIX', 'Description for SIX')
       ) a (id, code, description);

        ID CODE DESCRIPTION
---------- ---- --------------------
         4   FOUR Description for FOUR
         5    FIVE  Description for FIVE
         6    SIX    Description for SIX

SQL>

◉ WITH Clause


The table values constructor can be used as part of a WITH clause.

with a (id, code, description) AS (
  values (7, 'SEVEN', 'Description for SEVEN'),
         (8, 'EIGHT', 'Description for EIGHT'),
         (9, 'NINE', 'Description for NINE')
)
select * from a;

        ID CODE  DESCRIPTION
---------- ----- ---------------------
         7   SEVEN Description for SEVEN
         8   EIGHT  Description for EIGHT
         9   NINE   Description for NINE

SQL>

◉ MERGE


The table values constructor can be used as the source data for a MERGE statement.

merge into t1 a
  using (values
          (4, 'FOUR', 'Description for FOUR'),
          (5, 'FIVE', 'Description for FIVE'),
          (6, 'SIX', 'Description for SIX')
        ) b (id, code, description)
  on (a.id = b.id)
  when matched then
    update set a.code        = b.code,
               a.description = b.description
  when not matched then
    insert (a.id, a.code, a.description)
    values (b.id, b.code, b.description);

3 rows merged.

SQL>

select * from t1;

        ID CODE   DESCRIPTION
---------- ------ -------------------------
         1   ONE      Description for ONE
         2   TWO     Description for TWO
         3   THREE  Description for THREE
         4   FOUR    Description for FOUR
         5   FIVE      Description for FIVE
         6   SIX        Description for SIX

6 rows selected.

SQL>

rollback;

Source: oracle-base.com

Wednesday, July 10, 2024

Transport Layer Security (TLS) Connections without a Client Wallet in Oracle Database 23ai

Transport Layer Security (TLS) Connections without a Client Wallet in Oracle Database 23ai

In previous releases HTTPS callouts from the database required the use of a client wallet. From Oracle database 23ai onward we can use the operating system certificate store instead.

Operating systems usually have a certificate store containing the root certificates of popular certificate authorities. This allows the operating system to make trusted connections to sites using those root certificates. These certificate stores are kept up to date with operating patches. Oracle 23ai allows us to make use of the operating system certificate store, rather than having to use a wallet, which removes the burden of certificate management from us.

Test a URL From the Operating System


The simplest way to test a HTTPS URL is to use the curl command from the operating system command line. If a valid HTTPS connection is possible, we should get a "200 OK" response. We can see it works fine.

$ curl -is https://oracle-base.com/sitemap.xml | grep HTTP
HTTP/1.1 200 OK
$
This means the required root certificate is present in the operating system certificate store.

Create an ACL


In order to do a database callout we need an Access Control List (ACL) for the host. The following example creates an ACL for the host "oracle-base.com" on port 443. The principal is TESTUSER1, which is the user we will make the call from.

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

begin
  dbms_network_acl_admin.append_host_ace (
    host       => 'oracle-base.com', 
    lower_port => 443,
    upper_port => 443,
    ace        => xs$ace_type(privilege_list => xs$name_list('http'),
                              principal_name => 'testuser1',
                              principal_type => xs_acl.ptype_db)); 
end;
/

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

Test a Database Callout Without a Wallet


We create a procedure using the UTL_HTTP package to return the contents of a URL.

create or replace procedure show_html_from_url (
  p_url  in  varchar2
) as
  l_http_request   utl_http.req;
  l_http_response  utl_http.resp;
  l_text           varchar2(32767);
begin
  -- Make a http request and get the response.
  l_http_request  := utl_http.begin_request(p_url);

  l_http_response := utl_http.get_response(l_http_request);

  -- Loop through the response.
  begin
    loop
      utl_http.read_text(l_http_response, l_text, 32766);
      dbms_output.put_line (l_text);
    end loop;
  exception
    when utl_http.end_of_body then
      utl_http.end_response(l_http_response);
  end;
exception
  when others then
    utl_http.end_response(l_http_response);
    raise;
end show_html_from_url;
/

In previous releases attempting to use the procedure without opening a wallet would result in a certificate validation failure. That is not the case in Oracle 23ai, as we are using the operating system certificate store by default.

set serveroutput on long 1000000
exec show_html_from_url('https://oracle-base.com/sitemap.xml');

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>

... output removed ...

  <url>
</urlset>

PL/SQL procedure successfully completed.

SQL>

We could have achieved a similar result using HTTPURITYPE.

set serveroutput on long 1000000
select HTTPURITYPE.createuri('https://oracle-base.com/sitemap.xml').getclob();

HTTPURITYPE.CREATEURI('HTTPS://ORACLE-BASE.COM/SITEMAP.XML').GETCLOB()
--------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>

... output removed ...

  <url>
</urlset>

SQL>

Test a Database Callout With a Wallet


We can still use a wallet containing the relevant root certificate, but once we reference the wallet it takes priority. If the wallet doesn't contain the correct root certificate, the call will fail. To demonstrate this we make a new wallet containing a self-signed certificate, rather than the root certificate of the URL we are calling.

mkdir -p /u01/wallet
orapki wallet create -wallet /u01/wallet -pwd WalletPasswd123 -auto_login

orapki wallet add -wallet /u01/wallet -pwd WalletPasswd123 \
  -dn "CN=`hostname`, OU=Example Department, O=Example Company, L=Birmingham, ST=West Midlands, C=GB" \
  -keysize 1024 -self_signed -validity 365

We connect to a new session, open the wallet, and attempt to run the procedure to make the callout. As expected, this results in a certificate validation failure.

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

set serveroutput on long 1000000
exec utl_http.set_wallet('file:/u01/wallet', null);

exec show_html_from_url('https://oracle-base.com/sitemap.xml');
*
ERROR at line 1:
ORA-29273: HTTP request failed
ORA-06512: at "TESTUSER1.SHOW_HTML_FROM_URL", line 26
ORA-29024: Certificate validation failure
ORA-06512: at "SYS.UTL_HTTP", line 380
ORA-06512: at "SYS.UTL_HTTP", line 1189
ORA-06512: at "TESTUSER1.SHOW_HTML_FROM_URL", line 9
ORA-06512: at line 1
Help: https://docs.oracle.com/error-help/db/ora-29273/

SQL>

We get the same error when we try to use HTTPURITYPE.

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

set serveroutput on
exec utl_http.set_wallet('file:/u01/wallet', null);

select HTTPURITYPE.createuri('https://oracle-base.com/sitemap.xml').getclob();

ERROR:
ORA-29273: HTTP request failed
ORA-06512: at "SYS.HTTPURITYPE", line 38
ORA-29024: Certificate validation failure
ORA-06512: at "SYS.UTL_HTTP", line 380
ORA-06512: at "SYS.UTL_HTTP", line 1189
ORA-06512: at "SYS.HTTPURITYPE", line 23
Help: https://docs.oracle.com/error-help/db/ora-29273/

SQL>

We add the correct certificate to the wallet.

orapki wallet add -wallet /u01/wallet -trusted_cert -cert "/tmp/ISRG Root X1.crt" -pwd WalletPasswd123

Now the previous tests work as expected.

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

set serveroutput on long 1000000
exec utl_http.set_wallet('file:/u01/wallet', null);

exec show_html_from_url('https://oracle-base.com/sitemap.xml');

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>

... output removed ...

  <url>
</urlset>

PL/SQL procedure successfully completed.

SQL>


select HTTPURITYPE.createuri('https://oracle-base.com/sitemap.xml').getclob();

HTTPURITYPE.CREATEURI('HTTPS://ORACLE-BASE.COM/SITEMAP.XML').GETCLOB()
--------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>

... output removed ...

  <url>
</urlset>

SQL>

Mark a Self-Signed Certificate as Trusted


We are not always working with certificates from a certificate authority. Sometimes we may need to make callouts to services using self-signed certificates. Fortunately we can mark self-signed certificates as trusted on the OS of the database server. The following actions were performed as the "root" user.

We create a self-signed certificate, as demonstrated.

mkdir -p ~/certs

openssl req \
  -newkey rsa:4096 -nodes -sha256 -keyout ~/certs/${HOSTNAME}.key \
  -x509 -days 3650 -out ~/certs/${HOSTNAME}.crt \
  -subj "/C=GB/ST=West Midlands/L=Birmingham/O=Example Company/OU=Devs/CN=Tim Hall/emailAddress=me@example.com"

We copy it to the "/etc/pki/ca-trust/source/anchors/" directory and run update-ca-trust to make the change take effect.

cp ~/certs/${HOSTNAME}.crt /etc/pki/ca-trust/source/anchors/
update-ca-trust

We use trust list to check the certificate is present.

# trust list --filter=ca-anchors | grep -B 4 -A 2 "Tim Hall"
pkcs11:id=%EE%3A%98%8F%93%C2%64%23%E0%42%7F%52%97%54%6D%87%7F%C0%2F%05;type=cert
    type: certificate
    label: Tim Hall
    trust: anchor
    category: authority
#

Source: oracle-base.com

Monday, July 8, 2024

XML, JSON and Oracle Text Search Index Enhancements in Oracle Database 23ai

XML, JSON and Oracle Text Search Index Enhancements in Oracle Database 23ai

In Oracle 23ai the CREATE SEARCH INDEX statement allows us to create search indexes on XML, JSON and text data, making the syntax consistent between them.

◉ XML Search Indexes


The index type of XDB.XMLIndex was introduced in a previous release to allow us to index XML data.

drop table if exists t1 purge;

create table t1 (
  id    number,
  data  xmltype
);

create index t1_xmlindex_idx on t1 (data) indextype is xdb.xmlindex;

In Oracle 23ai we can create search indexes for XML using the CREATE SEARCH INDEX ... FOR XML syntax. The full syntax is available here.

drop table if exists xml_tab purge;

create table xml_tab (
  id    number,
  data  xmltype
)
xmltype column data
store as transportable binary xml;

create search index xml_tab_search_idx on xml_tab (data) for XML
parameters (
  'search_on text'
);

The SEARCH_ON parameter must be set for XML search indexes.

  • TEXT : Only text data is indexed for full-text search queries.
  • VALUE(data_types) : Enables range-search for the specified data types. One or more of BINARY_DOUBLE, NUMBER, TIMESTAMP, VARCHAR2 as a comma-separated list.
  • TEXT_VALUE(data_types) : A combination of support for full-text searches queries and range-search for the specified data types.

The XMLTYPE column must be stored as transportable binary XML to build a XML search index. For other storage types we can create an Oracle Text search index instead.

drop table if exists xml_tab purge;

create table xml_tab (
  id    number,
  data  xmltype
);

create search index xml_tab_search_idx on xml_tab (data);

◉ JSON Search Indexes


The original syntax for JSON search indexes in Oracle 12.1 was rather ugly.

drop table if exists t1 purge;

create table t1 (
  id    number,
  data  clob,
  constraint t1_json_chk check (data is json)
);

create index t1_search_idx on t1 (data)
  indextype is ctxsys.context
  parameters ('section group ctxsys.json_section_group sync (on commit)');

In Oracle 12.2 the JSON search index syntax was simplified using the CREATE SEARCH INDEX ... FOR JSON syntax. The full syntax is available here.

drop index if exists t1_search_idx;

create search index t1_search_idx on t1 (data) for json;

The SEARCH_ON parameter defaults to TEXT_VALUE for XML search indexes.

  • NONE : JSON queries are not supported. Only the data guide index is maintained.
  • TEXT : Only text data is indexed for full-text search queries.
  • VALUE(data_types) : Enables range-search for the specified data types. One or more of NUMBER, TIMESTAMP, VARCHAR2 as a comma-separated list.
  • TEXT_VALUE(data_types) : A combination of support for full-text searches queries and range-search for the specified data types.
  • TEXT_VALUE_STRING : A combination of support for full-text searches queries and range-search for NUMBER, TIMESTAMP and VARCHAR2 data types.

◉ Oracle Text Search Indexes


Oracle has a long history of full-text indexing for text data. You can read about it here.

- Full Text Indexing using Oracle Text

In Oracle 23ai we can create full-text search indexes using the CREATE SEARCH INDEX syntax. The full syntax is available here.

drop table if exists text_tab purge;

create table text_tab (
  id    number,
  data  clob
);

create search index text_tab_search_idx on text_tab (data);

Source: oracle-base.com

Saturday, July 6, 2024

Oracle Database 23ai Free RPM Installation On Oracle Linux 8 (OL8)

Oracle Database 23ai Free RPM Installation On Oracle Linux 8 (OL8)

Oracle Database 23ai free can be installed on Oracle Linux 8 using an RPM. This article describes the RPM installation of Oracle Database 23ai free 64-bit on Oracle Linux 8 (OL8) 64-bit. The article is based on a server installation with a minimum of 2G swap and secure Linux set to permissive.

1. Hosts File


The "/etc/hosts" file must contain a fully qualified name for the server.

<IP-address>  <fully-qualified-machine-name>  <machine-name>

For example.

127.0.0.1       localhost localhost.localdomain localhost4 localhost4.localdomain4
192.168.56.107  ol8-23.localdomain  ol8-23

Set the correct hostname in the "/etc/hostname" file.

ol8-23.localdomain

2. Oracle Installation


Download the relevant RPM from download page here.

- oracle-database-free-23ai-1.0-1.el8.x86_64.rpm

With the RPM file downloaded, we can install the Oracle prerequisites using the following commands as the "root" user.

dnf install -y oracle-database-preinstall-23ai

We now install the 23ai software using the following command as the root user. This assumes the RPM file is in the "/tmp" directory.

dnf -y localinstall /tmp/oracle-database-free-23ai-1.0-1.el8.x86_64.rpm

The ORACLE_HOME for the software installation is "/opt/oracle/product/23ai/dbhomeFree".

3. Create Database


In addition to the software installation, the RPM creates a script that allows us to create a demo database called "FREE", with a pluggable database (PDB) called "FREEPDB1". In the following example we set the DB_PASSWORD environment variable so we can do a silent database creation using the script.

# export DB_PASSWORD=SysPassword1

# (echo "${DB_PASSWORD}"; echo "${DB_PASSWORD}";) | /etc/init.d/oracle-free-23ai configure
Specify a password to be used for database accounts. Oracle recommends that the password entered should be at least 8 characters in length, contain at least 1 uppercase character, 1 lower case character and 1 digit [0-9]. Note that the same password will be used for SYS, SYSTEM and PDBADMIN accounts:
Confirm the password:
Configuring Oracle Listener.
Listener configuration succeeded.
Configuring Oracle Database FREE.
Enter SYS user password:
*************
Enter SYSTEM user password:
**************
Enter PDBADMIN User Password:
************
Prepare for db operation
7% complete
Copying database files
29% complete
Creating and starting Oracle instance
30% complete
33% complete
36% complete
39% complete
43% complete
Completing Database Creation
47% complete
49% complete
50% complete
Creating Pluggable Databases
54% complete
71% complete
Executing Post Configuration Actions
93% complete
Running Custom Scripts
100% complete
Database creation complete. For details check the logfiles at:
 /opt/oracle/cfgtoollogs/dbca/FREE.
Database Information:
Global Database Name:FREE
System Identifier(SID):FREE
Look at the log file "/opt/oracle/cfgtoollogs/dbca/FREE/FREE.log" for further details.

Connect to Oracle Database using one of the connect strings:
     Pluggable database: localhost.localdomain/FREEPDB1
     Multitenant container database: localhost.localdomain
[root@localhost yum.repos.d]#

We can of course create a database in the normal way, using the Database Configuration Assistant (DBCA). We don't have to use this script.

4. Using It


From the "oracle" user we can connect as follows.

export ORACLE_HOME=/opt/oracle/product/23ai/dbhomeFree
export PATH=$ORACLE_HOME/bin:$PATH

-- Root container
sqlplus sys/SysPassword1@//localhost:1521/free as sysdba

-- Pluggable database
sqlplus sys/SysPassword1@//localhost:1521/freepdb1 as sysdba

We can stop and start the service from the root user with the following commands.

/etc/init.d/oracle-free-23ai stop
/etc/init.d/oracle-free-23ai start

5. Vagrant Example


If you want to see it in action, you might want to try one of these Vagrant build.


Source: oracle-base.com

Friday, July 5, 2024

Oracle Database 23ai Free RPM Installation On Oracle Linux 9 (OL9)

Oracle Database 23ai Free RPM Installation On Oracle Linux 9 (OL9)

Oracle Database 23ai free can be installed on Oracle Linux 9 using an RPM. This article describes the RPM installation of Oracle Database 23ai free 64-bit on Oracle Linux 9 (OL9) 64-bit. The article is based on a server installation with a minimum of 2G swap and secure Linux set to permissive.

◉ Hosts File


The "/etc/hosts" file must contain a fully qualified name for the server.

<IP-address>  <fully-qualified-machine-name>  <machine-name>

For example.

127.0.0.1       localhost localhost.localdomain localhost4 localhost4.localdomain4
192.168.56.107  ol9-23.localdomain  ol9-23

Set the correct hostname in the "/etc/hostname" file.

ol9-23.localdomain

◉ Oracle Installation


Download the relevant RPM from download page here.

- oracle-database-free-23ai-1.0-1.el9.x86_64.rpm

With the RPM file downloaded, we can install the Oracle prerequisites using the following commands as the "root" user.

dnf install -y oracle-database-preinstall-23ai

We now install the 23ai software using the following command as the root user. This assumes the RPM file is in the "/tmp" directory.

dnf -y localinstall /tmp/oracle-database-free-23ai-1.0-1.el9.x86_64.rpm

The ORACLE_HOME for the software installation is "/opt/oracle/product/23ai/dbhomeFree".

◉ Create Database


In addition to the software installation, the RPM creates a script that allows us to create a demo database called "FREE", with a pluggable database (PDB) called "FREEPDB1". In the following example we set the DB_PASSWORD environment variable so we can do a silent database creation using the script.

# export DB_PASSWORD=SysPassword1

# (echo "${DB_PASSWORD}"; echo "${DB_PASSWORD}";) | /etc/init.d/oracle-free-23ai configure
Specify a password to be used for database accounts. Oracle recommends that the password entered should be at least 8 characters in length, contain at least 1 uppercase character, 1 lower case character and 1 digit [0-9]. Note that the same password will be used for SYS, SYSTEM and PDBADMIN accounts:
Confirm the password:
Configuring Oracle Listener.
Listener configuration succeeded.
Configuring Oracle Database FREE.
Enter SYS user password:
*************
Enter SYSTEM user password:
**************
Enter PDBADMIN User Password:
************
Prepare for db operation
7% complete
Copying database files
29% complete
Creating and starting Oracle instance
30% complete
33% complete
36% complete
39% complete
43% complete
Completing Database Creation
47% complete
49% complete
50% complete
Creating Pluggable Databases
54% complete
71% complete
Executing Post Configuration Actions
93% complete
Running Custom Scripts
100% complete
Database creation complete. For details check the logfiles at:
 /opt/oracle/cfgtoollogs/dbca/FREE.
Database Information:
Global Database Name:FREE
System Identifier(SID):FREE
Look at the log file "/opt/oracle/cfgtoollogs/dbca/FREE/FREE.log" for further details.

Connect to Oracle Database using one of the connect strings:
     Pluggable database: localhost.localdomain/FREEPDB1
     Multitenant container database: localhost.localdomain
[root@localhost yum.repos.d]#

We can of course create a database in the normal way, using the Database Configuration Assistant (DBCA). We don't have to use this script.

◉ Using It


From the "oracle" user we can connect as follows.

export ORACLE_HOME=/opt/oracle/product/23ai/dbhomeFree
export PATH=$ORACLE_HOME/bin:$PATH

-- Root container
sqlplus sys/SysPassword1@//localhost:1521/free as sysdba

-- Pluggable database
sqlplus sys/SysPassword1@//localhost:1521/freepdb1 as sysdba

We can stop and start the service from the root user with the following commands.

/etc/init.d/oracle-free-23ai stop
/etc/init.d/oracle-free-23ai start

◉ Vagrant Example


If you want to see it in action, you might want to try one of these Vagrant build.


Source: oracle-base.com

Saturday, June 29, 2024

EMPTY STRING ON NULL for JSON Generation in Oracle Database 23ai

EMPTY STRING ON NULL for JSON Generation in Oracle Database 23ai

Oracle database 23ai has introduced the ability to convert nulls to empty strings during JSON generation.

◉ Setup


We create and populate a table. Notice each row has a different combination of values with regards to null.

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

drop table if exists t1 purge;

create table t1 (
  col1 VARCHAR2(10),
  col2 VARCHAR2(10)
);

insert into t1 values ('ONE', 'TWO');
insert into t1 values ('ONE', null);
insert into t1 values (null, 'TWO');
insert into t1 values (null, null);
commit;


select rownum, col1, col2 from t1;

 ROWNUM COL1 COL2
----------      --------- ----------
         1          ONE       TWO
         2         ONE
         3                         TWO
         4

SQL>

◉ NULL ON NULL and ABSENT ON NULL


In previous releases our only options for null handling during JSON generation were NULL ON NULL and ABSENT ON NULL. We'll use JSON_OBJECT as an example, where the default behaviour is NULL ON NULL.

When using NULL ON NULL, implicitly or explictly, any null values in the data are generated as "null" in the output.

-- Implicit - NULL ON NULL.
select json_object(*) as data from t1;

DATA
--------------------------------------------------------------------------------
{"COL1":"ONE","COL2":"TWO"}
{"COL1":"ONE","COL2":null}
{"COL1":null,"COL2":"TWO"}
{"COL1":null,"COL2":null}

SQL>


-- Explicit - NULL ON NULL.
select json_object(* null on null) as data from t1;

DATA
--------------------------------------------------------------------------------
{"COL1":"ONE","COL2":"TWO"}
{"COL1":"ONE","COL2":null}
{"COL1":null,"COL2":"TWO"}
{"COL1":null,"COL2":null}

SQL>

When using ABSENT ON NULL any null values in the data result in the corresponding element being removed from the output.

select json_object(* absent on null) as data from t1;

DATA
--------------------------------------------------------------------------------
{"COL1":"ONE","COL2":"TWO"}
{"COL1":"ONE"}
{"COL2":"TWO"}
{}

SQL>

Here's an example with JSON_ARRAY, which uses ABSENT ON NULL by default.

-- Default - ABSENT ON NULL
select json_array(col1) as data from t1;

DATA
--------------------------------------------------------------------------------
["ONE"]
["ONE"]
[]
[]

SQL>


-- Explicit - ABSENT ON NULL
select json_array(col1 absent on null) as data from t1;

DATA
--------------------------------------------------------------------------------
["ONE"]
["ONE"]
[]
[]

SQL>


-- NULL ON NULL
select json_array(col1 null on null) as data from t1;

DATA
--------------------------------------------------------------------------------
["ONE"]
["ONE"]
[null]
[null]

SQL>

◉ EMPTY STRING ON NULL


In Oracle database 23ai we now have the option of using EMPTY STRING ON NULL. In this case null values are presented as empty strings in the output.

Here we see JSON_OBJECT being used with EMPTY STRING ON NULL.

select json_object(* empty string on null) as data from t1;

DATA
--------------------------------------------------------------------------------
{"COL1":"ONE","COL2":"TWO"}
{"COL1":"ONE","COL2":""}
{"COL1":"","COL2":"TWO"}
{"COL1":"","COL2":""}

SQL>

Here is an example of JSON_ARRAY using EMPTY STRING ON NULL.

select json_array(col1 empty string on null) as data from t1;

DATA
--------------------------------------------------------------------------------
["ONE"]
["ONE"]
[""]
[""]

SQL>

◉ Thoughts


In Oracle SQL and PL/SQL an empty string and a null are treated the same. This is not the case in other languages, so it's important to give people an option of presenting nulls as empty strings if required.

The default null handling of each JSON generation function can differ, so it's important to check the documentation, or always be explicit so other developers know your intentions.

Source: oracle-base.com

Friday, June 21, 2024

Direct Joins for UPDATE and DELETE Statements in Oracle Database 23ai

Direct Joins for UPDATE and DELETE Statements in Oracle Database 23ai

From Oracle database 23ai onward we are allowed to use direct joins to tables to drive UPDATE and DELETE statements.

◉ Setup


The following tables are necessary to run the examples in this article.

drop table if exists t1 purge;
drop table if exists t2 purge;
drop table if exists t3 purge;

create table t1 as
select level as id,
       'CODE' || level as code,
       'Description for ' || level as description
from   dual
connect by level <= 100;

alter table t1 add constraint t1_pk primary key (id);

create table t2 as
select level as id,
       'CODE' || (level*10) as code,
       'Updated description for ' || (level*10) as description
from   dual
connect by level <= 100;

alter table t2 add constraint t2_pk primary key (id);

create table t3 as
select level as id,
       'CODE' || (level*10) as code,
       'Updated description for ' || (level*10) as description
from   dual
connect by level <= 100;

alter table t3 add constraint t3_pk primary key (id);

◉ Direct Joins for UPDATE


First we check the data for the first five rows.

column code format a10
column description format a30

select * from t1 where id <= 5;

        ID CODE       DESCRIPTION
---------- ---------- ------------------------------
         1 CODE1      Description for 1
         2 CODE2      Description for 2
         3 CODE3      Description for 3
         4 CODE4      Description for 4
         5 CODE5      Description for 5

SQL>

Now we update the data in T1 using a join to the T2 table. We want to update the T1.CODE and T1.DESCRIPTION values, using the values from T2.CODE and T2.DESCRIPTION using a join in the ID value.

update t1 a 
set    a.code        = b.code,
       a.description = b.description
from   t2 b
where  a.id = b.id
and    b.id <= 5; 

Now we see the T1.CODE and T1.DESCRIPTION values have been updated.

select * from t1 where id <= 5;

        ID CODE       DESCRIPTION
---------- ---------- ------------------------------
         1 CODE10     Updated description for 10
         2 CODE20     Updated description for 20
         3 CODE30     Updated description for 30
         4 CODE40     Updated description for 40
         5 CODE50     Updated description for 50

SQL>

Let's rollback the changes.

rollback;

We can't use the ANSI join syntax between T1 and T2, but if there were several tables driving the update, those could be joined together using ANSI joins. The following example is a bit silly, but it proves a point by joining T2 to T3.

update t1 a 
set    a.code        = b.code,
       a.description = b.description
from   t2 b
join   t3 c on b.id = c.id
where  a.id = b.id
and    b.id <= 5;

rollback;

◉ Direct Joins for DELETE


First we check the data for the first five rows.

column code format a10
column description format a30

select * from t1 where id <= 5;

        ID CODE       DESCRIPTION
-------- ---------- ------------------------------
         1 CODE1      Description for 1
         2 CODE2      Description for 2
         3 CODE3      Description for 3
         4 CODE4      Description for 4
         5 CODE5      Description for 5

SQL>

We delete rows from T1 based on a query from T2. Notice we have a join between the two tables using the ID column, and one or more predicates to determine which rows from T2 are being used to drive the delete.

delete t1 a 
from   t2 b
where  a.id = b.id
and    b.id <= 5; 

We can see the rows have been deleted.

select * from t1 where id <= 5;

no rows selected

SQL>

Let's rollback the changes.

rollback;

We can add in the FROM keyword after the DELETE keyword, but it doesn't scan well.

delete from t1 a 
from   t2 b
where  a.id = b.id
and    b.id <= 5;

rollback;

We can't use the ANSI join syntax between T1 and T2, but if there were several tables driving the delete, those could be joined together using ANSI joins. The following example is a bit silly, but it proves a point by joining T2 to T3.

delete t1 a 
from   t2 b
join   t3 c on b.id = c.id
where  a.id = b.id
and    b.id <= 5;

rollback;

Source: oracle-base.com

Wednesday, June 19, 2024

DML RETURNING Clause Enhancements in Oracle Database 23ai

DML RETURNING Clause Enhancements in Oracle Database 23ai

This article demonstrates the enhancements to the DML RETURNING clause introduced in Oracle database 23ai.

Setup


The following tables are required to run the examples in this article.

drop table if exists t1;

create table t1 (
  id number,
  code varchar2(6),
  description varchar(25),
  constraint t1_pk primary key (id)
);

insert into t1 values (1, 'ONE', 'Description for ONE');
insert into t1 values (2, 'TWO', 'Description for TWO');
commit;


drop table if exists t2;

create table t2 (
  id          number,
  code        varchar2(6),
  description varchar(25),
  constraint t2_pk primary key (id)
);

insert into t2 values (3, 'THREE', 'Description for THREE');
insert into t2 values (4, 'FOUR', 'Description for FOUR');
commit;

Single Row Update


We can now return old and new values of columns from rows that are touched by an UPDATE statement.

( RETURN | RETURNING) ( OLD | NEW )  expr [ , ( OLD | NEW ) expr ]+ 
INTO  [data_item] ...

In this example we define a variables to hold the old and new values of the CODE and DESCRIPTION columns. We update the T1 table, appending "2" on to the end of the CODE and DESCRIPTION column values for the second row. The RETURNING clause defines the values we want to return, using the OLD and NEW keywords to indicate which value. The INTO clause lists the variables to hold those values.

set serveroutput on
declare
  l_old_code        t1.code%type;
  l_old_description t1.description%type;
  l_new_code        t1.code%type;
  l_new_description t1.description%type;
begin
  update t1
  set    code        = code || '2',
         description = description || '2'
  where  id          = 2
  returning old code , old description, new code, new description
  into l_old_code, l_old_description, l_new_code, l_new_description;

  dbms_output.put_line('l_old_code        = ' || l_old_code);
  dbms_output.put_line('l_old_description = ' || l_old_description);
  dbms_output.put_line('l_new_code        = ' || l_new_code);
  dbms_output.put_line('l_new_description = ' || l_new_description);

  rollback;
END;
/
l_old_code        = TWO
l_old_description = Description for TWO
l_new_code        = TWO2
l_new_description = Description for TWO2

PL/SQL procedure successfully completed.

SQL>

Multiple Row Update


We can do something similar for updates that touch multiple rows, but this time we need to use collections to hold the returned values. In this example we define a collection for each of the returned values. We update the table in a similar way, but this time we change INTO to a BULK COLLECT INTO and list the collections to hold the returned values. We loop through the collections to display the returned values.

set serveroutput on
declare
  type l_old_code_t is table of t1.code%type;
  type l_old_description_t is table of t1.description%type;
  type l_new_code_t is table of t1.code%type;
  type l_new_description_t is table of t1.description%type;

  l_old_code        l_old_code_t;
  l_old_description l_old_description_t;
  l_new_code        l_new_code_t;
  l_new_description l_new_description_t;
begin
  update t1
  set    code        = code || '1',
         description = description || '1'
  returning old code, old description, new code, new description
  bulk collect into l_old_code, l_old_description, l_new_code, l_new_description;

  for i in 1 .. l_old_code.count loop
    dbms_output.put_line('row               = ' || i);
    dbms_output.put_line('l_old.code        = ' || l_old_code(i));
    dbms_output.put_line('l_old.description = ' || l_old_description(i));
    dbms_output.put_line('l_new.code        = ' || l_new_code(i));
    dbms_output.put_line('l_new.description = ' || l_new_description(i));
  end loop;

  rollback;
end;
/
row               = 1
l_old.code        = ONE
l_old.description = Description for ONE
l_new.code        = ONE1
l_new.description = Description for ONE1
row               = 2
l_old.code        = TWO
l_old.description = Description for TWO
l_new.code        = TWO1
l_new.description = Description for TWO1

PL/SQL procedure successfully completed.

SQL>

Insert and Delete


The NEW and OLD keywords can be used on INSERT and DELETE also, but they don't bring anything new to the table. For inserts we have no old values, and for deletes we have no new values.

set serveroutput on
declare
  l_old_code        t1.code%type;
  l_old_description t1.description%type;
  l_new_code        t1.code%type;
  l_new_description t1.description%type;
begin
  insert into t1 (id, code, description)
  values (5, 'FIVE', 'Description for FIVE')
  returning old code , old description, new code, new description
  into l_old_code, l_old_description, l_new_code, l_new_description;

  dbms_output.put_line('l_old_code        = ' || l_old_code);
  dbms_output.put_line('l_old_description = ' || l_old_description);
  dbms_output.put_line('l_new_code        = ' || l_new_code);
  dbms_output.put_line('l_new_description = ' || l_new_description);

  rollback;
END;
/
l_old_code        =
l_old_description =
l_new_code        = FIVE
l_new_description = Description for FIVE

PL/SQL procedure successfully completed.

SQL>

set serveroutput on
declare
  l_old_code        t1.code%type;
  l_old_description t1.description%type;
  l_new_code        t1.code%type;
  l_new_description t1.description%type;
begin
  delete from t1
  where  id = 2
  returning old code , old description, new code, new description
  into l_old_code, l_old_description, l_new_code, l_new_description;

  dbms_output.put_line('l_old_code        = ' || l_old_code);
  dbms_output.put_line('l_old_description = ' || l_old_description);
  dbms_output.put_line('l_new_code        = ' || l_new_code);
  dbms_output.put_line('l_new_description = ' || l_new_description);

  rollback;
END;
/
l_old_code        = TWO
l_old_description = Description for TWO
l_new_code        =
l_new_description =

PL/SQL procedure successfully completed.

SQL>

Source: oracle-base.com

Monday, June 17, 2024

CASE Statement and CASE Expression Enhancements in Oracle Database 23ai

CASE Statement and CASE Expression Enhancements in Oracle Database 23ai

In Oracle database 23ai the simple CASE statement and expression are more flexible, allowing dangling predicates and multiple choices in a single WHEN clause.

This brings the PL/SQL simple CASE statement and expression in line with the SQL:2003 Standard [ISO03a, ISO03b] standard.

◉ Setup


The examples in this article use the following table.

drop table if exists t1 purge;

create table t1 (
  pct number
);

insert into t1 (pct)
values (-1), (0), (10), (40), (70), (80), (90), (100), (101);
commit;

◉ The Problem


In previous releases simple CASE statements and expressions were only capable of performing equality checks. If we needed comparisons other than equality checks we would have to use a searched case statement or expression.

In the following example we use a searched CASE statement to evaluate a threshold. We are using a searched CASE statement because most of the comparisons are not simple equality checks.

set serveroutput on
declare
  l_threshold varchar2(20);
begin
  for cur_rec in (select pct from t1) loop
    case 
      when cur_rec.pct  = 40 then l_threshold := 'Optimal';
      when cur_rec.pct <= 70 then l_threshold := 'Safe';
      when cur_rec.pct <= 80 then l_threshold := 'Check';
      when cur_rec.pct <= 90 then l_threshold := 'Warning';
      when cur_rec.pct  > 90 then l_threshold := 'Critical';
    end case;

    dbms_output.put_line(cur_rec.pct || ' : ' || l_threshold);
  end loop;
end;
/
-1 : Safe
0 : Safe
10 : Safe
40 : Optimal
70 : Safe
80 : Check
90 : Warning
100 : Critical
101 : Critical

PL/SQL procedure successfully completed.

SQL>

This example uses a searched CASE expression to do the same thing.

set serveroutput on
declare
  l_threshold varchar2(20);
begin
  for cur_rec in (select pct from t1) loop
    l_threshold := case 
                     when cur_rec.pct  = 40 then 'Optimal'
                     when cur_rec.pct <= 70 then 'Safe'
                     when cur_rec.pct <= 80 then 'Check'
                     when cur_rec.pct <= 90 then 'Warning'
                     when cur_rec.pct  > 90 then 'Critical'
                   end;

    dbms_output.put_line(cur_rec.pct || ' : ' || l_threshold);
  end loop;
end;
/
-1 : Safe
0 : Safe
10 : Safe
40 : Optimal
70 : Safe
80 : Check
90 : Warning
100 : Critical
101 : Critical

PL/SQL procedure successfully completed.

SQL>

◉ Dangling Predicates


In Oracle 23ai we can do the same thing using a simple CASE statement or expression using dangling predicates. A dangling predicate is an expression with its left operand missing.

This example uses a simple CASE statement with dangling predicates to achieve the same result.

set serveroutput on
declare
  l_threshold varchar2(20);
begin
  for cur_rec in (select pct from t1) loop
    case cur_rec.pct
      when 40    then l_threshold := 'Optimal';
      when <= 70 then l_threshold := 'Safe';
      when <= 80 then l_threshold := 'Check';
      when <= 90 then l_threshold := 'Warning';
      when  > 90 then l_threshold := 'Critical';
    end case;

    dbms_output.put_line(cur_rec.pct || ' : ' || l_threshold);
  end loop;
end;
/
-1 : Safe
0 : Safe
10 : Safe
40 : Optimal
70 : Safe
80 : Check
90 : Warning
100 : Critical
101 : Critical

PL/SQL procedure successfully completed.

SQL>

Here is the simple CASE expression equivalent.

set serveroutput on
declare
  l_threshold varchar2(20);
begin
  for cur_rec in (select pct from t1) loop
    l_threshold := case cur_rec.pct
                     when 40    then 'Optimal'
                     when <= 70 then 'Safe'
                     when <= 80 then 'Check'
                     when <= 90 then 'Warning'
                     when  > 90 then 'Critical'
                   end;

    dbms_output.put_line(cur_rec.pct || ' : ' || l_threshold);
  end loop;
end;
/
-1 : Safe
0 : Safe
10 : Safe
40 : Optimal
70 : Safe
80 : Check
90 : Warning
100 : Critical
101 : Critical

PL/SQL procedure successfully completed.

SQL>

◉ Multiple Choices in a Single WHEN Clause


A single WHEN clause can include multiple equality checks or dangling predicates as a comma-separated list.

In the following example we use a simple CASE statement to show an error if a value is below 0, exactly 0.5 or greater than 100. We also add values 41 and 42 to the optimal threshold.

set serveroutput on
declare
  l_threshold varchar2(20);
begin
  for cur_rec in (select pct from t1) loop
    case cur_rec.pct
      when < 0, 0.5, > 100 then l_threshold := 'Error';
      when 40, 41, 42      then l_threshold := 'Optimal';
      when <= 70           then l_threshold := 'Safe';
      when <= 80           then l_threshold := 'Check';
      when <= 90           then l_threshold := 'Warning';
      when  > 90           then l_threshold := 'Critical';
    end case;

    dbms_output.put_line(cur_rec.pct || ' : ' || l_threshold);
  end loop;
end;
/
-1 : Error
0 : Safe
10 : Safe
40 : Optimal
70 : Safe
80 : Check
90 : Warning
100 : Critical
101 : Error

PL/SQL procedure successfully completed.

SQL>

This is the simple CASE expression equivalent of the previous example.

set serveroutput on
declare
  l_threshold varchar2(20);
begin
  for cur_rec in (select pct from t1) loop
    l_threshold := case cur_rec.pct
                     when < 0, 0.5, > 100 then 'Error'
                     when 40, 41, 42      then 'Optimal'
                     when <= 70           then 'Safe'
                     when <= 80           then 'Check'
                     when <= 90           then 'Warning'
                     when  > 90           then 'Critical'
                   end;

    dbms_output.put_line(cur_rec.pct || ' : ' || l_threshold);
  end loop;
end;
/
-1 : Error
0 : Safe
10 : Safe
40 : Optimal
70 : Safe
80 : Check
90 : Warning
100 : Critical
101 : Error

PL/SQL procedure successfully completed.

SQL>

◉ SQL CASE Expressions


This functionality is not supported directly by SQL CASE expressions.

select pct,
       case pct
         when 0.5, < 0, > 100 then 'Error'
         when 40, 41, 42      then 'Optimal'
         when <= 70           then 'Safe'
         when <= 80           then 'Check'
         when <= 90           then 'Warning'
         when  > 90           then 'Critical'
       end as status
from   t1;

when 0.5, < 0, > 100 then 'Error'
                 *
ERROR at line 3:
ORA-02000: missing THEN keyword

SQL>

We can achieve a similar result by defining a function in the WITH clause to perform the CASE expression.

with
  function get_status(p_pct in number) return varchar2 is
  begin
    return case p_pct
             when < 0, 0.5, > 100 then 'Error'
             when 40, 41, 42      then 'Optimal'
             when <= 70           then 'Safe'
             when <= 80           then 'Check'
             when <= 90           then 'Warning'
             when  > 90           then 'Critical'
           end;
  end;
select pct, get_status(pct) as status
from   t1
/

       PCT STATUS
---------- --------------------------
        -1 Error
         0 Safe
        10 Safe
        40 Optimal
        70 Safe
        80 Check
        90 Warning
       100 Critical
       101 Error

9 rows selected.

SQL>

Source: oracle-base.com

Saturday, June 15, 2024

DB_DEVELOPER_ROLE Role in Oracle Database 23ai

DB_DEVELOPER_ROLE Role in Oracle Database 23ai

Oracle database 23ai introduced a new DB_DEVELOPER_ROLE role to provide the basic roles and privileges Oracle believe are necessary for a database developer.

◉ DB_DEVELOPER_ROLE Role Basics


Oracle database 23ai introduced a new DB_DEVELOPER_ROLE role to provide the basic roles and privileges Oracle believe are necessary for a database developer. Prior to this release, people would often grant the CONNECT and RESOURCE roles as a starting point for most developers, but the DB_DEVELOPER_ROLE role is more than the sum of these two roles, as we will see below.

The DB_DEVELOPER_ROLE role is granted and revoked in the normal way.

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

grant db_developer_role to testuser1;

revoke db_developer_role from testuser1;

◉ Comparing CONNECT, RESOURCE and DB_DEVELOPER_ROLE


The following three sections display the system, role and object privileges associated with each role.

    ◉ CONNECT Role

Here are the system, role and object privileges associated with the CONNECT role.

variable v_role VARCHAR2(30)
exec :v_role := 'CONNECT';

-- System Privileges
select sp.privilege
from   dba_sys_privs sp
where  sp.grantee = :v_role
order by 1;

PRIVILEGE
----------------------------------------
CREATE SESSION
SET CONTAINER

SQL>

-- Role Privileges
select rp.granted_role
from   dba_role_privs rp
where  rp.grantee = :v_role
order by 1;

no rows selected

SQL>

-- Object Privileges
column privilege format a30
column table_name format a30

select tp.privilege, tp.table_name 
from   dba_tab_privs tp
where  tp.grantee = :v_role
order by 1, 2;

no rows selected

SQL>

    ◉ RESOURCE Role

DB_DEVELOPER_ROLE Role in Oracle Database 23ai
Here are the system, role and object privileges associated with the RESOURCE role. There are seven more system privileges granted to the RESOURCE role in 23ai compared to 19c.

variable v_role VARCHAR2(30)
exec :v_role := 'RESOURCE';

-- System Privileges
select sp.privilege
from   dba_sys_privs sp
where  sp.grantee = :v_role
order by 1;

PRIVILEGE
----------------------------------------
CREATE ANALYTIC VIEW
CREATE ATTRIBUTE DIMENSION
CREATE CLUSTER
CREATE HIERARCHY
CREATE INDEXTYPE
CREATE MATERIALIZED VIEW
CREATE OPERATOR
CREATE PROCEDURE
CREATE PROPERTY GRAPH
CREATE SEQUENCE
CREATE SYNONYM
CREATE TABLE
CREATE TRIGGER
CREATE TYPE
CREATE VIEW

15 rows selected.

SQL>

-- Role Privileges
select rp.granted_role
from   dba_role_privs rp
where  rp.grantee = :v_role
order by 1;

GRANTED_ROLE
------------------------------------------------
SODA_APP

SQL>

-- Object Privileges
column table_name format a30

select tp.privilege, tp.table_name 
from   dba_tab_privs tp
where  tp.grantee = :v_role
order by 1, 2;

no rows selected

SQL>

    ◉ DB_DEVELOPER_ROLE Role

Here are the system, role and object privileges associated with the DB_DEVELOPER_ROLE role.

variable v_role VARCHAR2(30)
exec :v_role := 'DB_DEVELOPER_ROLE';

-- System Privileges
select sp.privilege
from   dba_sys_privs sp
where  sp.grantee = :v_role
order by 1;

PRIVILEGE
------------------------------
CREATE CUBE
CREATE CUBE BUILD PROCESS
CREATE CUBE DIMENSION
CREATE DIMENSION
CREATE DOMAIN
CREATE JOB
CREATE MINING MODEL
CREATE MLE
CREATE SESSION
DEBUG CONNECT SESSION
EXECUTE DYNAMIC MLE
FORCE TRANSACTION
ON COMMIT REFRESH

13 rows selected.

SQL>

-- Role Privileges
select rp.granted_role
from   dba_role_privs rp
where  rp.grantee = :v_role
order by 1;

GRANTED_ROLE
------------------------------------------------
CTXAPP
RESOURCE

SQL>

-- Object Privileges
column privilege format a30
column table_name format a30

select tp.privilege, tp.table_name 
from   dba_tab_privs tp
where  tp.grantee = :v_role
order by 1, 2;

PRIVILEGE                      TABLE_NAME
------------------------- ------------------------------
EXECUTE                        DBMS_REDACT
EXECUTE                        DBMS_RLS
EXECUTE                        DBMS_TSDP_MANAGE
EXECUTE                        DBMS_TSDP_PROTECT
EXECUTE                        JAVASCRIPT
READ                               V_$PARAMETER
READ                               V_$STATNAME
SELECT                           DBA_PENDING_TRANSACTIONS

SQL>

◉ Considerations


For many years we have been discouraged from using the predefined roles, and encouraged to use the "least privileges" approach when granting privileges to users. From a security perspective, the less privileges a user has, the smaller the attack surface.

We can see from the above comparison, the DB_DEVELOPER_ROLE role has more privileges than the CONNECT and the RESOURCE roles combined. For some people or companies this might be considered too much privilege. It's up to you or your company to decide if this role is suitable or not.

The addition of more privileges to the RESOURCE role means people who are in the habit of granting the CONNECT plus RESOURCE roles are getting something approaching the level of privilege granted by the DB_DEVELOPER_ROLE. It is worth considering the impact of this.

Source: oracle-base.com

Friday, June 14, 2024

Bigfile Tablespace Defaults in Oracle Database 23ai

Bigfile Tablespace Defaults in Oracle Database 23ai

Bigfile tablespaces were introduced in Oracle 10g. In Oracle database 23ai bigfile tablespaces are the default.

◉ BIGFILE Default for SYSAUX, SYSTEM, and USER Tablespaces


In Oracle database 23ai most of the Oracle provided tablespaces are bigfile tablespaces by default.

We connect to the root container and check out the tablespaces for this container. All are bigfile tablespaces excluding the TEMP tablespace.

conn / as sysdba

select tablespace_name, bigfile
from   dba_tablespaces
order by 1;

TABLESPACE_NAME      BIG
------------------------------  ---
SYSAUX                         YES
SYSTEM                         YES
TEMP                              NO
UNDOTBS1                    YES
USERS                           YES

SQL>

We switch to a pluggable database and display the tablespaces for this container. This is similar, but the USERS tablespace in the PDB is a smallfile tablespace. This is the default behaviour in this release of 23ai Free.

alter session set container=freepdb1;

select tablespace_name, bigfile
from   dba_tablespaces
order by 1;

TABLESPACE_NAME   BIG
------------------------------ ---
SYSAUX                         YES
SYSTEM                         YES
TEMP                              NO
UNDOTBS1                   YES
USERS                           NO

SQL>

◉ BIGFILE Default for User Defined Tablespaces


Bigfile is the default file size when creating a new tablespace. In the following example we create a new tablespace without explicitly setting the bigfile/smallfile file size. We are using Oracle Managed Files (OMF), so we don't need to manually name the associated datafile.

create tablespace new_ts datafile size 2g;

Notice the new tablespace has been created as a bigfile tablespace.

select tablespace_name, bigfile
from   dba_tablespaces
order by 1;

TABLESPACE_NAME    BIG
------------------------------ ---
NEW_TS                         YES
SYSAUX                         YES
SYSTEM                         YES
TEMP                               NO
UNDOTBS1                    YES
USERS                            NO

SQL>

◉ Considerations


These new defaults were introduced in 23.4. if I run the same tests in 23.3 I get the following.

conn / as sysdba

select tablespace_name, bigfile
from   dba_tablespaces
order by 1;

TABLESPACE_NAME   BIG
------------------------------ ---
SYSAUX                         NO
SYSTEM                         NO
TEMP                              NO
UNDOTBS1                    NO
USERS                            NO

SQL>

alter session set container=pdb1;

select tablespace_name, bigfile
from   dba_tablespaces
order by 1;

TABLESPACE_NAME   BIG
------------------------------ ---
SYSAUX                         NO
SYSTEM                         NO
TEMP                              NO
UNDOTBS1                    NO
USERS                            NO

6 rows selected.

SQL>

create tablespace new_ts datafile size 2g;

select tablespace_name, bigfile
from   dba_tablespaces
order by 1;

TABLESPACE_NAME  BIG
------------------------------ ---
NEW_TS                         NO
SYSAUX                         NO
SYSTEM                         NO
TEMP                              NO
UNDOTBS1                   NO
USERS                            NO

SQL>

I've been told some of the 23ai cloud services have different defaults in this behaviour. I suspect this is because of different versions of the software at the point of the image creation they are based on. I would expect future release updates to result in all tablespaces, including TEMP, to be bigfile when a clean installation is performed.

Source: oracle-base.com

Monday, June 10, 2024

Bigfile Tablespace Shrink in Oracle Database 23ai

Oracle Database 23ai, Oracle Database Certification, Oracle Database Prep, Oracle Database Guides, Oracle Database Learning

From Oracle database 23ai onward we can use the DBMS_SPACE package to shrink a bigfile tablespace to reclaim unused space.

◉ Setup


We need a tablespace to run some tests. In Oracle database 23ai the default file size for a tablespace is bigfile, so we don't need to specify it explicitly.

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

-- Create a tablespace and user for the test.
drop user if exists reclaim_user cascade;
drop tablespace if exists reclaim_ts including contents and datafiles;

create tablespace reclaim_ts datafile size 10m autoextend on next 1m;

create user reclaim_user identified by reclaim_user default tablespace reclaim_ts quota unlimited on reclaim_ts;
grant create session, create table to reclaim_user;
grant select_catalog_role to reclaim_user;

-- Create and populate two tables in the test schema.
conn reclaim_user/reclaim_user@//localhost:1521/freepdb1

create table t1 (
  id   number,
  col1 varchar2(4000),
  col2 varchar2(4000),
  constraint t1_pk primary key (id)
);

create table t2 (
  id   number,
  col1 varchar2(4000),
  col2 varchar2(4000),
  constraint t2_pk primary key (id)
);

insert /*+append*/ into t1
select rownum, rpad('x', 4000, 'x'), rpad('x', 4000, 'x')
from dual
connect by level <= 100000;
commit;

insert /*+append*/ into t2
select rownum, rpad('x', 4000, 'x'), rpad('x', 4000, 'x')
from dual
connect by level <= 100000;
commit;

exec dbms_stats.gather_table_stats(null, 't1');
exec dbms_stats.gather_table_stats(null, 't2');

We check the size of the datafile associated with the tablespace and the tables.

select tablespace_name, blocks, bytes/1024/1024 as size_mb
from   dba_data_files
where  tablespace_name = 'RECLAIM_TS';

TABLESPACE_NAME                    BLOCKS    SIZE_MB
------------------------------                   ---------- ----------
RECLAIM_TS                                      427520       3340

SQL>

column table_name format a10

select table_name, blocks, (blocks*8)/1024 as size_mb
from   user_tables
where  table_name in ('T1', 'T2')
order by 1;

TABLE_NAME     BLOCKS    SIZE_MB
----------                ----------   ----------
T1                          200696      1567.9375
T2                          200694     1567.92188

SQL>

We truncate the first table, leaving a gap in the datafile before the table segments start.

truncate table t1;

exec dbms_stats.gather_table_stats(null, 't1');

We can repeat this setup between tests to start cleanly.

◉ Analyze Bigfile Tablespace


We run an analyze to see how much space we can save by performing a shrink. We call the SHRINK_SPACE procedure in the DBMS_SPACE package, passing in the name of the bigfile tablespace name and the TS_MODE_ANALYZE shrink mode constant.

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

set serveroutput on
execute dbms_space.shrink_tablespace('RECLAIM_TS', shrink_mode => dbms_space.ts_mode_analyze);
-------------------ANALYZE RESULT-------------------
Total Movable Objects: 2
Total Movable Size(GB): 1.56
Original Datafile Size(GB): 3.39
Suggested Target Size(GB): 3.19
Process Time: +00 00:00:00.053777

PL/SQL procedure successfully completed.

SQL>

It doesn't think we can save much space, which sounds suspicious as we have truncated one table, which takes up approximately half of the space in the data file.

◉ Shrink Bigfile Tablespace


We run a shrink operation by calling the SHRINK_SPACE procedure with the tablespace name.

set serveroutput on
execute dbms_space.shrink_tablespace('RECLAIM_TS');
-------------------SHRINK RESULT-------------------
Total Moved Objects: 2
Total Moved Size(GB): 1.56
Original Datafile Size(GB): 3.26
New Datafile Size(GB): 1.63
Process Time: +00 00:00:30.586722

PL/SQL procedure successfully completed.

SQL>

Despite what the analyze said, we have reduced the associated datafile to approximately half its original size.

The previous command is the equivalent of calling the procedure with a shrink mode of TS_MODE_SHRINK and a target size of TS_TARGET_MAX_SHRINK.

set serveroutput on
execute dbms_space.shrink_tablespace('RECLAIM_TS', shrink_mode => dbms_space.ts_mode_shrink, target_size => dbms_space.ts_target_max_shrink);

Source: oracle-base.com