Home / OCI

OCITroubleshootingIntermediate

Autonomous Database DBMS_CLOUD.COPY_DATA fails: ORA-20401, ORA-20404 and reject limit errors

Fix failed Object Storage loads into Autonomous Database by separating credential, URI and data errors, then reading the log and bad-file tables.

Deepak Bhardwaj7 min read

Applies toOracle Autonomous Database Serverless, DBMS_CLOUD, OCI Object Storage

A DBMS_CLOUD.COPY_DATA load from OCI Object Storage fails with an ORA-20xxx error, or it finishes with fewer rows than expected. Work out which layer failed first: credential, object URI, or the data in the file. Each has a different fix.

Map the error to the layer

Symptom Likely cause Fix
ORA-20401 Wrong username or auth token, deleted token, or API key mismatch Recreate the credential
ORA-20403 Authenticated but not permitted Fix the IAM policy
ORA-20404 Wrong region, namespace, bucket or object name; can also be a missing permission Test with LIST_OBJECTS, then check policy
ORA-20003 Rejected rows exceeded rejectlimit Read the bad-file table
ORA-20004 Credential doesn't exist in this schema Check USER_CREDENTIALS
ORA-20005 Target table doesn't exist Create it; COPY_DATA doesn't
ORA-20006 or ORA-20011 URI not recognized or malformed Rebuild the URI
ORA-20009 Invalid format option or JSON Check option names and values
Success, too few rows Rows rejected within the limit, or wildcard matched fewer files Check log table and object list

ORA-20401, ORA-20403 and ORA-20404 follow the HTTP status that Object Storage returned. OCI often returns 404 instead of 403 so it doesn't reveal that a resource exists. Treat a 404 on a correct URI as a permission problem.

Check 1: Find the failed load

Run as the schema that ran the load:

SELECT id, type, status, table_name, start_time, rows_loaded,
       logfile_table, badfile_table
FROM   user_load_operations
WHERE  type = 'COPY'
ORDER  BY start_time DESC
FETCH FIRST 10 ROWS ONLY;

As ADMIN, use dba_load_operations to see other schemas.

Query the log and bad tables that the row names. Replace the number with yours:

SELECT * FROM COPY$42_LOG;
SELECT * FROM COPY$42_BAD;

The log usually shows the rejected record, the column, and the underlying Oracle error.

Warning

Log and bad tables are kept for two days by default. Copy what you need into your own table before it's removed, or raise logretention (days) in the load's format.

Check 2: Test the credential and URI without loading

This isolates access problems from data problems:

SELECT object_name, bytes, last_modified
FROM   DBMS_CLOUD.LIST_OBJECTS(
         credential_name => 'OBJ_STORE_CRED',
         location_uri    => 'https://objectstorage.REGION.oraclecloud.com/n/NAMESPACE/b/BUCKET/o/');
Result Meaning
File is listed Credential and bucket work; check the exact object name and the read permission
Empty Wrong prefix, or the bucket is empty
ORA-20401 Credential is wrong
ORA-20404 or ORA-20403 Wrong region, namespace or bucket, or no permission

From a shell, confirm the namespace and the exact object name. Names are case-sensitive:

oci os ns get --query data --raw-output
oci os object list --bucket-name BUCKET --prefix daily/ --all \
  --query 'data[].{name:name,size:size}' --output table

Encode spaces and special characters in the URI, such as %20 for a space. In the URI, everything after /o/ is the object name, including any folder-like prefix.

Listing and reading are separate permissions. If LIST_OBJECTS works but COPY_DATA gets a 404 on an object that exists, the principal probably lacks object read.

Fix: credential errors

See which credentials this schema has:

SELECT credential_name, username, enabled, comments FROM user_credentials;

Auth token credential

For OCI Object Storage, password is an auth token, not the console password. For a user in a non-default identity domain, the username includes the domain.

BEGIN
  DBMS_CLOUD.CREATE_CREDENTIAL(
    credential_name => 'OBJ_STORE_CRED_V2',
    username        => 'DOMAIN_NAME/user@example.com',
    password        => 'AUTH_TOKEN');
END;
/

Create a new name, test it with LIST_OBJECTS, then switch jobs over. That avoids breaking loads that still use the old one. Run the statement from a client that doesn't save history, and don't keep the token in a script.

API key credential

BEGIN
  DBMS_CLOUD.CREATE_CREDENTIAL(
    credential_name => 'OBJ_STORE_KEY',
    user_ocid       => 'ocid1.user.oc1..xxxx',
    tenancy_ocid    => 'ocid1.tenancy.oc1..xxxx',
    private_key     => 'PRIVATE_KEY_TEXT',
    fingerprint     => 'aa:bb:cc:...');
