Pages

Showing posts with label PLSQL. Show all posts
Showing posts with label PLSQL. Show all posts

Wednesday, May 20, 2015

Wrapping PLSQL Source Code



Wrapping is the process of hiding PLSQL source code. Wrapping helps to protect your source code from business competitors and others who might misuse it. You can wrap PLSQL source code with either the wrap utility or DBMS_DDL subprograms. The wrap utility wraps a single source file, such as a SQL*Plus script. The DBMS_DDL subprograms wrap a single dynamically generated PLSQL unit, such as a single CREATE PROCEDURE statement.

Wrapped source files can be moved, backed up, and processed by SQL*Plus and the Import and Export utilities, but they are not visible through the static data dictionary views *_SOURCE.

Guidelines for Wrapping

  1. Wrap only the body of a package or object type, not the specification. This allows other developers to see the information they must use the package or type, but prevents them from seeing its implementation.
  2. Wrap code only after you have finished editing it. You cannot edit PL/SQL source code inside wrapped files. Either wrap your code after it is ready to ship to users or include the wrapping operation as part of your build environment. To change wrapped PL/SQL code, edit the original source file and then wrap it again.
  3. Before distributing a wrapped file, view it in a text editor to be sure that all important parts are wrapped.
Limitations of Wrapping

  1. Wrapping is not a secure method for hiding passwords or table names. Wrapping a PL/SQL unit prevents most users from examining the source code, but might not stop all of them.
  2. Wrapping does not hide the source code for triggers. To hide the workings of a trigger, write a one-line trigger that invokes a wrapped subprogram.
  3. Wrapping does not detect syntax or semantic errors. Wrapping detects only tokenization errors (for example, runaway strings), not syntax or semantic errors (for example, nonexistent tables or views). Syntax or semantic errors are detected during PL/SQL compilation or when executing the output file in SQL*Plus.
  4. Wrapped PL/SQL units are not downward-compatible. Wrapped PL/SQL units are upward-compatible between Oracle Database releases, but are not downward-compatible. 
Wrapping PL/SQL Code with wrap Utility

The wrap utility processes an input SQL file and wraps only the PL/SQL units in the file, such as a package specification, package body, function, procedure, type specification, or type body. It does not wrap PL/SQL content in anonymous blocks or triggers or non-PL/SQL code.

To run the wrap utility, enter the wrap command at your operating system prompt using the following syntax (with no spaces around the equal signs):

wrap iname=input_file [ oname=output_file ]

input_file is the name of a file containing SQL statements, that you typically run using SQL*Plus. If you omit the file extension, an extension of .sql is assumed. For example, the following commands are equivalent:

wrap iname=/mydir/myfile
wrap iname=/mydir/myfile.sql

You can also specify a different file extension:
wrap iname=/mydir/myfile.src

output_file is the name of the wrapped file that is created. The defaults to that of the input file and its extension default is .plb. For example, the following commands are equivalent:

wrap iname=/mydir/myfile
wrap iname=/mydir/myfile.sql oname=/mydir/myfile.plb

You can use the option oname to specify a different file name and extension:
wrap iname=/mydir/myfile oname=/yourdir/yourfile.out


Input and Output Files for the PL/SQL wrap Utility
The input file can contain any combination of SQL statements. Most statements are passed through unchanged. CREATE statements that define subprograms, packages, or object types are wrapped; their bodies are replaced by a scrambled form that the PLSQL compiler understands.

The following CREATE statements are wrapped:

CREATE [OR REPLACE] FUNCTION function_name
CREATE [OR REPLACE] PROCEDURE procedure_name
CREATE [OR REPLACE] PACKAGE package_name
CREATE [OR REPLACE] PACKAGE BODY package_name
CREATE [OR REPLACE] TYPE type_name AS OBJECT
CREATE [OR REPLACE] TYPE type_name UNDER type_name
CREATE [OR REPLACE] TYPE BODY type_name

The CREATE [OR REPLACE] TRIGGER statement, and [DECLARE] BEGIN-END anonymous blocks, are not wrapped. All other SQL statements are passed unchanged to the output file.

