Welcome!

You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

Beyond <CFQUERY> Part 2 of 2

Beyond <CFQUERY> Part 2 of 2

This month I hope to shed some light on Oracle's larger datatypes for those of you who like to do things big.

Let's go straight to the deep end with stored procedures. They're faster and more secure than standalone queries. In the first instance, procedures are faster because a lot of the execution process has already been completed before runtime, as I mentioned in my previous article(CFDJ, Vol. 4, issue 6) (In that article I covered some of the many ways you can use Oracle with the rather humble-looking <CFQUERY> tag.) The reason is that the validation process is done at compilation time, so when you invoke the procedure from your ColdFusion template, all it has to do is run.

Obviously, there are more generic benefits to using stored procedures, as they provide a degree of separation from your ColdFusion code, meaning that as long as the procedure call doesn't change, it's entirely possible to update the Oracle procedure incorporating database changes without having to alter your front-end ColdFusion application at all. Also, as I mentioned in my last article, using functions and procedures allows you to share the load across servers (provided you have separate servers for your ColdFusion and Oracle installations, as Macromedia recommends).

Procedures have the added benefit of hiding some of the complexity of database interaction. As is quite often the case, there's a mix of skills in any development team, and using procedures means that your strong Oracle developers can develop the database application, your ColdFusion developers can create the front end, and neither will have to have an in-depth knowledge of what the other is doing.

Some of you may recall a recent article by Ben Forta on <CFQUERYPARAM> ("Faster and Safer Database Queries," CFDJ, Vol. 4, issue 2) in which he highlighted the added security it provided through facilitating datatype checking. The same is true for calling stored procedures, which requires the use of <CFPROCPARAM> instead (see Listing 1). This also extends to the Oracle side of the application, where the procedure has to define the datatypes (see Listing 2). Combine this with proper exception handling and you have more secure database access. The two listings constitute an example of a simple Oracle procedure, showing parameter declaration basic exception handling.

The example procedure includes two types of calls to sequences (seq_category, seq_img_id). As you can see, they are simple to use and just as easy to create:

/* this is a simple sequence creation script*/
CREATE SEQUENCE seq_example increment by 1 start with 1;

And they ensure that all your primary keys are unique to boot. The only reason I mention this at all is that in the not too distant past I recall inheriting some code in which the developer had created a primary key by selecting the Max(id) from the table and then adding 1 to it. The main issue with this is that if someone else is running the same page at the same time, you're going to retrieve the same Max(id) and therefore, ultimately, try to insert a record with the same primary key.

How Much Can a CLOB Hold?
Recently I followed a thread on the Macromedia Forums discussing the use of CLOBS in Oracle-ColdFusion applications. The crux of the issue was that no one seemed to know how to fully utilize the 4GB of storage space Oracle says a CLOB can hold. As the thread progressed, it emerged that a number of people were unable to input data held in a CLOB that ex-ceeded 4,000 characters. Reading on, I saw a range of possible solutions using Oracle's dbms_lob package, but as ColdFusion cfstoredproc doesn't support CLOBs, it seemed this couldn't be the best solution. I decided to investigate the problem. Initial searches proved fruitless, so I ran a few experiments. True to form, I found I could successfully input 4,000 characters to a CLOB, but as soon as I tried to put in 4,001, I got this error:

Oracle Error Code = 1704

ORA-01704: string literal too long
Now my math isn't too hot, but that's a far cry from the 4GB Oracle had promised. So I looked still deeper and discovered a thread on a disparate forum located in one of the far corners of the Web where some helpful individual hinted that there were certain limitations with Oracle native drivers. With this is mind, I recalled a time when I dabbled in some light Delphi development that introduced me to ODBC drivers. Now it's widely accepted that ODBC drivers are slower than native drivers, but in the course of my experiment I discovered that this time lag might well be worth the wait. I got our DBA to install the Merant ODBC drivers and set up a datasource pointing to the database containing my CLOB table.

I then ran the following code, increasing the loop size to see what would happen: <cftry>

<cfset v_txt = "start">
<cfloop from="1" to="1000">
<cfset v_txt = v_txt & "0123456789">
</cfloop>
<cfset v_txt = v_txt & "end">

<cfquery name="clob_test" datasource="#request.ODBC_ds#">
INSERT INTO clob_test VALUES (seq_clob.nextval, '#v_txt#')
</cfquery>

