Presentation is loading. Please wait.

Presentation is loading. Please wait.

An Introduction to Oracle

Similar presentations


Presentation on theme: "An Introduction to Oracle"— Presentation transcript:

1 An Introduction to Oracle
Victor Matos

2 What is ORACLE ? Very robust implementation of a Relational Database Management System (RDBMS) The relational model of data is simple to understand and has been extensively scrutinized since 1970’s

3 What else is good about ORACLE ?
The company is solid and successful, since 1994 revenues in the order of $2+ billion/year Very popular software, worldwide distribution Runs in 100+ different type of computers

4 Reasons for the Oracle Success
Security Mechanisms users are given specific rights to operate on the data. Backup and Recovery minimizes data loss and idle time in the presence of failures Space Management flexible allocation Open Connectivity uninterrupted services reachable from heterogeneous clients Development Tools many to choose from

5 Parts of the Oracle Server
Procedural Option: built-in programming capabilities based on the PL/SQL language Stored Procedures: programs stored in the server-side could be invoked using an ADA-like interface Triggers: dormant server-side routines which are ‘fired’ when specific maintenance conditions are met

6 Parts of the Oracle Server cont
Packages: libraries of server-side routines including proc, functions, triggers, user defined data types, constants, variables.

7 Parts of the Oracle Server cont
Distributed Option: data could be stored in different machines and placed in different cities. Oracle Distributed option provides location transparency, the user does not need to be aware of where the data is kept.

8 Oracle Distributed Option

9 Parts of the Oracle Server cont
Parallel Server Option: Independent machines (nodes) which their own memory and disk space could tap into a common disk database. This loosely coupled architecture provides data sharing and message exchange between processes

10 Parallel Server Option

11 Parts of the Oracle Server cont
Parallel Query Option: Computers holding more than one CPU (such as multiPentium Windows NT) could use those processors in solving independent portions of a query. An Oracle control unit breaks the query into pieces, and re-assembles the partial results.

12 Parallel Query Option

13 ORACLE Products SQL * Plus: User-Friendly-Interface, superset of SQL
Oracle-Forms GUI interface (forms, menu, libraries) Oracle-Reports Multimedia reporting (text, images, charts) Oracle Loader Migration facilitator, legacy data to Oracle Developer Integrated development environment: Designer Forms, Reports, Graphics, Book, Browser, Procedure builder, SQL*Plus, CASE Personal Oracle Full version of the Oracle server for the PC

14 ORACLE Architecture Terminology
An instance is a portion of the computers memory and a collection of processes required by Oracle to operate A database is the name of a reserved disk area A tablespace is a collection of datafiles (or tables) A table is a ‘file’ or container for application-specific data

15 ORACLE Architecture Terminology:
Rollback is the action of setting a data item to its previous value. For instance, assume an account holds $50, if a deposit of $1000 on this account is not completed the balance is set back to $50. Undo is similar to roll-back, the action of resetting a data item to its most recent previous value Dirty-block is a memory resident image of a disk block which has been changed by a process while in memory LRU flushes from memory the block which for the longest period of time has not been used

16 ORACLE Architecture

17 … … ORACLE Architecture A. What is inside of the database dictionary?
SQL> column comments format a35 wrap SQL> select * from dictionary; TABLE_NAME COMMENTS ALL_CATALOG All tables, views, synonyms, and sequences accessible to the user ALL_CLUSTERS Description of clusters accessible to the user ALL_CONSTRAINTS Constraint definitions on acce ssible tables … … 276 rows selected.

18 ORACLE Architecture B. What is inside of a datafile?
SQL> describe user_source Name Null? Type NAME NOT NULL VARCHAR2(30) TYPE VARCHAR2(12) LINE NOT NULL NUMBER TEXT VARCHAR2(2000) NOTE: You could use desc instead of describe

19 ORACLE Architecture

20 ORACLE Architecture 1. CREATE DATABASE Command
Used to create a database, making it available for general use, with the following options: o to establish a maximum number of instances, data files, o redo log files groups, or redo log file members o to specify names and sizes of data files and redo log files o to choose a mode of use for the redo log Warning: This command prepares a database for initial use and erases any data currently in the specified files. Only use this command when you understand its ramifications.

