Category: nice to know

  • Calculating CPU usage in Oracle

    The performance of Oracle is determined by 4 factors: the CPU, internal memory, disk access and network performance. The latter, network performance, is only relevant if data are written or read from a network device. In scheme, it looks like:

    performance determining factors

    Let us look at the CPU. The most important data can be derived from this sql:

    select sql_text, 
    to_char(LAST_ACTIVE_TIME,'YYYY-MM-DD HH24:MI:SS') LAST_ACTIVE_TIME ,
    cpu_time/1000000 cpu_time,
    elapsed_time/1000000 elapsed_time,
    rows_processed
    from v$sqlarea
    where last_active_time > SYSDATE-0.001
    order by last_active_time desc
    ;

    This query uses a view v$sqlarea that contains most important CPU indicators.

    This query provides the time that is spent is cpu. It is provided in seconds. Likewise, the elapsed time is provided in seconds.

    The rows_processed field is an interesting one. It indicates the records that are sent to the user. If a summary is required, whereby the summary is given in one record, we see rows_processed = 1. If we have a setting in the client whereby only 50 records are returned, we see
    rows_processed = 50.

    If we fire 2 SQL statements with the same texts, we see that rows_processed, cpu_time are added across the two queries. This implies that a SQL summary will show rows_processed = 2 as two SQL statements are run, each summary providing one rows_processed.

    Additional information can be derived from another query that provides CPU per session:

    SELECT n.username, t.name, s.sid, s.value/1000 FROM
    v$sesstat s,
    v$statname t,
    v$session n
    WHERE
    s.statistic# = t.statistic# AND n.sid = s.sid
    AND t.name='CPU used by this session' ORDER BY s.value desc;

    This provides CPU used in milli seconds (hence the division by 1000) as split per user session. This then shows which user consumes most cpu. Very roughly, the results from this query should be aligned to the earlier query that provides cpu time per query.

    A final word. One may ask if the cpu is overloaded when running a query This can be checked by monitoring the temperature in the core. A nice programme is “Core Temp” that may warn you for overheated cores.

  • Backing up in Oracle via data pump

    Oracle has several possibilities to back up the data. One possibility is backing up via data pump. This facility can be used by the command line. Let us discuss three different commands to use the data pump facility.

    The commands use the expdp and impdp facility that are stored in the bin directory with Oracle Home. So you must have the possibility to access the Oracle server.

    The data that are backed up are stored in a file. It is possible to link the directory where such data are stored to a user (say C##oldSCOTT). This is done via:

    CREATE OR REPLACE DIRECTORY test_dir AS ‘D:\app\tmaanen\virtual\admin\orcl\dpdump’;
    GRANT READ, WRITE ON DIRECTORY test_dir TO c##oldscott;

    The first command is a command to backup several tables. It runs from the command line as:

    expdp c##oldscott/pswpsw@orcl tables=EMPLOYEES,DEPARTMENTS directory=TEST_DIR dumpfile=EMP_DEPT.dmp logfile=expdpEMP_DEPT.log

    One may restore these tables via:

    impdp c##oldscott/pswpsw@orcl tables=EMPLOYEES,DEPARTMENTS directory=TEST_DIR dumpfile=EMP_DEPT.dmp logfile=impdpEMP_DEPT.log

    This restore may also be applied on other databases, as long as a user c##oldscott is created.

    Second situation. Likewise, one may also backup and restore a whole scheme:

    expdp c##oldscott/pswpsw@orcl schemas=c##oldscott directory=TEST_DIR dumpfile=SCOTT.dmp logfile=expdpSCOTT.log
    impdp c##oldscott/pswpsw@orcl schemas=c##oldscott directory=TEST_DIR dumpfile=SCOTT.dmp logfile=impdpSCOTT.log

    Third situation. A complete backup and restore. This can be done with:

    expdp.exe FULL=Y DUMPFILE=exp.dmp USERID=SYSTEM/pswpsw
    impdp.exe FULL=Y DUMPFILE=exp.dmp USERID=SYSTEM/pswpsw REUSE_DATAFILES=Y TABLE_EXISTS_ACTION=REPLACE

    A final remark. Once I got this error:

    Hum hum – error

    This was solved after I realised that Oracle was running with a user account that had no write privs on the box. I changed the user that starts the oracle service with a user with more extended privs. That solved the issue. I got this solution from https://asktom.oracle.com/pls/apex/asktom.search?tag=unable-to-get-expdpimpdp-utility-run-successfully.

  • Oracle only listens to localhost

    It happens to me quite often. I install Oracle and it only listens to the localhost. In a few steps, one can get it to listen to the IP address instead of the localhost.

    What is the problem if Oracle only listens to the localhost? This implies that the instance cannot be accessed from outside. The Oracle server simply doesn’t listen to outside clients.

    The first step is to change the listener.ora (can be found in network\admin) where localhost is replaced by the IPaddress:

    LISTENER =
    (DESCRIPTION_LIST =
    (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.2.26)(PORT = 1521))
    (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
    )

    Similarly, we change the settings in tnsnames.ora. This will then look like:

    LISTENER_ORCL = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.2.26)(PORT = 1521))ORACLR_CONNECTION_DATA = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521)) ) (CONNECT_DATA = (SID = CLRExtProc) (PRESENTATION = RO) ) )

    ORCL = (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.2.26)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = orcl) ) )

    Restart the engine, and let us see if we on the server are able to access the instance on the Ip address. That works, both from the tnsping command and the enterprise manager app:

    tnsping and EM

    The server must then be given access through the firewall. This can be accomplished to provide access through the firewall for TNSLISTENER (can be found in ORAHOME\bin).

    access for TNSLISTENER.
  • Encryption in Oracle

    Oracle has a nice facility to store data in an encrypted form. This allows to hide data content from users while still allowing them to see the columns. If one would like to use the encryption facilities, one must be given this grant: GRANT EXECUTE  ON dbms_crypto TO username;

    The code to store data in an encrypted form is:

    CREATE OR REPLACE FUNCTION F_ENCRYPTION 
    (text IN VARCHAR2
    )
    RETURN VARCHAR2 AS
    encrypted_text VARCHAR2(255);
    raw_set RAW(100);
    raw_password RAW(100);
    encryption_result RAW(100);
    encryption_password VARCHAR2(100) := 'bunvegni';
    operation_mode NUMBER;
    BEGIN
    raw_set:=utl_i18n.string_to_raw(text,'AL32UTF8');
    raw_password := utl_i18n.string_to_raw(encryption_password,'AL32UTF8');
    operation_mode:=DBMS_CRYPTO.ENCRYPT_DES + DBMS_CRYPTO.PAD_ZERO + DBMS_CRYPTO.CHAIN_ECB;
    encryption_result:=DBMS_CRYPTO.ENCRYPT(raw_set,operation_mode,raw_password);
    encrypted_text := RAWTOHEX (encryption_result);
    RETURN encrypted_text;
    END F_ENCRYPTION;

    This can then be used to store data. As an example:

    create table Tom_Encrypt(naam_enc varchar2(255));

    followed by:

    insert into Tom_Encrypt(naam_enc) values(F_ENCRYPTION('Dikke Tom')); 
    insert into Tom_Encrypt(naam_enc) values(F_ENCRYPTION('Lieve Ine'));
    insert into Tom_Encrypt(naam_enc) values(F_ENCRYPTION('Paula 24 jan'));
    insert into Tom_Encrypt(naam_enc) values(F_ENCRYPTION('Stella'));
    commit;
    select * from Tom_Encrypt;

    The stored data can be seen, but the actual content remains unknown:

    unknown content

    With a special function, we are able to see the actual content. The function to decrypt is:

    CREATE OR REPLACE FUNCTION F_DECRYPTION 
    (encrypted_text IN VARCHAR2)
    RETURN VARCHAR2 AS
    decrypted_text varchar2(255);
    raw_set RAW(100);
    raw_password RAW(100);
    decryption_result RAW(100);
    decryption_password VARCHAR2(100) := 'bunvegni';
    operation_mode NUMBER;
    BEGIN
    raw_set:=HEXTORAW(encrypted_text);
    raw_password :=utl_i18n.string_to_raw(decryption_password,'AL32UTF8');
    operation_mode:=DBMS_CRYPTO.ENCRYPT_DES + DBMS_CRYPTO.PAD_ZERO + DBMS_CRYPTO.CHAIN_ECB;
    decryption_result:=DBMS_CRYPTO.DECRYPT(raw_set,operation_mode,raw_password);
    dbms_output.put_line(decryption_result);
    decrypted_text := utl_i18n.raw_to_char (decryption_result,'AL32UTF8');
    RETURN decrypted_text;
    END F_DECRYPTION;

    This then allows us to see the content. The SQL code is: select F_DECRYPTION(naam_enc) from Tom_encrypt;

    Being able to read data.

  • Masking in Oracle

    Oracle has recently introduced masking as one of the facilities. Masking allows data to be hidden from users / or only display part of the content. Other users can still the normal content. Let us take an example. A salary can shown as a random number to some users while others might still see the original content.

    A well known example is a credit card number. If I look at my Amazon account, I see that my credit card is shown as “Master Card ending in 6211”. The original content is masked: only part is shown. As the last numbers of my credit card is shown, I know Amazon has my correct credit card number. On the other hand such display is sure; if someone sees my screen, he has no knowledge of my credit card number.

    Masking is fundamentally different from encrypting. If my data are masked, my data are either not shown or just partly shown to some users. The data might still be stored in a plain form, leaving them exposed to whomever has access to them. Encrypted data are not exposed; even a dba can not read them if he doesn’t have the key to decrypt them. Some dba even do not want to have keys to, say, the encrypted passwords.

    If one would like to use this Oracle facility, you should has have the newest version of Oracle (12c) and the newest version of SQL developer (version 18 or above). 

    Next grants are necessary to implement masking:

    grant select on Sys.redaction_policies to C##SCOTT;
    grant select on Sys.redaction_columns to C##SCOTT;
    grant execute on dbms_redact to C##SCOTT;

    If we then log in as C##SCOTT, we can select a table in SQL developer. Right click on the table and choose the option “redaction”:

    setting masking rules

    The menu is rather straight forward. One must indicate the scheme, table, column and the masking type:

    filling out masking rules

    Click on “apply” and the rule is set. One may verify this by selecting the data from the table:

    data are masked

    A final note: we may exempt some users from the masking rule. In above menu, we have exempted c##kijk from the masking rule. C##kijk is created by:

    create user c##kijk identified by "AA1234!!"; 
    grant connect, resource to C##kijk;
    grant select on c##redact_user.employees to c##kijk;

    And if log in as c##kijk, we see unmasked values:

    original values
  • Variables in Oracle

    The question is simple: we have an Oracle query and we want to use one search criterium as a parameter. Let us take a simple example. We want to use a parameter in the SQL statement: select * from doel where teller = parameter. So we can write the SQL only once and we can apply the SQL with different parameter values.
    For this example, we use a table doel.

    drop table doel;
    
    CREATE TABLE "DOEL" 
       (	"TELLER" NUMBER, 
    	"NAAM" VARCHAR2(20 BYTE)
       );
    Insert into DOEL (TELLER,NAAM) values ('1','Piet');
    Insert into DOEL (TELLER,NAAM) values ('2','Jan');
    Insert into DOEL (TELLER,NAAM) values ('3','Klaas');
    commit;
    

    Solution 1. We write a SQL statement with a bind variable. We define the bind variable first and we then use that bind variable in a SQL statement.

    var zoek number;
    exec :zoek := 2;
    select * from doel where teller =:zoek;
    

    Solution 2. We create a situation where we use a substitution variable.

    accept p_zoek prompt "Please enter teller number: " default 10;
    
    select * from doel where teller = &p_zoek
    /
    

    Solution 3. We explicitly define a substitution variable. We use that substitution variable in a subsequent SQL statement.

    DEFINE P_zoek = 2;
    
    SELECT * 
    FROM doel 
    WHERE teller = &P_zoek;
    

    Solution 4. We write a PL/SQL procedure. This PL/SQL procedure has a parameter. This procedure can be executed with exec zoek(2);.

    CREATE OR REPLACE PROCEDURE ZOEK 
      (P_ZOEK IN NUMBER) AS 
      select_s  VARCHAR(225);
    BEGIN
      select_s := ' select * from doel where teller = '||P_ZOEK;
      EXECUTE IMMEDIATE select_s;
    END ZOEK;
    
  • a view with security

    One may implement security by creating a view. This view then only contains the columns that you would like to show. If one adds a filter, one may also limit the rows that are shown. The user that is allowed to read a view, only sees the columns and rows that are included in the view.

    The user can not see the underlying tables. If one looks at the privileges, one sees that the other tables are excluded from the porivileges granted:

  • drop Oracle table

    Oracle knows the command “drop table”. One may include this in a script where a table is first deleted (using “drop table”) and subsequently rebuilt with additional SQL statement.
    But what happens if the table doesn’t exist? One may then end up with an error SQL Error: ORA-00942: “table or view does not exist”.

    How to avoid this error?
    Oracle doesn’t have a clause that reads as “if exists then drop table”. The solution to avoid this error is to set up a procedure that reads like:

    create or replace PROCEDURE DROP_TABLE
    (
      P_TABLE_NAME IN VARCHAR2
    ) AS
    n_table           INT;
    stmt              VARCHAR(100);
    BEGIN
      stmt := 'drop table ' || P_TABLE_NAME;
      SELECT COUNT(*) INTO n_table FROM user_tables WHERE table_name = UPPER(p_table_name);
      IF (n_table > 0) THEN
        EXECUTE IMMEDIATE stmt;
      END IF;
    END DROP_TABLE;
    

    This procedure can be called with “exec drop_table(‘ff123’); If the table does not exist, we have no entries in user_tables. In that case, nothing happens. If we have a table that exists, the user_table has an entry and the “execute immediate stmt” is executed. This implies the table is dropped.

  • Processing CSV files in Spark

    It is possible to process CSV files in Spark as if these files are tables. That looks very promising: reading a file, translating the file into something that can be seen as a table and subsequently applying SQL to this. We need some additional jars however. First, we need to download 2 jars: http://mvnrepository.com/artifact/com.databricks/spark-csv_2.10 and http://mvnrepository.com/artifact/org.apache.commons/commons-csv/1.2. I stored these files in SPARK_HOME\lib. In that directory, I saw other jars as well. I then started spark from SPARK_HOME with ./bin/spark-shell –jars lib/spark-csv_2.10-1.5.0.jar,lib/commons-csv-1.2.jar. This then includes the jars that were just downloaded.
    The inclusion of these jars provide a so-called SQL context (sqlContext).
    I could then issue two lines of code:

    • val df = sqlContext.read.format(“com.databricks.spark.csv”).option(“inferScheme”,”true”).option(“header”,”true”).load(“/user/tom/baby_names.csv”);
    • df.registerTempTable(“names”)

    In this situation a file (/user/tom/baby_names.csv) can be approached as a table (names). One may then apply SQL to this:

    • val Som = sqlContext.sql(“select sum(Int(Count)) from names”)

    Som is a dataframe. One may display the content with Som.collect.foreach(println)

  • the Oracle Tuning Advisor

    Oracle has now included an Oracle tuning advisor. Its purpose is to advise on a SQL statement. For me, it provides an answer on whether to add an index or not. I was taught that one should always start with tables that have no indices. Only when it is demonstrated that indices are used, one should create an index. The idea is that maintenance of indices cost time, which must be offset against the gains from an index. If no gains are expected, it is useless to create such index. Of course, we could use the explain plan for that. This reveals whether an index is used or not.
    First, such a SQL statement should be properly included in a structure where it can be analysed. Such a structure can be created with (with SQL Plus:):

    DECLARE
      my_task_name VARCHAR2(30);
      my_sqltext   CLOB;
    BEGIN
      my_sqltext := 'select * from C##HR.GROOT where n=500000';
    
      my_task_name := DBMS_SQLTUNE.CREATE_TUNING_TASK (
              sql_text    => my_sqltext
    ,         user_name   => 'C##HR'
    ,         scope       => 'COMPREHENSIVE'
    ,         time_limit  => 60
    ,         task_name   => 'STA_SPECIFIC_EMP_TASK'
    ,         description => 'Task to tune a query on a specified employee');
    END;
    /
    

    The existence of this structure can be shown if we look into the enterprise manager under the heading Performance > SQL Tuning Advisor > Manual.
    There, we see the entry that we just created.

    Subsequently, we may execute this entry with:

    BEGIN
      DBMS_SQLTUNE.EXECUTE_TUNING_TASK( task_name => 'STA_SPECIFIC_EMP_TASK');
    END;
    /
    

    Clicking on it shows a suggestion:

    It states that an index could be added to improve performance.
    One could also receive such information with:

    SET LONG 10000;
    SET PAGESIZE 1000
    SET LINESIZE 200
    SELECT DBMS_SQLTUNE.report_tuning_task('STA_SPECIFIC_EMP_TASK') AS recommendations FROM dual;
    SET PAGESIZE 24
    

    If that is done (an index on the filter), and the entry is executed again, the suggestion is disappeared.
    We may finally remove the entry with:

    exec dbms_sqltune.drop_tuning_task('STA_SPECIFIC_EMP_TASK');