In this sample chapter, you will learn how to describe PL/SQL architecture within Oracle applications, and how it can be used to develop web and mobile applications in both conventional and cloud environments.
PL/SQL stands for “Procedural Language Extension to SQL.” Because of its tight integration with SQL, PL/SQL supports the great majority of the SQL features, such as SQL data manipulation, data types, operators, functions, and transaction control statements. As an extension to SQL, PL/SQL combines SQL with programming structures and subroutines available in any high-level language.
PL/SQL is used for both server-side and client-side development. For example, database triggers (code that is attached to tables discussed in Chapter 13, “Triggers,” and Chapter 14, “Mutating Tables and Compound Triggers”) on the server side and the logic behind an Oracle form on the client side can be written using PL/SQL. In addition, PL/SQL can be used to develop web and mobile applications in both conventional and cloud environments when used in conjunction with a wide variety of Oracle development tools.
Lab 1.1: PL/SQL Architecture
Many Oracle applications are built using multiple tiers, also known as N-tier architecture, where each tier represents a separate logical and physical layer. For example, a three-tier architecture would consist of three tiers: a data management tier, an application processing tier, and a presentation tier. In this architecture, the Oracle database resides in the data management tier, and the programs that make requests against this database reside in either the presentation tier or the application processing tier. Such programs can be written in many programming languages, including PL/SQL. An example of a simplified three-tier architecture is shown in Figure 1.1.
Figure 1.1 Three-Tier Architecture
Although PL/SQL is just like any other programming language, its main distinction is that it is not a stand-alone programming language. Rather, PL/SQL is a part of the Oracle RDBMS as well as various Oracle development tools such as Oracle Application Express (APEX) and Oracle Forms and Reports, components of Oracle Fusion Middleware. As a result, PL/SQL may reside in any layer of the multitier architecture.
No matter which layer PL/SQL resides in, any PL/SQL block or subroutine is processed by the PL/SQL engine, which is a special component of various Oracle products. As a result, it is easy to move PL/SQL modules between various tiers. The PL/SQL engine processes and executes any PL/SQL statements and sends any SQL statements to the SQL statement processor. The SQL statement processor is always located on the Oracle server. Figure 1.2 illustrates the PL/SQL engine residing on the Oracle server.
Figure 1.2 PL/SQL Engine
When the PL/SQL engine is located on the server, the whole PL/SQL block is passed to the PL/SQL engine on the Oracle server. The PL/SQL engine processes the block according to the scheme depicted in Figure 1.2.
When the PL/SQL engine is located on the client, as it is in Oracle development tools, the PL/SQL processing is done on the client side. All SQL statements that are embedded within the PL/SQL block are sent to the Oracle server for further processing. When a PL/SQL block contains no SQL statements, the entire block is executed on the client side.
Using PL/SQL has several advantages. For example, when you issue a SELECT statement in SQL*Plus or SQL Developer against the STUDENT table, it retrieves a list of students. The SELECT statement you issued at the client computer is sent to the database server to be executed. The results of this execution are then returned to the client. In turn, rows are displayed on your client machine.
Now, assume that you need to issue multiple SELECT statements. Each SELECT statement is a request against the database and is sent to the Oracle server. The results of each SELECT statement are sent back to the client. Each time a SELECT statement is executed, network traffic is generated. Hence, multiple SELECT statements will result in multiple round-trip transmissions, adding significantly to the network traffic.
When these SELECT statements are combined into a PL/SQL program, they are sent to the server as a single unit. The SELECT statements in this PL/SQL program are executed at the server. The server sends the results of these SELECT statements back to the client, also as a single unit. Therefore, a PL/SQL program encompassing multiple SELECT statements can be executed at the server and have all the results returned to the client in the same round trip. This process is obviously more efficient than having each SELECT statement execute independently. This model is illustrated in Figure 1.3.
Figure 1.3 compares two applications. The first application uses four independent SQL statements that generate eight trips on the network. The second application combines SQL statements into a single PL/SQL block, which is then sent to the PL/SQL engine. The engine sends SQL statements to the SQL statement processor and checks the syntax of the PL/SQL statements. As you can see, only two trips are generated on the network with the second application.
Figure 1.3 PL/SQL in Client-Server Architecture
In addition, applications written in PL/SQL are portable. They can run in any environment that Oracle products can run in. Because PL/SQL does not change from one environment to the next, different tools can use PL/SQL programs.
PL/SQL Block Structure
A block is the most basic unit in PL/SQL. All PL/SQL programs are combined into blocks. These blocks can also be nested within one another. Usually, PL/SQL blocks combine statements that represent a single logical task. Therefore, different tasks within a single program can be separated into blocks. With this structure, it is easier to understand and maintain the logic of the program.
PL/SQL blocks can be divided into two groups: named and anonymous. Named PL/SQL blocks are used when creating subroutines. These subroutines, which include procedures, functions, and packages, can be stored in the database and referenced by their names later. In addition, subroutines such as procedures and functions can be defined within the anonymous PL/SQL block. These subroutines exist as long as the block is executing and cannot be referenced outside the block. In other words, subroutines defined in one PL/SQL block cannot be called by another PL/SQL block or referenced by their names later. Subroutines are discussed in Chapters 19 through 21. Anonymous PL/SQL blocks, as you have probably guessed, do not have names. As a result, they cannot be stored in the database or referenced later.
PL/SQL blocks contain three sections: a declaration section, an executable section, and an exception-handling section. The executable section is the only mandatory section of the block; both the declaration and exception-handling sections are optional. As a result, a PL/SQL block has the structure illustrated in Listing 1.1.
Listing 1.1 PL/SQL Block Structure
DECLARE Declaration statements BEGIN Executable statements EXCEPTION Exception-handling statements END;
The declaration section is the first section of the PL/SQL block. It contains definitions of PL/SQL identifiers such as variables, constants, cursors, and so on. PL/SQL identifiers are covered in detail throughout this book.
DECLARE v_first_name VARCHAR2(35); v_last_name VARCHAR2(35);
This example shows the declaration section of an anonymous PL/SQL block. It begins with the keyword DECLARE and contains two variable declarations. The names of the variables, v_first_name and v_last_name, are followed by their data types and sizes. Notice that a semicolon terminates each declaration.
The executable section is the next section of the PL/SQL block. It contains executable statements that allow you to manipulate the variables that have been declared in the declaration section.
BEGIN SELECT first_name, last_name INTO v_first_name, v_last_name FROM student WHERE student_id = 123; DBMS_OUTPUT.PUT_LINE ('Student name: '||v_first_name||' '|| v_last_name); END;
This example shows the executable section of the PL/SQL block. It begins with the keyword BEGIN and contains a SELECT INTO statement from the STUDENT table. The first and last names for student ID 123 are selected into two variables: v_first_name and v_last_name. Chapter 3, “SQL in PL/SQL,” contains a detailed explanation of the SELECT INTO statement. Next, the values of the variables, v_first_name and v_last_name, are displayed on the screen with the help of the DBMS_OUTPUT.PUT_LINE statement. This statement is covered later in this chapter in greater detail. The end of the executable section of this block is marked by the keyword END.
Two types of errors may occur when a PL/SQL block is executed: compilation or syntax errors and runtime errors. Compilation errors are detected by the PL/SQL compiler when there is a misspelled reserved word or a missing semicolon at the end of the statement.
BEGIN DBMS_OUTPUT.PUT_LINE ('This is a test') END;
This example contains a syntax error: the DBMS_OUTPUT.PUT_LINE statement is not terminated by a semicolon.
Runtime errors occur while the program is running and cannot be detected by the PL/SQL compiler. These types of errors are detected or handled by the exception-handling section of the PL/SQL block. It contains a series of statements that are executed when a runtime error occurs within the block.
When a runtime error occurs, control is passed to the exception-handling section of the block. The error is then evaluated, and a specific exception is raised or executed. This is best illustrated by the following example. All changes are shown in bold.
BEGIN SELECT first_name, last_name INTO v_first_name, v_last_name FROM student WHERE student_id = 123; DBMS_OUTPUT.PUT_LINE ('Student name: '||v_first_name||' '|| v_last_name); EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE ('There is no student with student id 123'); END;
This example shows the exception-handling section of the PL/SQL block. It begins with the keyword EXCEPTION. The WHEN clause evaluates which exception must be raised. In this example, there is only one exception, called NO_DATA_FOUND, and it is raised when the SELECT statement does not return any rows. If there is no record for student ID 123 in the STUDENT table, control will be passed to the exception-handling section and the DBMS_OUTPUT.PUT_LINE statement will be executed. Chapter 8, “Error Handling and Built-In Exceptions,” Chapter 9, “Exceptions,” and Chapter 10, “Exceptions: Advanced Concepts,” contain detailed explanations of the exception-handling section.
You have seen examples of the declaration section, executable section, and exception-handling section. These examples may be combined into a single PL/SQL block.
For Example ch01_1a.sql
DECLARE v_first_name VARCHAR2(35); v_last_name VARCHAR2(35); BEGIN SELECT first_name, last_name INTO v_first_name, v_last_name FROM student WHERE student_id = 123; DBMS_OUTPUT.PUT_LINE ('Student name: '||v_first_name||' '|| v_last_name); EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE ('There is no student with student id 123'); END;
How PL/SQL Gets Executed
Every time an anonymous PL/SQL block is executed, the code is sent to the PL/SQL engine, where it is compiled. A named PL/SQL block is compiled only at the time of its creation or if it has been changed. The compilation process includes syntax and semantic checking, as well as code generation.
Syntax checking involves checking PL/SQL code for syntax or compilation errors. As stated previously, a syntax error occurs when a statement does not exactly correspond to the syntax of the programming language. A misspelled keyword, a missing semicolon at the end of the statement, and an undeclared variable are all examples of syntax errors. After syntax errors are corrected, the compiler can generate a parse tree.
Semantic checking involves further processing on the parse tree. It determines whether database objects such as table names and column names referenced in the SELECT statements are valid and whether you have privileges to access them. At the same time, the compiler can assign a storage address to program variables that are used to hold data. This process, which is called binding, allows Oracle software to reference storage addresses when the program is run.
Code generation creates code for the PL/SQL block in interpreted or native mode. Code created in interpreted mode is called p-code. P-code is a list of instructions to the PL/SQL engine that are interpreted at runtime. Code created in a native mode is a processor-dependent system code that is called native code. Because native code does not need to be interpreted at runtime, it usually runs slightly faster.
The mode in which the PL/SQL engine generates code is determined by the PLSQL_CODE_TYPE database initialization parameter. By default, its value is set to INTERPRETED. This parameter is typically set by the database administrators.
For named blocks, both p-code and native code are stored in the database and are used the next time the program is executed. When the process of compilation has completed successfully, the status of a named PL/SQL block is set to VALID, and it is also stored in the database. If the compilation process was not successful, the status of the named PL/SQL block is set to INVALID.