21 ORACLE Architecture CREATE DATABASE Command create database Oracle
controlfile reuse logfile 'D:\ORAWIN95\DATABASE\log1orcl.ora' size 200K reuse, 'D:\ORAWIN95\DATABASE\log2orcl.ora' size 200K reuse datafile 'D:\ORAWIN95\DATABASE\sys1orcl.ora' size 20M reuse autoextend on next 10M maxsize 200M character set WE8ISO8859P1;

22 ORACLE Architecture CREATE DATABASE Command (details)
CONTROLFILE REUSE reuses existing control files identified by the initialization parameter CONTROL_FILES LOGFILE specifies one or more files to be used as redo log files. MAXLOGFILES specifies the maximum number of redo log file groups that can ever be created for the database. MAXLOGMEMBERS specifies the max number of copies, for a redo log file group. MAXLOGHISTORY specifies the max number of archived redo log files for automatic media recovery of Oracle7 with the Parallel Server option. MAXINSTANCES specifies the max number of instances that can simultaneously have this database mounted and open.

23 ORACLE Architecture CREATE DATABASE Command (details)
ARCHIVELOG In this mode, the contents of a redo log file group must be archived before the group can be reused. NOARCHIVELOG In this mode, the contents of a redo log file group need not be archived before the group can be reused. CHARACTER SET specifies the character set the database uses to store data. DATAFILE specifies one or more files to be used as data files. These files all become part of the SYSTEM tablespace. AUTOEXTEND enables or disables the automatic extension of a datafile.

24 ORACLE Architecture How to create a TableSpace
CREATE TABLESPACE MyTabspace_2 DATAFILE 'd:\ORAWIN95\DATABASE\MyData2.dat' SIZE 10M DEFAULT STORAGE ( INITIAL K NEXT K MINEXTENTS 1 MAXEXTENTS 999 PCTINCREASE 10) ONLINE; How to eliminate a tablespace DROP TABLESPACE Mytabspace2 INCLUDING CONTENTS CASCADE CONSTRAINTS;

25 ORACLE Architecture Create additional tablespaces
-- USER_DATA: “Create user” command sets this as the default tablespace -- TEMPORARY_DATA: Create user sets this as the temporary tablespace -- ROLLBACK_DATA: For rollback segments create tablespace user_data datafile 'D:\ORAWIN95\DATABASE\usr1orcl.ora' size 3M reuse autoextend on next 5M maxsize 150M; create tablespace rollback_data datafile 'D:\ORAWIN95\DATABASE\rbs1orcl.ora' size 5M reuse autoextend on next 5M maxsize 150M; create tablespace temporary_data datafile 'D:\ORAWIN95\DATABASE\tmp1orcl.ora' size 2M reuse

26 ORACLE Architecture Rollback_data User_data rbs1orcl usr1orcl usr2orcl

27 ORACLE Architecture

28 … ORACLE Architecture Creating Rollback Segments
-- Create 16 rollback segments. Allows 16 concurrent users with open -- transactions updating the database. This should be enough???. create public rollback segment rb1 storage(initial 50K next 50K) tablespace rollback_data; create public rollback segment rb2 storage(initial 50K next 50K) create public rollback segment rb16 storage(initial 50K next 50K)

29 ORACLE Architecture

30 (under construction!) Architecture Summary: 1- tablespace 2- redo log 3- control files 4- user proc 5- server proc (dbwrt, ckpt, lgwr, smon, pmon, arch, lckn, reco) 6- sga (dict, datacache, redolog, sqlarea) 7- instances

31 SQL * Plus SQL*Plus is a user-friendly-interface imitating
a notepad. Its primary use is in supporting the construction of simple schema objects. o Normally used to easily interact with the Oracle server o Facilitates the prototyping of SQL commands o ”Quick and dirty” way of developing/testing PL-SQL and other Oracle objects

32 Using SQL * Plus to create Objects
Schema Objects users tables views sequences synonyms indexes clusters hash clusters Other schema objects such as packages, and triggers will be discussed later.

