venerdì 13 dicembre 2013

Oracle Tip: Image Processing in Oracle 11g

There are many ways to store images in Oracle DB. The most common manner is to store images as binary content in BLOB columns.
Starting from version 11g, Oracle introduced Oracle Multimedia (previously known as Oracle interMedia), a feature for storing images, audio, video and other multimedia data.
Oracle Multimedia introduced ORDAudio, ORDDoc, ORDImage, ORDVideo, and SI_StillImage data types and method for:
  • extracting metadata and attributes from multimedia content
  • embedding metadata generated for other application into images
  • embedding multimedia data from Oracle Multimedia, Web servers, file systems, and other servers
  • editing and transforming images
In this post, I will focus on the transformations you can apply to image data.
We start creating a table for storing a TIFF image.

CREATE TABLE AVT_IMG
(
ID NUMBER,
TIFF_IMG ORDSYS.ORDImage
);
 
We also create a database directory to the path where we store the images to be loaded into the DB.

CREATE OR REPLACE DIRECTORY avt_img_dir as 'C:\Imagenes_Blog';
 
 

We instanciate an object ORDImage and we load the TIFF image in the table AVT_IMG.

-- ORDImage.init()
INSERT INTO AVT_IMG VALUES(1,ORDImage.init());
COMMIT;
-- Load the image
DECLARE
obj ORDSYS.ORDImage;
ctx RAW(64) := NULL;
BEGIN
-- The import() method also sets the object properties by reading the image blob.
select TIFF_IMG into obj
from AVT_IMG
where ID = 1 for update;

obj.setSource('FILE', 'AVT_IMG_DIR', 'flowers.tif');
obj.import(ctx);
update AVT_IMG set TIFF_IMG = obj where id = 1;
commit;
END;
/
 
Using ORDSYS.ORDImage methods, we can read image properties:

DECLARE
image ORDSYS.ORDImage;
compression_format VARCHAR2(4000);
img_height NUMBER;
img_width NUMBER;
content_size NUMBER;
metav XMLSequenceType;
properties_match BOOLEAN;
BEGIN
-- Load the image into a variable
SELECT TIFF_IMG INTO image FROM AVT_IMG
WHERE ID=1;
-- Check if properties are readable
properties_match := image.checkProperties();
IF properties_match THEN
DBMS_OUTPUT.PUT_LINE('Check Properties succeeded');
ELSE
DBMS_OUTPUT.PUT_LINE('Check Properties failed');
END IF;
-- Read image properties
compression_format := image.getCompressionFormat();
img_height := image.getHeight();
img_width := image.getWidth();
content_size := image.getContentLength();
DBMS_OUTPUT.PUT_LINE('Compression Format: ' || compression_format);
DBMS_OUTPUT.PUT_LINE('Height: ' || img_height);
DBMS_OUTPUT.PUT_LINE('Width: ' || img_width);
DBMS_OUTPUT.PUT_LINE('Size: ' || content_size);
COMMIT;
END;
/
 
The result is:


and it matches with the image we are using as an example.



Let's alter the table as follows:
ALTER TABLE AVT_IMG ADD (JPEG_IMG ORDSYS.ORDImage, TIFF_BLOB BLOB, JPEG_BLOB BLOB);
for storing TIFF_IMG BLOB content (without metadata) and its copy in JPEG format.
The method getContent() extracts the image BLOB content.

UPDATE AVT_IMG
SET TIFF_BLOB =  ordsys.ordimage.getContent(TIFF_IMG);
COMMIT;
 
To change the image format, for instance from TIFF to JPEG, we can use the method processCopy().
DECLARE
imgTiff blob;
imgJpeg blob;
BEGIN
UPDATE AVT_IMG SET JPEG_BLOB = empty_blob()
RETURNING TIFF_BLOB, JPEG_BLOB
INTO imgTiff, imgJpeg;
-- processCopy() method gets the following parameters: 
-- * Source file
-- * Parameter string
-- * Destination file
ordsys.ordimage.processCopy(imgTiff, 'fileformat=jpeg', imgJpeg);
UPDATE AVT_IMG SET JPEG_BLOB = imgJpeg;
COMMIT;
END;
/
 
 