END;
/

Keys protected by a passphrase aren't supported. The fingerprint must match the public key uploaded for that same user.

Resource principal (preferred)

This removes the stored secret. Create a dynamic group that matches the database's OCID:

resource.id = 'ocid1.autonomousdatabase.oc1.REGION.xxxx'

Add policies for that bucket:

Allow dynamic-group adb-loaders to read buckets in compartment data where target.bucket.name = 'BUCKET'
Allow dynamic-group adb-loaders to read objects in compartment data where target.bucket.name = 'BUCKET'

If the dynamic group is in a non-default identity domain, write it as 'DomainName'/'adb-loaders'.

Then, as ADMIN:

EXEC DBMS_CLOUD_ADMIN.ENABLE_RESOURCE_PRINCIPAL();
EXEC DBMS_CLOUD_ADMIN.ENABLE_RESOURCE_PRINCIPAL(username => 'LOADER');

SELECT owner, credential_name
FROM   dba_credentials
WHERE  credential_name = 'OCI$RESOURCE_PRINCIPAL';

Use 'OCI$RESOURCE_PRINCIPAL' as credential_name in the load. ORA-20031 means it is already enabled. Allow time for IAM changes to take effect before you retest.

Caution

Don't make the bucket public to get a load through. A public bucket exposes every object in it.

Fix: ORA-20003 reject limit reached

The default rejectlimit is 0, so one bad row fails the load. Read the log table before you raise it.

Error in the log Cause Format option or fix
ORA-01722 on the first row Header row loaded as data skipheaders = 1
Whole line lands in column 1 Wrong delimiter; the default is pipe delimiter = ,
ORA-01861, ORA-01843 or ORA-01830 Date doesn't match dateformat or timestampformat
ORA-12899 Value longer than the column Widen the column; check for multibyte text
Commas inside quoted text split the row Quote not set quote = "
Fields missing at end of row Short records ignoremissingcolumns = true
Garbled accents Wrong character set characterset, such as AL32UTF8
Stray \r in the last column Line endings Set recorddelimiter

A typical CSV load with explicit options, which also captures the operation ID:

SET SERVEROUTPUT ON
DECLARE
  l_op NUMBER;
BEGIN
  DBMS_CLOUD.COPY_DATA(
    table_name      => 'ORDERS_STG',
    credential_name => 'OCI$RESOURCE_PRINCIPAL',
    file_uri_list   => 'https://objectstorage.REGION.oraclecloud.com/n/NAMESPACE/b/BUCKET/o/daily/orders_*.csv',
    format          => json_object(
                         'type'         value 'csv',
                         'delimiter'    value ',',
                         'quote'        value '"',
                         'skipheaders'  value '1',
                         'dateformat'   value 'YYYY-MM-DD',
                         'rejectlimit'  value '0',
                         'logretention' value '14'),
    operation_id    => l_op);
  DBMS_OUTPUT.PUT_LINE('operation ' || l_op);
END;
/

CSV fields map to columns by position. If the file order differs from the table, pass field_list or correct the file.

Warning

truncatecol, conversionerrors => store_null and a high rejectlimit make a load succeed by changing or dropping data. Use them only on staging tables, and compare counts afterwards.

Compressed files

Gzip files need 'compression' value 'gzip' or 'auto'. ZIP archives aren't supported, so repack them as gzip.

Before you rerun

COPY_DATA adds rows; it doesn't replace them. Rerunning after a load that partly succeeded can create duplicates.

SELECT COUNT(*) FROM orders_stg;

Caution

TRUNCATE can't be rolled back. Truncate only staging tables, and confirm the schema and table name first.

Load into staging, check counts, then move rows to the final table with MERGE or INSERT:

TRUNCATE TABLE orders_stg;
-- rerun COPY_DATA, then
SELECT COUNT(*), MIN(order_date), MAX(order_date) FROM orders_stg;

Prevent it next time

  • Use the resource principal so there is no token to expire or leave with an employee.
  • Keep rejectlimit at 0 for scheduled loads, and alert on anything other than COMPLETED in user_load_operations:
SELECT id, table_name, status, start_time, logfile_table
FROM   user_load_operations
WHERE  type = 'COPY'
AND    status <> 'COMPLETED'
AND    start_time > SYSTIMESTAMP - INTERVAL '1' DAY;
  • Set delimiter, quote, date format and character set explicitly, so a change in defaults or session settings can't break the load.
  • Have the producer publish a row count, and compare it with rows_loaded.
  • Upload under a temporary name and rename when complete, so a wildcard never picks up a partial batch.