33 Using SQL * Plus to create Objects
Create User Command Creates a database user, or an account through which you can log in to the database. You can optionally assign the following properties to the user: default tablespace temporary tablespace quotas for allocating space in tablespaces profile containing resource limits Example: You can create the user MARIA by issuing the following statement: CREATE USER Maria IDENTIFIED BY Macarena DEFAULT TABLESPACE payroll_ts QUOTA 10M ON payroll_ts QUOTA 5M ON temp_ts QUOTA 5M ON system PROFILE accountant; Grant Connect, Resource to Maria;

34 Using SQL * Plus to create Objects
Schema Objects: TABLES Tables are the basic unit of data storage in an Oracle database. Data is stored in rows and columns. Typical datatypes are: CHAR, VARCHAR2, NUMBER, DATE A row is a collection of column information corresponding to a single record. You can optionally specify rules for each column of a table. These rules are called integrity constraints. Example: NOT NULL Once you create a table, you insert rows of data using SQL statements. Table data can then be queried, deleted, or updated using SQL.

35 Using SQL * Plus to create Objects
Create Table Command Example I. To define the EMP table owned by SCOTT, you could issue the following statement: CREATE TABLE scott.emp ( empno NUMBER CONSTRAINT pk_emp PRIMARY KEY, ename VARCHAR2(10) CONSTRAINT nn_ename NOT NULL CONSTRAINT upper_ename CHECK (ename = UPPER(ename)), job VARCHAR2(9), mgr NUMBER CONSTRAINT fk_mgr REFERENCES scott.emp(empno), hiredate DATE DEFAULT SYSDATE, sal NUMBER(10,2) CONSTRAINT ck_sal CHECK (sal > 500), comm NUMBER(9,0) DEFAULT NULL, deptno NUMBER(2) CONSTRAINT nn_deptno NOT NULL CONSTRAINT fk_deptno REFERENCES scott.dept(deptno) ) PCTFREE 5 PCTUSED 75 ;

36 Using SQL * Plus to create Objects
Create Table Command Notes 1- This table contains 8 columns. Ex: EMPNO column is of datatype NUMBER and has an associated integrity constraint named PK_EMP. 2- HIRDEDATE column is of datatype DATE and has a default value of SYSDATE. 3- PCTFREE of 5 indicates that 5% of space is reserved for future updates 4- PCTUSED of 75, says that a minimum of 75% of the table should be used on each data block 5- The constraint on the mgr field indicates that such a value (mgr’s id) must also be found in the scott.emp table (a recursive reference)

37 Using SQL * Plus to create Objects
Create Table Command. Typical data types

38 Using SQL * Plus to create Objects
Create Table Command. Example II. Assuming you have the parallel query option, then the fastest method to create a table that has the same columns as the EMP table, but only for those employees in department 10, is to issue a command similar to the following: CREATE TABLE emp_tmp UNRECOVERABLE PARALLEL (DEGREE 3) AS SELECT * FROM emp WHERE deptno = 10; Notes 1- The UNRECOVERABLE keyword speeds up table creation because there is no overhead in generating and logging redo information. 2- Parallelism speeds up the creation of the table. 3- After the table is created, querying the table is also faster because the same degree of parallelism is used to access the table.

39 ORACLE: PL/SQL What is PL/SQL ?
PL/SQL stands for Procedural extensions to SQL. It adds programming capabilities to SQL. It is a block-structured language with a syntax similar to C Normally used on the server-side, however some client-side products (ORA-FORMS) could also have it as a built-in part. It is not a stand-alone language

40 PL/SQL Architecture CLIENT SIDE CODE ORACLE SERVER CODE ...
VisualBasic Java C, C++ COBOL MS-Access PowerSoft People’s Soft SAP HTML + scripts (JavaScript, Perl, VBS) ... ORACLE SERVER CODE PL-SQL (Oracle 7, 8, 8i) Java (Oracle8i)

41 PL/SQL Architecture

42 PL/SQL Programming PL/SQL = SQL + standard procedural programming
Support for procedures, functions, flow-control statements, declared variables, user-defined types. A PL/SQL program is either a procedure, a function, or an anonymous block Anonymous blocks are nameless fragments of code normally executed as script files

