Improving the way of handling CLOB_Column in DBMS.SUBSTR

I've recently been tasked with developing a backend application using Node.js, TypeScript, and an Oracle SQL server. Within this application, there is a database table named TableA which consists of columns: ID (NUMBER) & App_Log_File (CLOB).

The App_Log_File column stores entire log files based on the database structure or business logic. Upon investigation, I discovered that some rows contain large text files ranging from 3-4.5MB in size, consisting of approximately 40,000-60,000 lines.

Since the data type of the App_Log_File column is CLOB, I had to use the function

DBMS_LOB.substr(clob_colm_name, maxCharacterLength, startIndex)
to retrieve the column data. However, Oracle SQL Server only allows fetching 4000 characters from CLOB Data.

To overcome this limitation, I came up with a dynamic SQL schema solution:

interface LogFileReqModel {
    rowId: number,
    logfilelength: number
}

function getLogFilesSchema(query: LogFileReqModel): string {
    const maxCharacterLength: number = 4000;
    const loopLength: number = Number(((query.logfilelength||0)/maxCharacterLength).toFixed(0));

    let fetchLogQuery: string = ''
    for(let i=0; i<(loopLength + 1); i++) {
        fetchLogQuery += (fetchLogQuery ? ',\n' : '') + `\t\tDBMS_LOB.substr(App_Log_File, ${maxCharacterLength}, ${maxCharacterLength*i + 1}) AS log_file_${i}`;
    }

    let sqlSchema: string = `
        SELECT 
        -- ID,
        ${query.logfilelength > 0 ? fetchLogQuery : `'' AS log_file_0`}
        FROM TableA
        WHERE ID = ${query.rowId}`;

    return sqlSchema;
}

const logFileSqlSchema: string = getLogFilesSchema({ rowId: 12, logfilelength: 3589833 });
console.log('sqlSchema: ', logFileSqlSchema);

This approach dynamically generates query columns based on the length of the log file, ensuring efficient retrieval:

SELECT 
    DBMS_LOB.substr(App_Log_File, 4000, 1) AS log_file_0,
    DBMS_LOB.substr(App_Log_File, 4000, 4001) AS log_file_1,
    DBMS_LOB.substr(App_Log_File, 4000, 8001) AS log_file_2,
    ... [truncated for brevity] ...
    DBMS_LOB.substr(App_Log_File, 4000, 3588001) AS log_file_897
FROM TableA
WHERE ID = 12

If you have any suggestions for improving the SQL schema or alternative approaches, please feel free to share your SQL query recommendations for enhancement.

Typescript Demo Query
Is there another way to optimize the SQL schema? If so, please provide any SQL query recommendations for improvement.

Answer №1

  1. Avoid adding variables directly into your query using string concatenation or template strings. Instead, utilize a bind variable.
  2. When retrieving the contents of a CLOB column, simply read the entire CLOB column without breaking it into smaller VARCHAR2-sized chunks.

To simplify your code, you can use the following:

const logFileSqlSchema: string = "SELECT App_Log_File FROM TableA WHERE ID = ?";
console.log('sqlSchema: ', logFileSqlSchema);

When executing the query, bind your id value to the anonymous bind variable ?, and then stream the CLOB data when accessing the result-set.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to retrieve a union type of keys from a nested object in TypeScript

My attempt to extract types of keys from nested objects led me to try the following approach. Check out TS Playground type RecursiveRecord = { [key in string]: string | RecursiveRecord; }; type Keys<T extends RecursiveRecord, K = keyof T> = K ext ...

Generating statically typed events in Vue

Recently, I encountered a run-time error in a Vue / Typescript application due to the lack of typing for custom events. For example, the following code compiles without any issues but fails at run-time: // Within component A public foo() { this.$e ...

Comparing ngModules and index.tsIn the world of Angular development

Recently, I came across angular seed and noticed that they include both index.ts and modules. It got me thinking about why they use both when they can achieve the same goal of exporting TypeScript types. ...

Removing data from two connected tables

I have two tables named NOTIF and PJ_GEN with the following structure: TABLE NOTIF ========== ID_NOTIF COD_ONE LIB DATE TABLE PJ_GEN ========== ID_PJ COD_TWO LIB_TWO There is a many-to-many association defined by the table below: PJ_BY_NOTIF ========== ...