All comment lines in the unit being wrapped are deleted, except for those in a CREATE OR REPLACE header and C-style comments (delimited by /* */). The output file is a text file, which you can run as a script in SQL*Plus to set up your PL/SQL subprograms and packages. Run a wrapped file as follows:

SQL> @wrapped_file_name.plb;


Using DBMS_DDL.CREATE_WRAPPED Procedure
In the below example CREATE_WRAPPED is used to dynamically create and wrap a package specification and a package body in a database.

Example: Using DBMS_DDL.CREATE_WRAPPED Procedure to Wrap a Package
DECLARE
  package_text VARCHAR2(32767); -- text for creating package spec & body
 
  FUNCTION generate_spec(pkgname VARCHAR2) RETURN VARCHAR2 AS
  BEGIN
    RETURN 'CREATE PACKAGE ' || pkgname || ' AS
            PROCEDURE raise_salary (emp_id NUMBER, amount NUMBER);
            PROCEDURE fire_employee (emp_id NUMBER);
            END ' || pkgname || ';';
  END generate_spec;
 
  FUNCTION generate_body(pkgname VARCHAR2) RETURN VARCHAR2 AS
  BEGIN
    RETURN 'CREATE PACKAGE BODY ' || pkgname || ' AS
            PROCEDURE raise_salary (emp_id NUMBER, amount NUMBER) IS
            BEGIN
              UPDATE employees
              SET salary = salary + amount WHERE employee_id = emp_id;
            END raise_salary;
           
            PROCEDURE fire_employee (emp_id NUMBER) IS
            BEGIN
              DELETE FROM employees WHERE employee_id = emp_id;
              END fire_employee;
            END ' || pkgname || ';';
  END generate_body;
 
BEGIN
  -- Generate package spec
  package_text := generate_spec('emp_actions')
 
  -- Create wrapped package spec
  DBMS_DDL.CREATE_WRAPPED(package_text);
 
  -- Generate package body
  package_text := generate_body('emp_actions');
 
  -- Create wrapped package body
  DBMS_DDL.CREATE_WRAPPED(package_text);
 
END;

-- Invoke procedure from wrapped package
CALL emp_actions.raise_salary(120, 100);
When you check the static data dictionary views *_SOURCE, the source is wrapped, or hidden, so that others cannot view the code details. For example:

SELECT text FROM USER_SOURCE WHERE name = 'EMP_ACTIONS';

The resulting output is similar to the following:

TEXT
--------------------------------------------------------------------
PACKAGE emp_actions WRAPPED
a000000
1f
abcd
...

Sunday, April 12, 2015

Architecture of PLSQL


PL/SQL Architecture includes below:
PL/SQL Engine
PL/SQL Units and Compilation Parameter

PL/SQL Engine
The PL/SQL compilation and run-time system is an engine that compiles and executes PL/SQL units. The engine can be installed in the database or in an application development tool, such as Oracle Forms.

In either environment, the PL/SQL engine accepts as input any valid PL/SQL unit. The engine executes procedural statements, but sends SQL statements to the SQL engine in the database, as shown in below:
Architecture of PLSQL
PLSQL Engine



















Typically, the database processes PL/SQL units. When an application development tool processes PL/SQL units, it passes them to its local PL/SQL engine. If a PL/SQL unit contains no SQL statements, the local engine processes the entire PL/SQL unit. This is useful if the application development tool can benefit from conditional and iterative control.

For example, Oracle Forms applications frequently use SQL statements to test the values of field entries and do simple computations. By using PL/SQL instead of SQL, these applications can avoid calls to the database.

PL/SQL Units and Compilation Parameters
A PL/SQL unit is any one of the following:

PL/SQL block
FUNCTION
PACKAGE
PACKAGE BODY
PROCEDURE
TRIGGER
TYPE
TYPE BODY

PL/SQL units are affected by PL/SQL compilation parameters (a category of database initialization parameters). Different PL/SQL units—for example, a package specification and its body—can have different compilation parameter settings. For more information about these parameters, see Oracle Database Reference. To display the values of these parameters, use the static data dictionary view ALL_PLSQL_OBJECT_SETTINGS. For more information about this view, see Oracle Database Reference.