43 PL/SQL Programming Block-Structure Declaration Section
Execution Section Exception Section

44 PL/SQL: Example1 -- CELCIUS1 (Lowest temp, Highest Temp) Converts Fahrenheit temperatures to Celcius. Results are saved -- into TEMP, a table predefined to hold (number, number, text) CREATE OR REPLACE PROCEDURE Celcius1 (Low IN NUMBER, High IN NUMBER) IS Celcius number; Fahren number; Msg varchar2(55); BEGIN DELETE FROM temp; FOR Fahren IN Low..High LOOP Celcius:= ROUND ( (Fahren -32)*5/9 ); IF (Fahren < 30 ) THEN Msg := 'Too cold'; ELSIF (Fahren < 70 ) THEN Msg := 'Cold'; ELSIF (Fahren <80) THEN Msg := 'Very nice'; ELSE Msg := 'Hot'; END IF; INSERT INTO Temp VALUES (Fahren, Celcius, Msg); END LOOP; END; Create table Temp (…)

45 PL/SQL: Example1 Test the program using the following SQL*PLUS commands SQL> delete from Temp; SQL> execute Celcius1(0,100); SQL> select * from temp; F F F3 …… Cold Cold Very nice Very nice Very nice Very nice Very nice Very nice Very nice Very nice Very nice Very nice Hot Hot

46 PL/SQL: Example1 A second way of testing a stored procedures is to call it from an anonymous block. Type in the following code sql> edit CelciusTest DECLARE BEGIN delete from Temp; Celcius1 (0,100); END; sql> / sql > select * from Temp;

47 PL/SQL: Example2 The COMPANY database

48 PL/SQL: Example2 -- WorkLoad
-- Employees are either assigned/removed to/from a project CREATE or REPLACE PROCEDURE WorkLoad ( p_action VARCHAR2, p_ssn VARCHAR2, p_pno NUMBER, p_hours NUMBER:= 40 ) IS BEGIN IF (p_action = 'ASSIGN' ) THEN INSERT INTO works_on VALUES (p_ssn, p_pno, p_hours); ELSIF (p_action = 'REMOVE') THEN DELETE FROM works_on WHERE (essn = p_ssn) AND (pno = p_pno); END IF; END;

49 PL/SQL: Example2 Testing the procedure with an anonymous block.
SQL > edit workLoadTest DECLARE BEGIN WorkLoad('ASSIGN', ,10,1.7); END; sql> / sql> select * from Works_On;

50 PL/SQL Programming PL/SQL Syntax

51 PL/SQL Programming Defining/Initializing Variables
Salary NUMBER(10,2); DeptNumber NUMBER := 17; LastName VARCHAR2(20); Sex CHAR := ‘F’; JobType CHAR(15); TaxDate DATE := ‘15-APR-99’; Most common data types are: NUMBER, VARCHAR2, DATE

52 PL/SQL Programming Defining Variables %TYPE Declares a variable with
respect to a Table.Column Bonus EMP.Sal%TYPE; EMP EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO 7369 SMITH CLERK DEC 7499 ALLEN SALESMAN FEB 7521 WARD SALESMAN FEB Number(7,2)

53 PL/SQL Programming Defining Variables
%ROWTYPE Defines a record with respect to an existing table definition TempEmp EMP%ROWTYPE; Refers to fields using: TempEmp.Salary EMP EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO 7369 SMITH CLERK DEC 7499 ALLEN SALESMAN FEB 7521 WARD SALESMAN FEB

54 PL/SQL Programming Creating/Debugging a Stored PL/SQL Function
This example shows how to create an debug a PL/SQL stored function using SQL*Plus CREATE or REPLACE FUNCTION IsFile ( MyTable IN VARCHAR2 ) RETURN ( boolean ) IS result user_tables.table_name%TYPE; BEGIN SELECT table_name INTO result FROM user_tables WHERE table_name = UPPER(MyTable); RETURN true; EXCEPTION WHEN No_Data_Found THEN RETURN false; END; / Intentional error