We can convert between the following formats: BMPF, CALS, GIFF, JFIF, PBMF, PGMF, PICT, PNGF, PNMF, PPMF, RASF, RPIX, TGAF, TIFF, WBMP.

If we want to create an ORDImage object from the JPEG_IMG BLO, this is the code:

UPDATE AVT_IMG
SET JPEG_IMG = ordsys.ordimage(
ordsys.ordsource(
JPEG_BLOB, null, null, null, sysdate, 1 ),
null, null, null, null, null, null, null );
  
The methods process() (that overwrites the source file) and processCopy() can perform more complex operations, as adjusting image contrast, scale or rotating the image. The following code performs a 90 degrees rotation.

DECLARE
imgTiff blob;
imgJpeg blob;
BEGIN
UPDATE AVT_IMG  set JPEG_BLOB=JPEG_BLOB
RETURNING  JPEG_BLOB
INTO  imgJpeg;
ordsys.ordimage.process(imgJpeg, 'rotate=90');
UPDATE AVT_IMG SET JPEG_BLOB = imgJpeg;
COMMIT;
END;
 
 
This is just a short demo of what Oracle Multimedia can do. For more info, see http://www.oracle.com/pls/db112/portal.portal_db?selected=7&frame=#oracle_multimedia.

martedì 3 dicembre 2013

Oracle Tip: OBI .rpd File path

The customer is thinking of migrating to OBIEE 11g on Exalytics. I need to migrate the .rpd file but the current installation has undergone some crazy update so it is impossible to connect and see the .rpd online in the OBIEE Client. 
The only way I had to recover the latest version of the .rpd file was locating it in the OBIEE Installation. 
The path for accessing to the current .rpd file (and previous versions of it) is: 

<OBI Root>/Middleware/instances/instance1/bifoundation/OracleBIServerComponent/coreapplication_obis1/repository

mercoledì 27 novembre 2013

Oracle Tip: BI Publisher Report URL without Login

My current customer wants to integrate BI Publisher reports in its web portal. They want to publish URLs that allow users to view reports, skipping the login page.
We can retrieve the Report URL by selecting any of Share Report Link options.

 Copy the URL and add the parameters id and passwd for logging into BI Publisher.

http://<server>:<port>/xmlpserver/Components/<Report_Name>.xdo?id=<user_id>&passwd=<user_password>&_xpf=&_xpt=0&_xdo=<Path to the Report>.xdo&_xmode=4&_params<parameters_if_any>&_xt=<Layout_Name>&_xf=analyze&_xana=view

The main disadvantage of this method is that user credentials are not encrypted. This is not the safest method on earth, but it works and it made my customer happy.

giovedì 14 novembre 2013

Oracle Tip: Oracle Warehouse Builder (OWB) import table error

I have installed the latest version of Oracle Warehouse Builder 11g 64 bit on a Windows pc (my work pc, actually) since I needed to connect to a customer OWB ETL implementation. 
Everything looked ok (I could connect to the OWB Workspace, navigate through the project, open and deploy mappings, etc.), since I have tried to import new tables in the Oracle Schema. 
As soon as I clicked on Import Database Object, I got the following (and cryptic) error:

SQL Exception 
Persistent Layer Error: SQL Exception
Class name: CacheMediator
Method Name: getSQLResult
Error Message from Persisten Layer: ORA-02085
....
If I clicked on OK, the next step was a grey window with much more known error Java null pointer exception.
I really needed to import the new tables I had created to be able to work, so I started Googling the error, with no success. After a considerable amount of time I got on this note:
https://blogs.oracle.com/warehousebuilder/entry/advanced_properties_of_location_new_for_11gr2