<cfcatch type="DATABASE">
<cfoutput>#cfcatch.message#</cfoutput>
</cfcatch>
</cftry>
The result (as you'll find if you try it yourself) is way beyond the measly 4,000 characters facilitated by the native drivers. In fact, I consistently managed to increase this by four times - to just over 16,000 characters. Admittedly this is a long way short of the 4GB promised by Oracle, but in reality it's plenty to store dynamic content in.

The story doesn't end there, however. Late in my testing I stumbled across a new cf_sql_datatype that relates back to what I mentioned at the beginning of this article, where <CFQUERYPARAM> allows you to do datatype checking. Now I'm familiar with the normal array of varchar, number, and so on, but I'd never seen cf_sql_clob, so I tried this out by using the trusty <CFQUERYPARAM> tag in my insert statement and specifying the datatype as cf_sql_clob, making the insert look something like this:

<cfquery name="clob_test"
datasource="#attributes.ds#">
INSERT INTO clob_test
VALUES (seq_clob.nextval,
<cfqueryparam cfsql
type="CF_SQL_CLOB"
value="#v_txt#">)
</cfquery>
Using Oracle native drivers I got a number of errors. On 8.1.5 I got this one:

Oracle Error Code = 1461
ORA-01461: can bind a LONG value only for insert into a LONG column
And on 8.1.6:

Oracle Error Code = 936

ORA-00936: missing expression
Not good. However, Merant came to the rescue, and I now have no problem inserting into my CLOBs. I actually let it stand at a final figure of around 400,000 characters successfully inserted.

The Driver Makes the Difference
So there you have it. The trick is not in complex Oracle coding, but in selecting the right drivers. If you're really worried about the time lags associated with ODBC drivers, then use them only for your CLOB manipulation. The main thing is, you won't have to change your code at all, but be sure your datasource is configured properly in the ColdFusion Administrator, either by enabling Long text retrieval or setting the buffer to an adequate level.

Oracle also offers another LOB in the form of binary large objects (BLOBs). As the name suggests, these store the information in binary format. It's possible to store all manner of information in your database: images, word documents, test files, even PDFs - the list is nearly endless.

Don't get too excited, though. While Oracle does provide the handy dbms_lob package with which you can insert BLOBs, check their length, see if they're empty, and so on, it's annoying that you can retrieve them only in binary format. Now I don't know about your users, but I've found mine prefer that the Word document they stored in the database comes out of the database as a Word document. Unfortunately, when you simply select a BLOB from the database...well, it comes out in binary. So this is a bit of a problem, as I'm sure you can appreciate.

All is not lost, however. You can create your own CFX tag to apply the mime type to the binary and format it correctly. Unfortunately, this is beyond the scope of this article, as my Java knowledge is minimal and my C++ nonexistent, but I won't leave you high and dry. There are two solutions for those whose pockets are deeper than their Java knowledge. There's a CFX tag called BLOB manager, available from the Macromedia tag library. I've tried the online demo, which seems pretty slick. For the more Java-savvy or less well funded, try out the tutorial at www.planet-source-code.com/vb/scripts/ ShowCode.asp?txtCodeId=45&lngWId=9.

*  *  *

Well, that's all from me, folks, but remember: use sequences for your primary keys and stored procedures to hide complexity, and be wary when handling large objects.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


IoT & Smart Cities Stories
Whenever a new technology hits the high points of hype, everyone starts talking about it like it will solve all their business problems. Blockchain is one of those technologies. According to Gartner's latest report on the hype cycle of emerging technologies, blockchain has just passed the peak of their hype cycle curve. If you read the news articles about it, one would think it has taken over the technology world. No disruptive technology is without its challenges and potential impediments t...
Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
If a machine can invent, does this mean the end of the patent system as we know it? The patent system, both in the US and Europe, allows companies to protect their inventions and helps foster innovation. However, Artificial Intelligence (AI) could be set to disrupt the patent system as we know it. This talk will examine how AI may change the patent landscape in the years to come. Furthermore, ways in which companies can best protect their AI related inventions will be examined from both a US and...
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (November 12-13, 2018, New York City) today announced the outline and schedule of the track. "The track has been designed in experience/degree order," said Schmarzo. "So, that folks who attend the entire track can leave the conference with some of the skills necessary to get their work done when they get back to their offices. It actually ties back to some work that I'm doing at the University of San...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...