55 Line and column where error was found
PL/SQL Programming Creating/Debugging a Stored PL/SQL Function Warning: Function created with compilation errors. SQL> show errors Errors for FUNCTION ISFILE: LINE/COL ERROR 1/47 PLS-00103: Encountered the symbol "(" when expecting one of the following:<an identifier> <a double-quoted delimited-identifier> LONG_ double SQL> EDIT IsFile.sql Line and column where error was found Use the editor to correct each error in the script file

56 PL/SQL Programming Creating/Debugging a Stored PL/SQL Function
-- Testing ISFILE( ) function, using an anonymous block -- Script: isFileTest. Author: V.Matos May 22, 1999. clear screen DECLARE -- put file names here theFile user_tables.table_name%TYPE := 'EMPXYZ'; BEGIN delete from temp; if ISFILE(theFile) then insert into temp values (1,1, theFile || ' exists'); else insert into temp values (2,2, theFile || ' does NOT exist'); end if; END; / select * from TEMP; clear buffer -- erase this line and try again

57 PL/SQL Programming Running the anonymous script
Testing the Anonymous Procedure SQL> @isFileTest procedure successfully executed SQL> select * from TEMP; F1 F2 F3 EMPXYZ does NOT exist Running the anonymous script Results are placed into the TEMP table

58 PL/SQL Programming -- RaiseSalary: Function increases salary of certain employee by PctRaise CREATE or REPLACE FUNCTION RaiseSalary ( EmpSsn number, PctRaise number ) RETURN number IS NewSalary number; OldSalary number; BEGIN SELECT Salary INTO OldSalary FROM Employee WHERE SSN = EmpSSN; NewSalary:= OldSalary * (1 + PctRaise); UPDATE Employee SET Salary = NewSalary WHERE SSN = EmpSsn; RETURN NewSalary; EXCEPTION WHEN No_Data_Found THEN INSERT INTO temp VALUES (EmpSSN, ‘Not found’,Null); RETURN -1; END; Default type is ‘IN’ Returned value

59 PL/SQL Programming -- Anonymous proc. to test the RAISESALARY routine
-- Script: raiseSalaryTest Author: VMatos 20-MAY-99 DECLARE theSalary EMPLOYEE.SALARY%TYPE; BEGIN delete from TEMP; theSalary := raiseSalary( , 0.10); insert into TEMP values ( , theSalary, NULL); END; / select * from TEMP; clear buffer /

60 PL/SQL Programming PROCEDURE which returns several results
CREATE or REPLACE PROCEDURE GetEmpNameSal ( EmpSSN IN number, EmpName OUT varchar2, EmpSalary OUT number ) IS BEGIN select Lname ||', '|| Fname, Salary into EmpName, EmpSalary from Employee where SSN = EmpSSN; EXCEPTION WHEN No_Data_Found THEN insert into TEMP values (EmpSSN, ‘ERROR. Emp not found’,NULL); EmpName:= '***'; EmpSalary:= -1; END; OUT variables carry results outside of the procedure

61 PL/SQL Programming Testing the getEmpNameSal procedure.
-- Script: getEmpNameSalTest DECLARE theName TEMP.F3%TYPE; theSalary EMPLOYEE.SALARY%TYPE; BEGIN delete from TEMP; getEmpNameSal ( , theName, theSalary); insert into temp values ( , theSalary, theName); END; / F F F3 SMITH, John

62 PL/SQL Programming Anonymous Procedures
The following anonymous procedure performs the following tasks: Executes stored proc. GetEmpNameSal to obtain the name and salary of the employee whose SSN is Results are saved into the TEMP table. Invokes the function RaiseSalary to increase the employee’s salary by 10%. Again, a new line is added to TEMP reporting the new salary value.

63 PL/SQL Programming Anonymous Procedures
-- Name: Test2Routines.Sql -- Anonymous Procedure to Test STORED routines -- Uses: proc. GetEmpName,and func. RaiseSalary -- table TEMP (already created with three columns) DECLARE EmpName varchar(20); mSalary number; BEGIN DELETE FROM Temp; GetEmpNameSal ( , EmpName, mSalary); INSERT INTO Temp VALUES ( , mSalary, EmpName); mSalary:= RaiseSalary( , 0.10); END; Local memory variables defined to store the Emp name and salary retrieved using the stored procedure