Encountering a type mismatch error in Typescript while working with Redux state in a store file

It appears that I have correctly identified all the types, but could there be a different type of Reducer missing? 'IinitialAssetsState' is not assignable to type 'Reducer' The complete error message: Type '(state: { assets: n ...

Why is it that the component passed in props fails to function properly when invoked as a function? React is signaling a shift in the order of Hooks being called

Here is a simple example I've prepared to illustrate how I am passing a component and then calling it like a function, as well as another example where it works just by calling it normally. You can switch between the working and not working examples b ...

Tips for changing the color of an icon when clicking a button

How can I dynamically change the color of an icon when clicked? Would using ngClass be the most efficient approach for this task? Currently, I have assigned a class to my icon. <ion-card> <ion-row> <ion-col> < ...

Easily Convert Square Bracket Notation to Dot Notation in JavaScript/Typescript for Quick Replacement

Currently, I am reviewing some code that includes unnecessary square bracket notations. To improve code comprehension, my aim is to transform instances like abc[3]['prop']["subprop"] into abc[3].prop.subprop. I have been able to achiev ...

What is the quickest way to send a message with just one press of the Enter key

Whenever I press "Enter Keyword," the message should be sent instead of going to the next line. ...

Entering information into fluctuating object fields

Suppose I have a dynamic object with a union type: data: {[key in 'num' | 'str' | 'obj']: number | string | object}; I set the object properties as follows: data.num = 1; data.str = 'text'; data.obj = {}; E ...

What is the reason for allowing var to declare duplicates, while const and let restrict duplicate declarations?

What is the reason behind var allowing duplicate declaration while const and let do not? var allows for duplicate declarations: xx=1; xx=2; console.log(xx+xx);//4 var xx=1; var xx=2; console.log(xx+xx);//4 However, let and const do not allow for dupl ...

Using TypeScript to utilize an enum that has been declared in a separate file

Imagine I have defined an enum in one file (test1.ts): export enum Colors{ red=1, blue=2, green=3 } Then in another file (test2.ts), I am creating a class with a method. One of the parameters for that method is a Color from the Colors enum: ...

Dynamic routing with ngIf in Angular 2's router system

Is there a way to use *ngIf with dynamic router in Angular? Let's say I have a top navigation component with a back button, and I only want the back button to be visible on the route 'item/:id'. I tried using *ngIf="router.url == '/ite ...

Steps for transforming a CASE Statement into a Custom Function in T-SQL

In my T-SQL query running on SQL Server 2014, I have implemented a CASE statement to handle different conditions. (CASE WHEN c.[Market FINAL] = 'Overbooking' AND c.[Booking type] = 'GRP' THEN 'Overbooking' ...

Is it possible to implement a customized pathway for the functions within an Azure function app?

Recently, I set up a new function app on Azure using Azure Functions Core Tools with Typescript as the language. The app includes a test function named MyTestFunction that responds with an HTTP response when called. This particular function is located in ...

I am experiencing an issue with my service provider when it comes to displaying multiple navigator stacks

Currently, I am developing a provider to manage the user's state across different views. The primary function of this provider is to display either one stack navigator or another based on whether a certain variable is filled or empty. This setup allow ...

"Encountering an Insertion Error with Database in Asp.net Using C

I am currently working on an ASP.NET application that captures input from text boxes on multiple pages. On the final page, I utilize insertion methods through adapters. Interestingly, when I input dummy values like "hjihi" into the text boxes, I do not enc ...

What is the best way to showcase the information retrieved from my API?

I am attempting to display the ID and Document number that are retrieved from an array. Data Returned However, I am not seeing any results in return. You can view the application results here. I have tried using string interpolation like {{document.id}} ...

Summary of data with various GROUP BY operations

Imagine having a table named census containing the following data: COUNTRY PROVINCE CITY POPULATION ============================================== USA California Sacramento 1234 USA California SanFran 4321 USA ...

Retrieving information from multiple tables in a MySQL query

I have a database with 3 tables structured as follows: store_locations id store_id zip_code city state last_updated -------------------------------------------------------------------------------- 1 7438 ...