Oracle PL/SQL for dummies phần 5 pps

44 318 0
Oracle PL/SQL for dummies phần 5 pps

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

The reason for these rules is simple. Oracle can’t be sure that modifying data, the session, the system, or object structure doesn’t have any impact on the data you’re querying or even on objects you’re processing. If such activity isn’t blocked, a logical loop or conflict that can’t be resolved might result. Think about what should happen if the function in the next example is called in SQL. This function updates the salary of the specified employee and tells you whether the update was successful: create or replace function f_giveRaise_tx (i_empNo NUMBER, i_pcnt NUMBER) return VARCHAR2 is begin update emp set sal=sal*(i_pcnt/100)+sal where empNo = i_empNo; return ‘OK’; exception when others then return ‘Error:’||substr(sqlerrm,1,256); end f_giveRaise_tx; Instead of the update confirmation, the result of the query is an Oracle error, which is caught by the exception handler of the function: SQL> select f_giveRaise_tx(7369,100) 2 from dual; F_GIVERAISE_TX(7369,100) Error:ORA-14551: cannot perform a DML operation inside a query SQL> Oops! Oracle just told you that you cannot make that UPDATE. Performance impact How does the Oracle know what exactly is happening “under the hood” of the function that you placed inside the query? How can it determine what impact that function could have on overall execution? It can’t. In terms of performance, using functions in SQL is risky. With functions in SQL, the whole idea of SQL optimization gains another dimension; namely, decreasing the impact of function calls. There are some guidelines you can follow. The next example shows a display function for an employee that returns name and job. It also includes a view that uses this display function for managers: 158 Part II: Getting Started with PL/SQL 11_599577 ch06.qxp 5/1/06 12:12 PM Page 158 create or replace function f_emp_dsp (i_empNo NUMBER) return VARCHAR2 is v_out_tx VARCHAR2 (256); begin DBMS_OUTPUT.put_line(‘Inside of F_EMP_DSP’); select initcap(eName)||’: ‘||initcap(job) into v_out_tx from emp where empNo = i_empNo; return v_out_tx; end f_emp_dsp; / create or replace view v_emp as select empNo, eName, mgr, f_emp_dsp(mgr) mgr_name, deptNo from emp; / When you query the view, it may run much more slowly than a query that accesses the EMP table directly. If performance is important (and performance is always important), you need to be careful. Here are some guidelines: Don’t ask for what you don’t need If you only need EMPNO and ENAME, the following statement is inefficient: select * from v_emp; Use this statement instead: select empNo, eName from v_emp; Remember that one of the columns in the view v_emp is defined as a func- tion. In the first case, that function will be executed for each record to be processed. The asterisk (*) means that you are retrieving all columns listed in the view including the column defined as a function. You do not need that extra data, but it will still be unnecessarily calculated when the query is exe- cuted, making your query run more slowly than necessary. Don’t ask for what you already have Function f_emp_dsp will return exactly the same value for the same employee each time it is called. This behavior is called “deterministic.” Knowing about this behavior can help Oracle avoid redundant function calls. If a deterministic function was called previously with the same arguments, the optimizer can elect to use the previous result. Thus, the function could be modified as follows: 159 Chapter 6: PL/SQL and SQL Working Together 11_599577 ch06.qxp 5/1/06 12:12 PM Page 159 create or replace function f_emp_dsp (in_empNo NUMBER) return VARCHAR2 DETERMINISTIC is Declaring a function DETERMINISTIC is only a hint, and there is no guaran- tee that the optimizer will use it. However, it can be very handy. Don’t run the function all the time when you only need it some of the time Assume that you need to take some action for every record in department 10, which includes using the display function for employees. You could start by writing your query this way: declare cursor c_emp is select * from v_emp; begin for r_emp in c_emp loop if r_emp.deptNo = 10 then end if; end loop; end; You should assume that any number of calls greater than the number of employees in department 10 is a waste of resources. The following query works exactly as expected: declare cursor c_emp is select * from v_emp where deptNo=10; begin for r_emp in c_emp loop end if; end; Function calls can be expensive from a system resource perspective. Do your best to ensure that the calls you use are efficient and do only what you want them to do. Getting good performance with functions Oracle can’t do everything for you. For example, it can’t guess exactly what you want from your system. The human mind can always outsmart a com- puter, but the trick is not to outsmart yourself. 160 Part II: Getting Started with PL/SQL 11_599577 ch06.qxp 5/1/06 12:12 PM Page 160 Sticking to the following rules will make your life and your database perfor- mance significantly better. ߜ As you write any function, ask yourself, “Will it be used in SQL or not?” If so, verify that SQL works with the datatypes you’re passing in and out. ߜ Verify that you are not performing illegal reads/writes. For how to cheat if needed, see Chapter 12, which covers transaction control. ߜ Think about performance at design time, not later, when users start to complain about it. Write your code with its future use in mind. Sometimes saving a keystroke or two in implementation might seem like a good idea, but it can result in hours of necessary tuning when your system is in production. 161 Chapter 6: PL/SQL and SQL Working Together 11_599577 ch06.qxp 5/1/06 12:12 PM Page 161 162 Part II: Getting Started with PL/SQL 11_599577 ch06.qxp 5/1/06 12:12 PM Page 162 Part III Standards and Structures 12_599577 pt03.qxp 5/1/06 12:13 PM Page 163 In this part . . . P art III provides guidance about how to structure the code you write and useful standards for naming and coding. Chapter 7 discusses the many options of where to place PL/SQL code within a system and provides information to help you make the right decision. Chapters 8 and 9 cover the importance of establishing standards for both naming and coding and list standards that we use in our own work to assist you in creating your own. 12_599577 pt03.qxp 5/1/06 12:13 PM Page 164 Chapter 7 Putting Your Code in the Right Place In This Chapter ᮣ Placing code in the database ᮣ Using triggers ᮣ Using application logic ᮣ Placing code in the middle tier W riting good code that runs efficiently isn’t enough to guarantee the success of a project. Deciding where to put the code is just as impor- tant as writing it. Code can be written in lots of different places within a system, but each of these places has pro and cons. Frequently, depending upon what the code needs to do, you can make a clear, correct decision about where the code should reside. At other times, you have a variety of acceptable alternatives for placing the code. Deciding how and where to place code has been a hotly debated topic in the application development world. In client/server development, you had to decide what logic belonged in the database and what logic belonged within the user interface. Since the advent of Web-based systems that run code on an application server, code can reside in even more places. With all these options, the question remains: Which code should be placed where? This chapter attempts to give you the answers by taking a look at the pros and cons of your options. First, you find out about storing code in the data- base. Then we explain why implementing logic in the middle tier should only be done very carefully. Putting Code in the Database The most common code container in the database is a stored procedure. Stored procedures refer to functions and procedures stored in isolation or 13_599577 ch07.qxp 5/1/06 12:13 PM Page 165 grouped into packages. Opting for packages has a number of benefits, including the ability to store large functions or procedures and better code maintenance. In other cases, you might want to store code as a trigger or an INSTEAD OF trigger view. The following sections take a look at all these options. Managing code Before modern PL/SQL editors were developed, searching the database and retrieving code from the database for editing were inconvenient, but these are now simple tasks. If you’re having difficulty finding a specific piece of code, most IDEs have efficient search capabilities that allow you to search all the code stored in the database and retrieve the desired section of code. Some organizations maintain their source code in documents rather than in the database. This is particularly true of large organizations using formal con- figuration management architectures where code must be checked in and out before it can be worked on. However, from the developer’s perspective, look- ing through code in the database is easier rather than trying to dig through files maintained by configuration management software. However, this won’t be possible if the code in the database is obfuscated, so that it isn’t human- readable. This is a measure that may be used in some security-conscious sites and by application packagers. The most popular IDEs used to search and maintain PL/SQL code are Toad and SQL*Navigator, both developed by Quest Software. For many years, Oracle seemed content not to compete in this market. However, Oracle has recently released SQL Developer (formerly called Raptor and also mentioned in Chapter 2). This tool is a fully featured PL/SQL code editor that might easily dominate the market in the future. Packaging code in the database Packages (as we discuss in Chapter 3) are the most common place to put code in the database. There are some differences between placing code in a package and making it an isolated routine beyond its logical organization; we discuss these differences here. From a code maintenance perspective, putting database code into packages is always better. This allows you to logically group and manage the code much more easily, assuming that you’re using an IDE that allows you to view a list of the functions and procedures within a package and quickly navigate to them. However, putting all your functions and procedures into packages has a few disadvantages. 166 Part III: Standards and Structures 13_599577 ch07.qxp 5/1/06 12:13 PM Page 166 Code scope and visibility in packages If you place a function or procedure inside a package, it isn’t necessarily accessible from outside the package. It will be accessible outside the package only if it is declared in the package specification. Even within the package, it is accessible only to other functions and procedures that are declared after it. Similarly, within packages, you can declare variables or any objects in the package that either are visible only within the package or can be referenced from outside the package. Listing 7-1 shows a package to handle login functions. Some functions are accessible only within the package; others can be seen outside of the package. Listing 7-1: The Login Function Package create or replace package pkg_emp is gv_current_empNo NUMBER; ➞ 2 procedure p_setCurrentEmpNo (i_empNo NUMBER); function f_getCurrentEmpNo return NUMBER; procedure p_giveRaise (i_pcnt NUMBER); end; create or replace package body pkg_emp is gv_LOGUSER_tx VARCHAR2(256); ➞ 11 procedure p_validateUser is ➞ 13 begin if gv_LOGUSER_tx is null then raise_application_error (-20999,’no valid user!’); else if gv_LOGUSER_tx not like ‘SCOTT%’ then raise_application_error (-20999,’not enough privileges!’); end if; end if; end; procedure p_setCurrentEmpNo (i_empno number)is begin gv_LOGUSER_tx:=user||’|’|| sys_context(‘userenv’,’ip_address’); gv_current_empno:=i_empNo; end; function f_getCurrentEmpno return NUMBER is begin return gv_current_empNo; (continued) 167 Chapter 7: Putting Your Code in the Right Place 13_599577 ch07.qxp 5/1/06 12:13 PM Page 167 [...]... of skill isn’t a good reason for placing data in the middle tier ߜ Some amount of code should be placed in the middle tier Code needed by the user interface will perform better in the middle tier ߜ One way that PL/SQL is used in the middle tier is when building applications using the Oracle Developer suite that includes Oracle Forms and Oracle Reports Forms isn’t used for much new development because... for each user on a system However, there is only so much room in memory for storing PL/SQL code If this memory fills up, Oracle is forced to swap out any code that hasn’t been used recently The next time that this code is referenced, it must be reloaded into memory, potentially swapping out other code Therefore, if you have a large amount of PL/SQL in your system and not a lot of memory allocated for. .. most comfortable for experienced Oracle developers It uses basically the same philosophy as creating any front-end application for an Oracle database ߜ The system isn’t closely tied to an application development framework (ADF) Most of the non-UI code resides in the database We explain why in more detail later in this chapter ߜ User interface work becomes much simpler For example, if you use Oracle s... either before or after the database event to which they are tied BEFORE EVENT triggers, as shown in the preceding code, are for preventing the event from actually happening AFTER EVENT triggers are also very useful For example, you could use them to create an audit trail when sensitive data in a record was successfully changed You should not record that information in BEFORE EVENT triggers, because before... be aware of these before setting your standards Oracle database influences One influence that affects PL/SQL naming and coding standards is the database itself Oracle includes some naming limitations that you must carry over into your naming standards Among your key considerations are the following: ߜ PL/SQL is an Oracle database programming language As a result, you will refer to Oracle database objects... packages for optimal performance Placing code in packages has mixed impacts on performance The first time a package is referenced, the entire package is brought into memory For very large packages (20,000 lines of code or more), this might mean a delay of a full second or more the first time that the package is referenced When the package is in memory, other users can reference it very quickly Oracle. .. Oracle can execute about 10,000 such update statements in a second, this performance problem becomes apparent only if you’re doing bulk updates to thousands (or millions) of records We avoid INSTEAD OF triggers for views that have to support a great deal of data manipulation Locking in INSTEAD OF trigger views The conventional wisdom for locking used to be that you need to lock all your objects before... any of them The technique for doing this was to use a SELECT FOR UPDATE command Experience has shown that using SELECT FOR UPDATE usually causes many more problems than it prevents You’ll want to keep in mind a few modifications of this old conventional wisdom about locking: ߜ In the UPDATE and DELETE triggers in Listing 7-7, it is theoretically possible to cause a deadlock for Oracle to resolve Because... the PL/SQL code and these other languages Chapter 8: Creating Naming Standards Modern application development tools and their influences Unfortunately, many organizations are unwilling to invest in tools to make their developers more productive Oracle s SQL*Plus is a no-frills tool with few of the nice features of products that try to support PL/SQL development Some developers even prefer SQL*Plus for. .. 8-1 PL/SQL Variable Prefixes Prefix Variable Type v_ Local variables declared within a function or procedure c_ Cursor r_ Record variable for CURSOR FOR loops gv_ Global variables declared within a package gl_ Global constants declared within a package gc_ Global cursors declared within a package Table 8-2 PL/SQL Variable Suffixes Suffix Variable Type _yn Pseudo-Boolean items using ‘Y’ and ‘N’ for . production. 161 Chapter 6: PL/SQL and SQL Working Together 11 _59 957 7 ch06.qxp 5/ 1/06 12:12 PM Page 161 162 Part II: Getting Started with PL/SQL 11 _59 957 7 ch06.qxp 5/ 1/06 12:12 PM Page 162 Part. display function for an employee that returns name and job. It also includes a view that uses this display function for managers: 158 Part II: Getting Started with PL/SQL 11 _59 957 7 ch06.qxp 5/ 1/06 12:12. result. Thus, the function could be modified as follows: 159 Chapter 6: PL/SQL and SQL Working Together 11 _59 957 7 ch06.qxp 5/ 1/06 12:12 PM Page 159 create or replace function f_emp_dsp (in_empNo NUMBER)

Ngày đăng: 08/08/2014, 20:21

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan