Monday, March 28, 2011

Amazon S3 API for PL/SQL

Amazon S3 is part of Amazon's Web Service offering and the name is an abbreviation for Simple Storage Service:
"Amazon S3 provides a simple web services interface that can be used to store and retrieve any amount of data, at any time, from anywhere on the web. It gives any developer access to the same highly scalable, reliable, secure, fast, inexpensive infrastructure that Amazon uses to run its own global network of web sites. The service aims to maximize benefits of scale and to pass those benefits on to developers."
A few months ago, Jason Straub published an Oracle whitepaper on how to integrate Oracle Application Express (Apex) with Amazon S3.

As Jason points out, Amazon has a Free Usage Tier which allows you to get started using Amazon S3 for free. If you have ever bought a book from Amazon, they already have your credit card on file, so signing up for Amazon Web Services is quick and easy (and they won't start charging your credit card until the free trial period is over).

Introducing the S3 API for PL/SQL

Inspired by Jason's whitepaper, I decided to write a stand-alone PL/SQL API for Amazon S3. This API can be used in any PL/SQL solution, with or without Apex.

The API supports all common S3 operations, including

  • Authentication
  • Creating new buckets
  • Listing existing buckets
  • Listing existing objects (with or without filtering)
  • Creating (uploading) new objects (and setting an Access Control List - ACL)
  • Generating download links (with or without expiry dates)
  • Downloading objects
  • Deleting objects

See the examples below for more details.

Use Cases

So what can you do with Amazon's S3 service in combination with a PL/SQL API?

I can think of several interesting use cases, some of which I might explore further in future posts:

  • Backing up your database (use DBMS_DATAPUMP to dump a file to disk, then compress it using ZIP_UTIL_PKG, then encrypt it using CRYPTO_UTIL_PKG, and upload it to S3)
  • Backing up your PL/SQL source code (use data dictionary views or DBMS_METADATA to extract the source code, optionally zip and/or encrypt it, and upload to S3)
  • Backing up your Apex applications (use WWV_FLOW_UTILITIES.EXPORT_APPLICATION_TO_CLOB to generate export file, optionally zip and/or encrypt it, and upload to S3)
  • Cloud storage for file uploads (instead of storing [large] files inside your database, store them in the cloud and download them on demand -- especially relevant for Oracle XE which has a file size limit)
  • Serve static content (generate static [text, CSV, HTML, PDF] files from the database and upload to S3)
  • Replication or shared storage (upload from one machine/database, download to another)
  • Data loading or message processing (set up to poll for new incoming files - uploaded by other S3 clients - and process them)

Remember that all these things can be scheduled to run in the database using DBMS_JOB or DBMS_SCHEDULER.

Where to get the Amazon S3 API for PL/SQL

You can download the API as part of the Alexandria Utility Library for PL/SQL.

Getting started

Download and compile the relevant PL/SQL API packages. Then register with Amazon for an S3 account and get your AWS keys (key and secret key), and login to the AWS Management Console to get familiar with the basic operations.

If you are unfamiliar with Amazon S3, I recommend that you read this short getting started guide that describes the common operations.

In the following examples we shall see how you can do the same operations using PL/SQL.


From your Amazon account control panel, you'll get the key strings you need to use the Amazon web services.

Before you call any of the following API methods, you must initialize the authentication package. You only have to do this once per database session (but remember, on the web, every page view is a separate database session, so in Apex you'll need to run this code for every page, typically as a Before Header page process).

Creating new buckets

Buckets are what you use to organize your objects (files) in Amazon S3. Think of them as top-level folders, but note that you cannot create more than 100 buckets in a single account, and the bucket name must be unique across all user accounts on Amazon S3. So creating buckets is not really something you'd do very often, and usually it will be done manually (to resolve any name conflicts with existing buckets).

A bucket is associated with a specific region where your objects will be stored. For reasons of latency/speed and possibly legal issues, it makes sense to select a region that's close to you and your users (although you may actually want to locate it far away if the purpose is backup for a major disaster in your own area).

Here's how to create a new bucket via PL/SQL code:

Checking the AWS management console to verify that the bucket has indeed been created (in the specified region):

Listing existing buckets

With one or more buckets created in your account, you can list the bucket names.

There are two way to do this, either by retrieving an index-by PL/SQL table using the GET_BUCKET_LIST function:

or, alternatively, via SQL using a pipelined function named GET_BUCKET_TAB:

Creating (uploading) new objects

An "object" is a file, and this is really what the S3 service is all about, storing files. So let's upload a file or two to our new bucket!

The API lets you upload any BLOB data to S3 using the NEW_OBJECT procedure.

When you upload a file to S3, the default Access Control List (ACL) makes sure that only the owner of the file (you!) can access (download) it.

Others get an "Access Denied" message (but see the "Generating download links" section for how to generate special time-limited download links):

There are a number of predefined ACLs that you can specify if, for example, you want to make the file publicly available.

Which can then be freely downloaded by anyone (the use of HTTPS is optional).

A note about "folders": S3 has no concept of "folders", but you can simulate folders by using a forward slash in your file names (as seen in the previous example). Some S3 clients, such as the AWS management console, will present such files in a folder structure. As far as the PL/SQL API is concerned, the slash is simply part of the file name and has no special meaning.

Listing existing objects

Now that we have uploaded a couple of files, we can list the contents of the bucket via the GET_OBJECT_LIST function:

You can also get a list in SQL via a pipelined function named GET_OBJECT_TAB:

In both cases, you can optionally specify a prefix that acts as a search filter for the file names you want to return, and/or the maximum number of items you want to return.

Generating download links

You can access a file that has been protected by an ACL by including a special checksum parameter in the URL.

The GET_DOWNLOAD_URL function lets you generate the URL needed to access the file. You can specify when the link should expire, so this means you can share a download link that will stop working after a specified amount of time, which can obviously be useful in a number of scenarios.

Pasting the generated URL into the browser allows us to access the file:

Downloading objects

Downloading a file from S3 using PL/SQL is straightforward with a call to the GET_OBJECT function which returns a BLOB:

Deleting objects

Removing a file is likewise very simple, just call the DELETE_OBJECT procedure:


The ability to upload and download any file from the Oracle database to "the cloud" (and vice versa) via PL/SQL is extremely useful for a number of purposes.

Let me know if you find this API useful!


Dimitri Gielis said...

Very nice post and definitely useful.


Greg said...

Awesome, thanks for sharing.

HÃ¥vard Kristiansen said...

Very nice Morten! It will be put to good use, rest assured!


Learco Brizzi said...

Nice post!

Jason Straub said...

You have opened up a lot of possibilites with this API. Nice work!

Andy said...

Morten, you are the best. Thanks for doing this. I had designs on something similar, but would have never done it as well.

I am having one issue. I am able to list my buckets fine, but when I go to put a new object up there, I get;

ORA-20000: The request signature we calculated does not match the signature you provided. Check your key and signing method.
ORA-06512: at "PROD.AMAZON_AWS_S3_PKG", line 41
ORA-06512: at "PROD.AMAZON_AWS_S3_PKG", line 69
ORA-06512: at "PROD.AMAZON_AWS_S3_PKG", line 708
ORA-06512: at line 13

Same aws id/key, but this error. I suspect something to do with the timestamp, but am not clear why this would not fail for both calls (get_bucket_list and new_object). I can provide far more detail in email if needed. I suspect you may not have much time to answer, but I would appreciate a quick word on what possible issues might be.

Again, you rock! Thanks so much.


Morten Braten said...

@Andy: When you upload a file, the file name, content-type (and optionally ACL) are also part of the calculated signature. What are your values for those parameters?

Also, try putting a call to debug_pkg.debug_on (and remember to enable DBMS output) before you call the new_object procedure. That should give you the full error message (including details of the signature that Amazon expects).

- Morten

Andy said...

Hi Morten,

I double checked my parameters and realized I did have the wrong content-type which may have been part of the issue.

After solving that I was getting a whole new issue, HTTP client error 403 - Forbidden.

Tried playing with permissions of the buckets, but no luck.

Created a new bucket, set permissions, and voila, it worked.

Now in business. Thanks Again. Great stuff.


Fadi said...

extremely helpful, thanks alot for this work.


Anonymous said...

Hi. I tried to compile the package but it says that identifier T_STR_ARRAY must be declared. How should I declare this type?

Thank you,

Morten Braten said...

@Anonymous: The declaration of T_STR_ARRAY (and other types) are found in the /pub/setup/types.sql file in the Alexandria PL/SQL Library download (zip) file.

- Morten

fateh.cis said...

Thanks for sharing this Package.

I am getting this error when I try to create a bucket:


The error:
ORA-29273: HTTP request failed
ORA-06512: at "SYS.UTL_HTTP", line 1130
ORA-24247: network access denied by access control list (ACL)
ORA-06512: at "TEST.AMAZON_AWS_S3_PKG", line 177
ORA-06512: at "TEST.AMAZON_AWS_S3_PKG", line 457
ORA-06512: at line 3
29273. 00000 - "HTTP request failed"
*Cause: The UTL_HTTP package failed to execute the HTTP request.
*Action: Use get_detailed_sqlerrm to check the detailed error message.
Fix the error and retry the HTTP request.


Keeping in mind that this procedure is executed fine:

http_req utl_http.req;
http_resp utl_http.resp;
http_req := utl_http.begin_request('');
http_resp := utl_http.get_response(http_req);

Any help please ?


Morten Braten said...

@Fateh: The error message is pretty clear, "ORA-24247: network access denied by access control list (ACL)" means that you are on Oracle 11g and that you need to adjust the ACL, which by default blocks all network access. You should open for traffic to the Amazon AWS domain ("*") on port 80.

See, for example, this article for more info:

- Morten

fateh.cis said...

Thanks, It is working fine now... Sorry to keep pestering you.

But I got another error:
The difference between the request time and the current time is too large.

I understand that I have to sync my server clock with Amazon.

This is my amazon console link :

I am in Dubai-UAE

I tried to alter the session time:
alter session set time_zone='US/Arizona';

But got the same error.
The difference between the request time and the current time is too large.

Any help please ?



Morten Braten said...

@Fateh: The amazon_aws_auth_pkg.init() procedure has a parameter to set your offset from GMT time. Use this to set your current time zone, before you call any other AWS operation.

- Morten

Frank Hogenes said...

Great solution, thanks !

Is there a known issue when having > 999 files in a bucket ?
select *
from table(amazon_aws_s3_pkg.get_object_tab('my-bucket-name')) t
ends up in a infinite loop on Oracle and I have pinpointed this issue to the number of files.

Thanks, Frank

John Julian Sr said...


This is fabulous. But one quick question: Have you tried this on an Oracle on Amazon RDS database yet? I'd be curious as to your experiences with that platform. I don't see why it wouldn't work, except that RDS has restrictions on what libraries and accounts can be accessed.


John Julian

Theodoros Emmanuel said...


this is exactly what i was looking for and it's amazing!

I have set it up, and overcome quite a few initial problems and errors.

I can list by buckets, create a new bucket, but i cannot list the contents of a bucket.

When trying to retrieve the contents of a bucket
SELECT * FROM table (amazon_aws_s3_pkg.get_object_tab('my-new-bucket'));

i'm getting this error

(i've changed the RequestId and HostId just in case)

I would be much obliged if anyone could help me on this, since i've been pounding on it for two days.

Thank you.

Morten Braten said...

@John Julian Sr: I had a look in the documentation for Oracle on Amazon RDS (see and it says that "Network access utilities such as utl_http, utl_tcp, utl_smtp, and utl_mail, are not supported at this time.". So anything that uses webservices (like this package) won't work with RDS, unfortunately. Ironic, given that RDS and S3 are services provided by the same company!

- Morten

Morten Braten said...

@Teo: I can't see the actual error message you posted (perhaps it contained XML tags and was "eaten" by the Blogger software?). You might want to re-post with the error message in plain text.

- Morten

Theodoros Emmanuel said...


Hi Morten and thanks for the reply. I found that the problem was from the marker parameter that allows get_object_tab to return multiple times. I neglected it so it returns the full results an once and it's working.

I do have another question though, if you can help.

The key values that i want to use contain Greek characters. nls_language in oracle is set to
as our windows client machines have the following setting in registry for NLS_LANG

Are there any other settings for the aws s3 i could try to see if this works?

Thank you

Theodoros Emmanuel said...


Everything works fine, but i do have one last problem.

I have created a bucket that contains directories that use Greek characters. I can view these directories and their contents correctly from the amazon s3 web console.

Also if a issue from dos prompt the following
aws s3 ls s3://my-new-bucket

the contents are displayed correctly.

But when i do this from pl/sql using
SELECT * FROM table (amazon_aws_s3_pkg.get_object_tab('my-new-bucket'));

the returning key values have incorrect characters (gibberish).

I'm using oracle XE 10g and NLS_CHARACTERSET is set to AL32UTF8.


Anonymous said...

Dear Morten,
Thanks for your contributions.
It worked perfectly for a Bucket in US region. But I got the below error when I tried to upload files to a Bucket in Frankfurt.

ORA-20000: Please re-send this request to the specified temporary endpoint. Continue to use the original request endpoint for future requests.

* I searched the net, but to no avail

Morten Braten said...

@Anonymous: See this issue for more info about buckets in the Frankfurt AWS region:

- Morten

ILSabbe said...

Hi Morten, wow what a gr8 job!!

It is like superHero now that i need to migrate around 500000 blobs from Oracle cmsdk to S3 :)

I just want to know if it is possible to install ONLY the amazon_s3 related packages, and which of the others are needed....
i suppose the types sql script is mandatory ... and which other?

Thanks a lot, i will let you know how it goes :)

Morten Braten said...

@ILSabbe: Thanks, glad the package is useful to you.

To do a minimal install, first install the "core" packages and types:

Then install the Amazon (S3) packages:

- Morten

Karavan said...

Very useful library.
Thank you for your job! :)