"Note the property "User Global Name", it specifies the unique name of the database, which is composed of the database name and the domain, in the form of database_name.database_domain. If you see the error ORA-02085: database link *** connects to *** during the import of metadata of database objects into OWB. It may mean the database has the system parameter global_names set to true, but you did not select the option "Use Global Name" of the Oracle location, as a result, the generated database link name for the import doesn't include the global database name and hence cannot access the database."

Basically I needed to specify the DB global name in each location that specified a connection to the DB. 
If you do not know the global name of your DB, this SQL query can give you a precious hand. 

SELECT * FROM global_name;

So unregister your location, specify the DB global name option and register the location again.

lunedì 4 novembre 2013

Oracle Tip: Generating Documentation Reports with Oracle SQL Developer Data Modeler

This is another tip for the lazy programmer. When it comes to documentation, no developer would like to go back extracting the code for every single table in his model.
Oracle SQL Developer Data Modeler has a very useful tool for generating reports.


Selecting Reports from the File Menu, you can choose if you want it generated in:
  • RTF
  • PDF 
  • HTML 
format.
You can create a template (e.g. if you want to select only tables of your models) or selecting only some objects of your model.
When you execute the report, it will be stored in a local route.
This is how a PDF report looks like. Ready to be sent to the customer or do some nice cut&paste from it.



martedì 8 ottobre 2013

Oracle Tip: Changing ODI 11g Database IP address

Yesterday we had an issue with a customer. Overnight they had changed the IP address of the database where ODI is installed.
To make everything work again, we had to:
1) Change Master Repository IP address
On login, choose the Edit Connection Option and change JDBC connection to the Master Repository. Test it and then login to the Master Repository only.


2) Change Work Repository IP address 
This was the trickiest part of the job because the option for editing the Work Repository connection string is not that easy to find in ODI 11g.
When you locate the Work Repository and you click on it, it will appear all greyed out and it seems there is no way to edit it until you spot a small icon on the upper left side.

This will allow you to edit the JDBC URL.


3) Change any Oracle Database Connection in the Topology 
Remember to change any Oracle Database Connection that refers to the database for which the IP address has changed

4) Change Agent IP address
If any agent has been installed on the server that has undergone the IP change, change Agent host details.


giovedì 3 ottobre 2013

OBIEE Tip: Sort a column based on another column

I was struggling with ordering Months in my Calendar Dimension. I wanted to show month names in my graphs and prompts and I wanted them to appear in temporal order (e.g. Jan-Feb-...-Dec). I could not use the Sort option beause it would sort values in alphabetical order.
Since in my dimension I have an attribute with the month number, it would have been great using it for sorting month names. Luckily OBIEE lets you do so, by selecting the column you need to sort in the Logical Layer and applying the Sort Order based on another column.



giovedì 5 settembre 2013

Oracle Tip: Migrate OBIEE 11g Dashboards, Answers and Prompts

You can easily move OBIEE Server Presentation objects (Dashboards, Answers and Prompts) from one environment to another (ej. from Development to Production) using OBIEE Catalog Manager.
The Catalog Manager appears in the OBIEE Client Menu. When you open it, you have to open the catalog by clicking on File -> Open Catalog.


You can choose if you want to open the Catalog online or off-line. 


Once you have logged in, you can see Catalog objects in a Folder structure. Locate the folders you want to export and select Archive from the File Menu. 


You have to specify the name and the path for the exported file.


Once you have exported the file you need, you have to load it in the new Catalog.
Close the Catalog and open the Catalog you want to migrate your objects to. Locate the location you want to import your objects to and select Unarchive. You will be asked to select the import file and click ok to complete the migration.






martedì 30 luglio 2013

Oracle Tip: Oracle Warehouse Builder Workflow Installation

To my surprise, Oracle Workflows were not installed in my current Development  environment (OWB Tahoe Development Version 11.2.0.3 and Oracle Database 11.2). I found out when I tried to deploy a new workflow. I was asked to input connection  details and when I tested the connection, I got the following error:
 "The connection was succesful but failed to retrieve workflow version." 