The compile-time values of most of the parameters are stored with the metadata of the PL/SQL unit, which means you can reuse those values when you explicitly recompile the program unit by doing the following:

1.    Use one of the following statements to recompile the program unit:
ALTER FUNCTION COMPILE
ALTER PACKAGE COMPILE
ALTER PROCEDURE COMPILE
2.    Include the REUSE SETTINGS clause in the statement. This clause preserves the existing settings and uses them for the recompilation of any parameters for which values are not specified elsewhere in the statement.

If you use the SQL statements CREATE OR REPLACE to explicitly compile a PL/SQL subprogram, or if you do not include the REUSE SETTINGS clause in the ALTER COMPILE statement, then the value of the compilation parameter is its value for the session.

Monday, March 23, 2015

Oracle SQL PLSQL Exam Preparation Question & Answar



What is SQL?
SQL stands for structured query language. It is a database language used for database creation, deletion, fetching rows and modifying rows etc. sometimes it is pronounced as se-qwell.

When SQL appeared?
It appeared in 1974.

What are the usages of SQL?
To execute queries against a database
To retrieve data from a database
To inserts records in a database
To updates records in a database
To delete records from a database
To create new databases
To create new tables in a database
To create views in a database

Does SQL support programming?
No, SQL doesn't have loop or Conditional statement. It is used like commanding language to access databases.
What are the subsets of SQL?
Data definition language (DDL)
Data manipulation language (DML)
Data control language (DCL)

What is data definition language?
Data definition language(DDL) allows you to CREATE, ALTER and DELETE database objects such as schema, tables, view, sequence etc.

What is data manipulation language?
Data manipulation language makes user able to access and manipulate data. It is used to perform following operations.
  • Insert data into database
  • Retrieve data from the database
  • Update data in the database
  • Delete data from the database
What is data control language?
Data control language allows you to control access to the database. It includes two commands GRANT and REVOKE.
GRANT: to grant specific user to perform specific task.
REVOKE: to cancel previously denied or granted permissions.

What are the type of operators available in SQL?
1.    Arithmetic operators
2.    Logical operators
3.    Comparison operator
What is the SQL query to display current date?
There is a built in function in SQL called sysdate which is used to return current timestamp.

Which types of join is used in SQL widely?
The knowledge of JOIN is very necessary for an interviewee. Mostly used join is INNER JOIN and (left/right) OUTER JOIN.

What is "TRIGGER" in SQL?
Trigger allows you to execute a batch of SQL code when an insert, update or delete command is executed against a specific table.
Actually triggers are special type of stored procedures that are defined to execute automatically in place or after data modifications.

What is self join and what is the requirement of self join?
Self join is often very useful to convert a hierarchical structure to a flat structure. It is used to join a table to itself as like if that is the second table.

What are set operators in SQL?
Union, intersect or minus operators are called set operators.

What is a constraint? Tell me about its various levels.
Constraints are representators of a column to enforce data entity and consistency. There are two levels :
·         column level constraint
·         table level constraint

Write an SQL query to find names of employee start with 'A'?
SELECT * FROM Employees WHERE EmpName like 'A%'

Write an SQL query to get third maximum salary of an employee from a table named employee_table
1.    SELECT TOP 1 salary   
2.    FROM (  
3.    SELECT TOP 3 salary  
4.    FROM employee_table  
5.    ORDER BY salary DESC ) AS emp  
6.    ORDER BY salary ASC;    



What is the difference between DELETE and TRUNCATE statement in SQL?

The main differences between SQL DELETE and TRUNCATE statements are given below:

No.
DELETE
TRUNCATE
1)
DELETE is a DML command.
TRUNCATE is a DDL command.
2)
We can use WHERE clause in DELETE command.
We cannot use WHERE clause with TRUNCATE
3)
DELETE statement is used to delete a row from a table
TRUNCATE statement is used to remove all the rows from a table.
4)
DELETE is slower than TRUNCATE statement.
TRUNCATE statement is faster than DELETE statement.
5)
You can rollback data after using DELETE statement.
It is not possible to rollback after using TRUNCATE statement