64 PL/SQL Programming Running the anonymous script
Testing the Anonymous Procedure SQL> @ Test2Routines procedure successfully executed SQL> select * from TEMP; F F F2 Smith, John Smith, John Running the anonymous script Results are placed into the TEMP table.

65 PL/SQL Programming Invoking a Stored Function from a SQL Query
The numbers in the BASEBALL table are hard to read. A function BigBucks(...) is called to facilitate the reading of the big numbers in the table SQL> select * from BASEBALL; PNAME PSALARY A. Belle K. Griffey B. Bonds D. Cone P. Butterfingers

66 PL/SQL Programming Do this just in case you do not have the BaseBall table! drop table BASEBALL; create table BaseBall (Pname varchar2(20), PSalary varchar2(30)); insert into BaseBall values ('A. Belle', ); insert into BaseBall values ('K. Griffey', ); insert into BaseBall values ('B. Bonds', ); insert into BaseBall values ('D. Cone', ); insert into BaseBall values ('P. Butterfingers', 900); select * from BaseBall; /

67 PL/SQL Programming Invoking a Stored Function from a SQL Query
-- Playball.sql -- This is a small SCRIPT (not an anonymous proc.) -- The pretty function is called from the SQL comnd column psalary format column bigbucks(psalary) format a30 select pname, psalary, BigBucks(psalary) from baseball; PNAME PSALARY BIGBUCKS(PSALARY) A. Belle Millions K. Griffey Billions B. Bonds Billions D. Cone Thousands P. Butterfingers Peanuts

68 PL/SQL Programming A Stored Function for Beautifying Big Numbers
Create or Replace Function BIGBUCKS ( salary number ) Return varchar IS Billion number := ; Million number := ; Thousand number := ; Message varchar(30); Dollars number(6,2); begin if (salary >= Billion) then Dollars:= salary / billion; message:= LPAD(to_char(dollars),8) || ' Billions'; return (message); elsif (salary >= Million) then Dollars:= salary / Million; message:= LPAD(to_char(dollars),8) || ' Millions'; elsif (salary >= Thousand) then Dollars:= salary / Thousand; message:= LPAD(to_char(dollars),8) || ' Thousands'; else message:= to_char(Salary,'999.00'); message:= LPAD(message,8)||' Peanuts'; end if; end; LPAD( ) adds n spaces on on left side of the string Numeric format

69 PL/SQL Programming Creating a Store Procedure: A dir-like Routine
1. Type the following code into a text file called: dirStor.sql create or replace PROCEDURE dirStor IS firstcol boolean; line varchar2(400); tableName varchar2(20); columnName varchar2(20); CURSOR data IS select table_name, column_name from user_col_comments;

70 PL/SQL Programming BEGIN delete from dirList; line:= ' ';
tableName:= ' '; FOR d IN data LOOP if (tableName <> d.table_name) then if (line <> ' ') then line:= line || ');' ; end if; insert into dirList values (line); tableName:= d.table_name; Line:= UPPER(d.table_name) || ' (' ; firstcol:= true; if NOT (firstcol) then line:= Line || ', '; firstcol:= false; line:= line|| LOWER(d.column_Name); END LOOP; END;

71 PL/SQL Programming Type-in the following lines into a file called: dir.sql. Put the file in the directory c:\bin\orawin95 -- Script: dir.sql execute dirStor select * from dirList; NOTE: dirList is a user-created table. You need to make the table before using it. Type the following SQL statement: CREATE TABLE dirList ( MyTables VARCHAR2(80) );

72 PL/SQL Programming An example of how to use the dir routine is given below: PL/SQL procedure successfully completed. MyTables DEPARTMENT (dname, dnumber, mgrssn, mgrstartdate); DEPENDENT (essn, dependent_name, sex, bdate, relationship); MYLOG (num1, msg); TEMP (F1, F2, F3); PROJECT (pname, pnumber, plocation, dnum); WORKS_ON (essn, pno, hours); 7 rows selected.