After Googling it, I discovered you have to install the Oracle Workflow Server by executing the wfinstall.bat script. You can find it in <OWB_HOME>\wf\install.


The screenshot shows a Windows installation. You have to input the following parameters:

  • Workflow Account: OWF_MGR is the default user
  • Workflow Password: Choose a password for the Workflow Manager User
  • SYS Password: password for SYS user 
  • TNS Connect Descriptor: specify connection details in the format <host>:<port>:<SID>

and then click on Submit. You do not have to create the DB user previously, the process will create it automatically.
At the end of the process, you will receive an encouraging message "Workflow Configuration has completed successfully".


Now, you would probably try to deploy the workflow again. At least, this is what I did and I got this error:

 RPE-02260: Database User OWF_MGR must be a Control Center User. Please use the OWB Design Client against the Control Center repository to  grant the Control Center User role.

So you first need to register the OWF_MGR user as a Workspace user (in Oracle Warehouse Builder -> Administration -> Repository Assistant). Finally, you will be able to create and deploy your workflows.

giovedì 25 luglio 2013

Oracle Tip: OWB Workspace Installation Error

I am starting a new project and I need to use Oracle Warehouse Builder. I have been given a 64bit Windows machine. A 32 bit version of OWB had already been installed, but when I tried to run it I got the following error:




The application was unable to start correctly (0xc0000018). 
After asking Google and Oracle Forums for explainations, I realized I had to download and install  OWB 11 for Microsoft Windows 64-bit (http://www.oracle.com/technetwork/es/developer-tools/warehouse/downloads/index.html).
I have downloaded it and I installed it. I needed to create a new Workspace, but after a few steps, I got the error:


The Warehouse Builder workspace owner installation failed on user OWBSYS. ORA-29532: Java call terminated by uncaught Java exception: java.sql.SQLException: OWBSYS is not granted access to <OWB_HOME>\repos.properties: Please run UnifiedRepos/reset_owbcc_home.sql

What is that? I have discovered that since the new installation was forced to be on a different PATH from the original, the OWBSYS user did not have access to the .properties file and installation could not go further.
So, I did what suggestes. I have located the set_owbcc_home.sql script and I run it as SYSTEM.

This is the script output:



SQL> @reset_owbcc_home.sql
Enter the full path of the Oracle home for the OWB Control Center install.
If you are installing in a Windows environment, please ensure that the case of t
he path exactly matches the Oracle install path including the drive letter.

OWB Control Center Home:
D:\product\11.2.0\dbhome_2

PL/SQL procedure successfully completed.


PL/SQL procedure successfully completed.

The script asked me for the Oracle Warehouse Builder path, as shown.

I then retried the Workspace creation and it worked fine.

lunedì 15 luglio 2013

Oracle Tip: ORA-30657 External Table Error

I was trying to load a CSV file into an external table. I copied the definition of the table from the final target table, adding the external table parameters: 

CREATE TABLE T1 
(field1 VARCHAR2(25) NOT NULL, 
field2 VARCHAR2(80) NOT NULL,
...
fieldn NUMBER)
ORGANIZATION EXTERNAL
(TYPE oracle_loader
DEFAULT DIRECTORY <oracle_directory_object_name>
ACCESS PARAMETERS (
RECORDS DELIMITED BY newline
BADFILE <file_name>
DISCARDFILE <file_name>
LOGFILE <file_name>
FIELDS TERMINATED BY '<terminator>'
LOCATION ('<file_name>'));

When I compiled the table, I got the following error. 



ORA-30657:  Operation not supported on external organized table  

Cause: User attempted on operation on an external table which is not supported.  

Action: Don't do that!



Quite hilarious... but what did I do wrong? The Oracle error message did not help me at all (and who could ever help?). I checked the directory. It was there and its name was typed correctly. File names were ok. So what was the issue? 

It was as easy as removing the NOT NULL clause on the field specification.  





CREATE TABLE T1 
(field1 VARCHAR2(25) NOT NULL, 
field2 VARCHAR2(80) NOT NULL,
...
fieldn NUMBER)
ORGANIZATION EXTERNAL
(TYPE oracle_loader
DEFAULT DIRECTORY <oracle_directory_object_name>
ACCESS PARAMETERS (
RECORDS DELIMITED BY newline
BADFILE <file_name>
DISCARDFILE <file_name>
LOGFILE <file_name>
FIELDS TERMINATED BY '<terminator>'
LOCATION ('<file_name>')


Silly error, but it took me a while to find out what was wrong. Hope this helps. 

venerdì 28 giugno 2013

Beauty Tip: Naked Skin de Urban Decay



Hace unos meses entré en el Sephora de Plaza Catalunya (unos de mis lugares favoritos aqui en Barcelona) en busca de una base de maquillaje que tuviera un tono rosado. Tengo la piel muy clara y solía utilizar bases de MAC.
Quizás nunca conseguí encontrar mi tono, pero todas me dejaban un aspecto amarillento, a pesar de ser muy buenas.
Nada más entrar, me paró el encargado de Urban Decay que me hizo probar esta base.
Me enamoré en seguida (de la base, no del chico).
Tiene una textura muy liquida y la cobertura es ligera. Así que no lo usaría en el caso en que quisiera cubrir muchas imperfecciones.
Lo que más me gustó es el acabado. El efecto es muy natural. Parece que ni te has maquillado, pero sin embargo dura todo el día y la piel no coge nada de brillo con el paso de las horas.
Está disponible en muchísimas tonalidades, así que cada uno puede encontrar la suya (http://www.urbandecay.com/naked-skin-liquid-makeup-from-urban-decay/334,default,pd.html).
Al ser muy liquida, puede resultar incomoda al aplicar, pero el efecto final compensa la pequeña dificultad.
El único defecto que le puedo encontrar es el aplicador. Cuando se me estaba terminando, resultaba difícil hacer que el producto saliera.
Dentro de un par de meses me voy a EEUU (donde Urban Decay es más barato que en España) y esta base está en primera posición en mi lista de compras.

martedì 25 giugno 2013

Tip: Generating Documentation in ODI

The most annoying part of my job is generating documentation. I hate when you finish a project and you have to go through all your code and interfaces to describe what they do. This is mainly for two reasons. First, I am not so well organized that I write down every little change when I apply it. Mea culpa. Second, because most of the time I am in a hurry and the most important thing is showing results instead of documenting what you are doing.
When you develop a considerable amount of interfaces, involving a considerable number of tables, columns and transformations, the last thing you want to do is re-open them to describe their behaviour.
Luckily, ODI provides a feature for generating PFD documents of your job. To use this functionality, you first have to configure it.
In ODI->User Parameters, you have to edit the following entries:
  •  Default PDF generation directory: this is the complete path to the folder you want to save your documentation to. E.g. C:\TEMP\
  • PDF Viewer: Full path to your PDF viewer. E.g. C:\Program Files (x86)\Adobe\Reader 10.0\Reader\AcroRd32.exe

ODI allows you to generate documentation for the following objects:
  • Knowledge Modules: right click on a project, then Print -> Print Knowledge Modules
  • Packages: right click on a project folder, then Print-> Print Packages
  • Procedures: right click on a project folder, then Print -> Procedure
  • Interfaces: right click on a project folder, then Print -> Interfaces
  • Folders: right click on a project folder, then Print ->Folder

The result is a PDF file with detailed information of the object you printed. The most complete option is the one for printing folders, because you can generate documentation of every object in it.
The thing I like the most is the fact that for every interface you get the physical structure of every source and target table, every join and, most important, each transformation you apply to get a target column.



martedì 21 maggio 2013

ORA-02292: integrity constraint (.) violated - child record

I was writing an ODI procedure from creating a static dimension from scratch. The procedure looked like this:

begin
DELETE FROM <DIM_TABLE>;
INSERT INTO <DIM_TABLE> VALUES (0,1,etc.);

COMMIT;
end


When I run it, I got the following error:

ORA-02292: integrity constraint (<OWNER>.<FK_CONSTRAINT>) violated - child record

The error means that I was trying to delete values that were used in a column that had a foreign key constraint on it.
To overcome this issue, without deleting any value in the referencing table, you first have to disable the constraint and then enable it again once you have finished populating the table.
So the procedure will look like this:


begin
execute immediate 'ALTER TABLE <DIM_TABLE> DISABLE CONSTRAINT <OWNER>.<FK_CONSTRAINT>';
DELETE FROM <DIM_TABLE>;
INSERT INTO <DIM_TABLE> VALUES (0,1,etc.);
COMMIT; 

execute immediate 'ALTER TABLE <DIM_TABLE> ENABLE CONSTRAINT <OWNER>.<FK_CONSTRAINT>';
end

lunedì 6 maggio 2013

Tip: How to specify Service Name in JDBC Connection

I needed to specify a new Oracle Database Connection in ODI. I have always used SIDs to configure JDBC connections.

jdbc:oracle:thin:@<hostname>:<port>:SID

Changing the SID for Service Name requires a minor syntax change. You have to replace the semicolon with a slash:


jdbc:oracle:thin:@<hostname>:<port>/<Service Name>

lunedì 22 aprile 2013

Tip: Oracle Data Modeler How to display just object names in a diagram

You may need to put your logical or physical diagram in a PowerPoint presentation, but it is quite unpractical showing all columns and details of a table. If you just want to show the Object Name, you have to go to View -> Details -> Only Names.


Then, you can give a better look to your diagram by customizing the look and feel and the best thing is that you can always go back to the full view.

martedì 2 aprile 2013

Tip: Solve ORA-14402

Recently I have partitioned a fact table and today I had to perform the weekly load.
I got into the error:

ORA-14402: updating partition key column would cause a partition change


This error was being raised every time I tried to update the partition field (a date) in a record. To overcome this issue just execute the following:


ALTER TABLE <my_table> ENABLE ROW MOVEMENT;

Tip: Scheduling OWB jobs using SQLPlus

Scheduling jobs in OWB 11g using the Calendar feature is possible only if you have bought the Data Integrator Enterprise Edition, which is not the case of the project I am currently working on.

Error you get when you try to create a new Calendar Module in OWB 11g without Data Integrator EE license

You can still schedule jobs by using a SQLPlus script which can then be called in a .bat or Shell script and scheduled using Windows Scheduler or Crontab in Unix.
In OWB 11g, we can find a SQL script ready to use in [OWBHOME]\owb\rtp\sql. The script you need is called: sqlplus_exec_template.sql
The script can be executed only by a Workspace Owner or a Workspace user with Execute privileges.
The script uses the following parameters:
  • WORKSPACE 
  • Workspace in which the job is to run: e.g. MY_WORKSPACE Make sure you specify the right Workspace Name. You can check it by executing:  

    SELECT * FROM ALL_IV_WORKSPACES
  • LOCATION_NAME 
  • Physical Name of the Location to which this task was deployed: e.g. MY_WAREHOUSE  
  • TASK_TYPE   
    • PLSQLMAP - OWB PL/SQL Mapping
    • SQLLOADERCONTROLFILE - OWB SQL*Loader Mapping
    • PROCESSFLOW - OWB ProcessFlow
    • ABAPFILE - OWB SAP Mapping
    • DATAAUDITOR - OWB DataAuditor Mapping
    • SCHEDULEDJOB - OWB Scheduled Job
    • CTMAPPING  - OWB Template Mapping
  • TASK_NAME
  • Physical Name of the Deployed Object.e.g. MY_MAPPING. Make sure you specify the TASK_NAME in the following format: [PARENT_TASK]/TASK_NAME
  • SYSTEM_PARAMS { , | (name = value [, name = value]...)}
  • CUSTOM_PARAMS { , | (name = value [, name = value]...)}
The following example shows how to call the DIM_ALL workflow under DIM_FACT workflow package deployed in WFS_LOCATION location in MYWKS workspace.

SQL> @sqlplus_exec_template.sql MYWKS WFS_LOCATION PROCESSFLOW "DIM_FACT
/DIM_ALL" "," ","


The script calls functions from the OWBSYS.wb_rt_script_util package so you may need to grant the right privilege to the OWB User.

    mercoledì 20 marzo 2013

    Tip: DATE and DATETIME in OBIEE

    I must admit that I am new to the OBIEE world and I really wish I can help people that are starting with this Oracle product to save some precious time when dealing with Calendar dimensions.
    I have created a Calendar dimension in my database with a field "DIA" to be DATE. This dimension is meant to replace one that was already in place, same content, but more fields. I have imported the table in the physical layer, mapped it to the logical layer, but when I run the dashboard I kept on seeing date fields with DD/MM/YYYY hh:mm in the calendar prompts.
    I spent quite a lot of time (call me dumb!) to find out that the answer was as simple as replacing the DATETIME field with DATE.


    venerdì 15 marzo 2013

    Tip: Reverse Engineering in Oracle Data Modeler

    I am currently building a Data Warehouse using OWB as integration tool. I have almost finished and now comes what I like the less about my job... documentation!
    During the development process, you usually create a number of staging tables. Oracle Data Modeler allows you to import tables from a schema. This way it is much easier writing down your documentation and you also have a visual presentation ready to use.
    Let's go through the reverse engineering process:
    1) Go to File -> Import -> Data Dictionary


    2) Add a new connection if you haven't set up any yet

    3) Select your Schema/Database


    
    Personally I find the filter option pretty useful for retrieving quickly the Schema you are looking for.

    4) Select the objects you want to import


    5) Click on Finish

    If everything goes ok, you have your Model imported in Oracle Data Modeler and you can export images of your diagrams or generate your DDL code to attach to your documentation.  



    lunedì 4 marzo 2013

    Oracle Tip: Find locked objects in Oracle Database

    Tipically I end up locking objects by executing an Oracle Warehouse Builder (OWB) mapping and then stopping it because I realize I have forgotten a join condition. If you abruptly kill the session, the object may stay locked until the rollback is completed or endlessy if the session is killed before any action against the target table is taken.
    In order to find out which object has been locked (and beg your DBA to kill the associated session or free the locks), run the following query:

     SELECT c.owner, c.object_name, c.object_type, b.SID, b.serial#,
                     b.status, b.osuser, b.machine
     FROM v$locked_object a, v$session b, dba_objects c
     WHERE b.SID = a.session_id AND a.object_id = c.object_id;

    The output will look like this:


    In case you are the DBA (and you have DBA privileges), then get the SID and the SERIAL# and run the following:


     alter system kill session 'SID,SERIAL#';

    mercoledì 27 febbraio 2013

    Tip: Reset Oracle Sequence

    Yesterday I was working on an ODI interface, a pretty easy one, which was supposed to insert new rows  into a table using a <SEQUENCE>.NEXTVAL for populating the primary key.
    The primary key was set NUMBER(4). The last value inserted had 17 as primary key. I was expecting new items to start from 18, but I was constantly getting: 


    SQL Error: ORA-12899: value too large for column

    After spending  a considerable amount of time for finding out which column was making my ODI interface fail, I have executed the following: 

    SELECT MY_SEQ.NEXTVAL
    FROM DUAL; 

    which returned me: 124586!!!
    Something has obviously gone wrong with that sequence and I needed to restore it to 17. So basically I have executed the following: 

    ALTER SEQUENCE MY_SEQ INCREMENT BY -(124586-17)

    and then execute: 

    SELECT MY_SEQ.NEXTVAL
    FROM DUAL; 

    to restore MY_SEQ.CURRVAL to 17
    Then you reset the correct increment by executing
      
     ALTER SEQUENCE MY_SEQ INCREMENT BY 1