What is PL/SQL?

PL/SQL stands for procedural language extension to SQL. It supports procedural features of programming language and SQL both. It was developed by Oracle Corporation in early of 90's to enhance the capabilities of SQL.

PL/SQL is a procedural language that has both interactive SQL and procedural programming language constructs such as iteration, conditional branching.

What is PL/SQL table? Why it is used?

Objects of type tables are called PL/SQL tables that are modeled as database table. We can also say that PL/SQL tables are a way to providing arrays. Arrays are like temporary tables in memory that are processed very quickly. PL/SQL tables are used to move bulk data. They simplifies moving collections of data.

What are the datatypes available in PL/SQL?

There are two types of datatypes in PL/SQL:
1.    Scalar datatypes Example are NUMBER, VARCHAR2, DATE, CHAR, LONG, BOOLEAN etc.
2.    Composite datatypes Example are RECORD, TABLE etc.

What is the basic structure of PL/SQL?

PL/SQL uses BLOCK structure as its basic structure. Each PL/SQL program consists of SQL and PL/SQL statement which form a PL/SQL block.
PL/SQL block contains 3 sections.
The Declaration Section (optional)
The Execution Section (mandatory)
The Exception handling Section (optional)

What is the difference between FUNCTION, PROCEDURE AND PACKAGE in PL/SQL?

Function: The main purpose of a PL/SQL function is generally to compute and return a single value. A function has a return type in its specification and must return a value specified in that type.
Procedure: A procedure does not have a return type and should not return any value but it can have a return statement that simply stops its execution and returns to the caller. A procedure is used to return multiple values otherwise it is generally similar to a function.
Package: A package is schema object which groups logically related PL/SQL types , items and subprograms. You can also say that it is a group of functions, procedure, variables and record type statement. It provides modularity, due to this facility it aids application development. It is used to hide information from unauthorized users.

What is exception? What are the types of exceptions?

Exception is an error handling part of PL/SQL. There are two type of exceptions: pre_defined exception and user_defined exception.

How exception is different from error?

Whenever an Error occurs Exception arises. Error is a bug whereas exception is a warning or error condition.

What is the main reason behind using an index?

Faster access of data blocks in the table.

What are PL/SQL exceptions? Tell me any three.

1.    Too_many_rows
2.    No_Data_Found
3.    Value_error
4.    Zero_error etc.

What is the maximum number of triggers, you can apply on a single table?

12 triggers.

How many types of triggers exist in PL/SQL?

There are 12 types of triggers in PL/SQL that contains the combination of BEFORE, AFTER, ROW, TABLE, INSERT, UPDATE, DELETE and ALL keywords.
  • BEFORE ALL ROW INSERT
  • AFTER ALL ROW INSERT
  • BEFORE INSERT
  • AFTER INSERT etc.

What is stored Procedure?

A stored procedure is a sequence of statement or a named PL/SQL block which performs one or more specific functions. It is similar to a procedure in other programming languages. It is stored in the database and can be repeatedly executed. It is stored as schema object. It can be nested, invoked and parameterized.

What are the advantages of stored procedure?

Modularity, extensibility, reusability, Maintainability and one time compilation.

What are the cursor attributes used in PL/SQL?

%ISOPEN: it checks whether the cursor is open or not.
%ROWCOUNT: returns the number of rows affected by DML operations: INSERT,DELETE,UPDATE,SELECT.
%FOUND: it checks whether cursor has fetched any row. If yes - TRUE.
%NOTFOUND: it checks whether cursor has fetched any row. If no - TRUE.

What is consistency?

Consistency simply means that each user sees the consistent view of the data.
Consider an example: there are two users A and B. A transfers money to B's account. Here the changes are updated in A's account (debit) but until it will be updated to B's account (credit), till then other users can't see the debit of A's account. After the debit of A and credit of B, one can see the updates. That?s consistency.

What is cursor and why it is required?

A cursor is a temporary work area created in a system memory when an SQL statement is executed.
A cursor contains information on a select statement and the row of data accessed by it. This temporary work area stores the data retrieved from the database and manipulate this data. A cursor can hold more than one row, but can process only one row at a time. Cursor are required to process rows individually for queries.