73 PL/SQL Programming Writing a Procedure to (a) Securely Insert Works_On records (b) Verify Potential Business Rules The procedure Insert_WorksOn() is invoked to add new records to the Works_On table in a very controlled way. Each call to the function provides the programmers authentication code and data (SSN, ProjNumb, Hour). For example: Result:= Insert_WorkOn(‘Dilbert’, ,10,40) If the programmer ‘Dilbert’ is not in the list of peoples authorized to make insertions, the operation is rejected and MYLOG file is update with a rejection message If the SSN and PNO provided are already in the Works_On table the current insertion is rejected and the log file is updated The function returns a numeric code 1, -1, -2, etc. to indicate the status of the execution. This number is stored into the variable Result (1: success, negative values: problems).

74 PL/SQL Programming To execute the examples in this section you may need to do the following DML changes. create table WORKS_ON ( essn char(9), pno number, hours number(5,1), CONSTRAINT pk_workson_key PRIMARY KEY (essn, pno)); drop table Valid_Operators; create table VALID_OPERATORS (Operator_Name varchar2(20) ); insert into VALID_OPERATORS values ('Dilbert'); insert into VALID_OPERATORS values ('Calbert');

75 PL/SQL Programming create or replace
FUNCTION Insert_WorksOn ( Programmer_Id varchar2, EmployeeSsn number, ProjectNumber number, WeeklyHours number ) RETURN number IS Programmer_Name varchar(20); Message varchar(70); BEGIN -- First block: Is the programmer allowed to insert records? -- Note: All code goes into one BEGIN...END block. select Operator_Name into Programmer_Name from Valid_Operators where Operator_Name = Programmer_Id; EXCEPTION when No_Data_Found then Insert into Mylog values (Programmer_Id, 'ERROR** unauthorized used of function'); RETURN -1; END; -- first block

76 PL/SQL Programming -- INSERTWORKSON cont.
-- Second block: Here other conditions could be checked -- before accepting record into the works_on table BEGIN insert into Works_On values (EmployeeSsn, ProjectNumber, WeeklyHours); RETURN 1; EXCEPTION When DUP_VAL_ON_INDEX then Message:= ' Emp ' || to_char(EmployeeSsn) || ' already in proj ' || to_char(ProjectNumber); insert into Mylog values (NULL, Message); RETURN -2; When Others then Message:= ' Emp ' || to_char(EmployeeSsn) || ' not assigned to ' || RETURN -3; END; -- second block END;

77 PL/SQL Programming Mylog Employee
--TESTING THE INSERT_WORKSON FUNCTION DECLARE theResultCode NUMBER; BEGIN delete from mylog; theResultCode := Insert_WorksOn ('Dilbert', , 10,1.2); insert into mylog values (' workson 10', theResultCode); END; COL COL2 Emp already in proj. 10 workson ESSN PNO HOURS Mylog Employee

78 PL/SQL Programming Result:= Delete_WorkOn(‘Dilbert’,123456789,1)
Writing a Secure Procedure to Delete a Works_On record The procedure Delete_WorksOn() is invoked to remove records from the Works_On table. In the function-call the programmers authentication code and the Works_On key field(s) are supplied. For example: in the following call, programmer ‘Dilbert’ asks to remove employee from proj. 1. Result:= Delete_WorkOn(‘Dilbert’, ,1) If the programmer ‘Dilbert’ is not authorized to make such a deletion, the operation is rejected and MYLOG file is update with a rejection message If employee is not in the Works_On table the current deletion is rejected and the log file is updated otherwise, the record is eliminated The function returns a numeric code 1, -1, -2, etc. to indicate the status of the execution. (1: success, negative values: problems).

79 PL/SQL Programming create or replace
FUNCTION Delete_WorksOn ( Programmer_Id varchar2, EmployeeSsn number, ProjectNumb number ) RETURN number IS Programmer_Name varchar(20); Message varchar(70); BEGIN -- First block: Verify that programmer is allowed to delete -- Note: all code goes in one BEGIN...END block select Operator_Name into Programmer_Name from Valid_Operators where Operator_Name = Programmer_Id; EXCEPTION when No_Data_Found then Message:= 'Programmer not allowed to ' || 'delete Works_On rec.'; Insert into Mylog values(Programmer_Id, Message ); RETURN -1; END; -- first block