How many types of cursors are available in PL/SQL?

There are two types of cursors in PL/SQL.

1.    Implicit cursor, and
2.    explicit cursor

What is the difference between %ROWTYPE and %TYPE and what is the main advantage to using these?

The %ROWTYPE allows the coder to indirectly represent a full or partial row of a database table or view, whereas the %TYPE allows for the coder to indirectly represent the data type from a previously declared variable or column. Basically, %ROWTYPE works on a full object whereas %TYPE works on a single column. The advantage to using either of these enables the coder to maintain data type declarations without ever having to know or change the data type for the items that use these. Below is an example of how the %TYPE allows for a layer of abstraction between names; allowing the coder to just change the first occurrence of the data type.
DECLARE
 name   VARCHAR(50);
 fname  name%TYPE;
 lname  name%TYPE;
 city   name%TYPE;
 country name%TYPE;
BEGIN
 Execution section;
END;
/

How might you display compile time warnings for PL/SQL code?

There are actually two methods to show compile time warnings. While both 'SHOW ERRORS' and the *_errors views (USER_ERRORS used here) show basically the same information; I tend to like the SHOW ERRORS command as it seems quicker to type. The advantage to using the *_errors views is that you can actually monitor every developer's current errors when using a view such as DBA_ERRORS, as there is an additional column for OWNER that will tell you the user encountering errors.

Define 'scope' and 'visibility' for PL/SQL variables.

The definition of scope and visibility for a variable is actually quite close with the only difference being if you have to qualify the variable. The scope of a variable refers to the region (breadth) of code where the variable can be referenced. The visibility refers to the region of code you can reference the variable without qualifying it. So, hopefully you can see, visibility is a subset of the scope and requires the variable to be qualified (told where it comes from) in order to use. An example is clearly the best option here to help explain. Consider the PL/SQL code:
What are two virtual tables available during database trigger execution?

The table columns are referred as OLD.column_name and NEW.column_name.
For triggers related to INSERT only NEW.column_name values only available.
For triggers related to UPDATE only OLD.column_name NEW.column_name values only available. 
For triggers related to DELETE only OLD.column_name values only available.

Is it possible to use Transaction control Statements such a ROLLBACK or COMMIT in Database Trigger? Why?

It is not possible. As triggers are defined for each table, if you use COMMIT of ROLLBACK in a trigger, it affects logical transaction processing.
What is Overloading of procedures?
The Same procedure name is repeated with parameters of different datatypes and parameters in different positions, varying number of parameters is called overloading of procedures.
e.g. DBMS_OUTPUT.put_line

What is a package? What are the advantages of packages?
Package is a database object that groups logically related procedures. The advantages of packages are Modularity, Easier Applicaton Design, and Information hiding, Reusability and Better Performance.

What are two parts of package?
The two parts of package are PACKAGE SPECIFICATION & PACKAGE BODY. Package Specification contains declarations that are global to the packages and local to the schema. Package Body contains actual procedures and local declaration of the procedures and cursor declarations.

What is difference between a Cursor declared in a procedure and Cursor declared in a package specification?

A cursor declared in a package specification is global and can be accessed by other procedures or procedures in a package.

A cursor declared in a procedure is local to the procedure that cannot be accessed by other procedures.

Rank:
In Oracle PL/SQL, RANK function is a built in analytic function which is used to rank a record within a group of rows. Its return type is number and serves for both aggregate and analytic purpose in SQL.

SQL of ROW_NUMBER, RANK & DENSE_RANK:
select last_name,department_id,salary,
       row_number() over ( order by salary desc) Row_Num,
       rank() over ( order by salary desc) Rank,
       dense_rank() over ( order by salary desc) Dense_RAnk      
from EMPLOYEES

SQL using LEAD & LAG function:

SELECT emp_ID,
       LAST_NAME,
       job_ID,
       salARY,
       LEAD(salARY, 1, 0) OVER (ORDER BY salARY) AS sal_next,
       LAG (salARY, 1, 0) OVER (ORDER BY salARY) AS sal_prev,
FROM   emPLOYEES;