80 PL/SQL Programming BEGIN delete from Works_On where Essn= EmployeeSsn
-- DELETE_WORKSON script cont. ---Second block: Other conditions could be checked here -- before deleting the record BEGIN delete from Works_On where Essn= EmployeeSsn AND Pno = ProjectNumb; if (sql%notfound) then Message:=' ** ' || to_char(EmployeeSsn) || ' / ' || to_char(ProjectNumb) || ' not found '; insert into Mylog values (NULL, Message); RETURN -2; end if; RETURN 1;

81 PL/SQL Programming When Others then
-- DELETE_WORKSON script cont. ---Second block: Other conditions could be checked here -- before deleting the record EXCEPTION When Others then Message:= ' *** ' || to_char(EmployeeSsn) || ' remains in Works_On'; insert into Mylog values (NULL, Message); RETURN -3; END; -- second block END;

82 PL/SQL Programming --TESTING THE DELETE_WORKSON FUNCTION
-- DELETE_WORKSON script cont. ---Second block: Other conditions could be checked here -- before deleting the record --TESTING THE DELETE_WORKSON FUNCTION DECLARE theCode Number; BEGIN delete from mylog; theCode := delete_WorksOn ('Dilbert', , 10); insert into mylog values ('After delete ', theCode); END; / select * from mylog; select * from works_on where essn like '123%';

83 PL/SQL Programming Writing a Secure Procedure to Update Project records The procedure Update_Project( ) is used to modify existing records in the Project table. Individual records are located using the Pnumber values as search-key. The updating of projects occurs in the context of a function call such as the example bellow. The arguments passed to the function are: Programmer_Id, project number, name, location; and number of responsible department. Result:= Update_Project(‘Dilbert’,1,‘Cerveza XXX’,‘Margarita’,NULL); Each project record to be updated must include the project number More than one field could be updated in a single function call Project numbers are not changeable (instead delete whole rec. and re-insert with a new number) If the programmer ‘Dilbert’ is authorized to make deletion, the operation is rejected If there is no record for project number 1, the current update is rejected If a field is not going to be updated, the word NULL must be written in the proper column The function returns a numeric code 1, -1, -2, etc. to indicate the status of the execution.

84 PL/SQL Programming Writing a Secure Procedure to Update Project records create or replace FUNCTION Update_Project( Programmer_Id number, ProjectNumber number, ProjectName varchar, ProjectLocation varchar, DepartmentNumber number ) RETURN number IS Programmer_Name varchar2(20); Message varchar2(70); VarPnumber number;

85 PL/SQL Programming Writing a Secure Procedure to Update Project records cont. BEGIN -- First block: Is programmer allowed to update projects? -- NOTE: all code goes in one BEGIN...END block select Operator_Name into Programmer_Name from Valid_Operators where Operator_Name = Programmer_Id; EXCEPTION when No_Data_Found then Message:= 'Programmer not allowed to ' || 'update Projects'; Insert into Mylog values (Programmer_Id, Message); RETURN -1; END; -- first block

86 PL/SQL Programming Writing a Secure Procedure to Update Project records cont. -- Second block: Verify there is a project record matching -- Pnumber key. If the field is not NULL, modify using given -- parameter BEGIN select Pnumber into VarPnumber from Project where Pnumber= ProjectNumber; if (ProjectName is not NULL) then update Project set Pname= ProjectName where Pnumber = ProjectNumber; end if; if (ProjectLocation is not NULL) then set Plocation= ProjectLocation End if; if (DepartmentNumber is not NULL) then set Dnum = DepartmentNumber RETURN 1 ; -- success !

87 PL/SQL Programming Writing a Secure Procedure to Update Project records cont. -- Deal with Update problems here EXCEPTION When No_Data_Found then Message:= ' Project ' || to_char(ProjectNumber) || ' does not exist '; insert into Mylog values (NULL, Message); RETURN -2; When Others then Message:= ' Project ' || to_char(ProjectNumber) || ' can not be updated '; RETURN -3; END; -- second block END;


Download ppt "An Introduction to Oracle"

Similar presentations


Ads by Google