Distributed Database Applications

Preview:

DESCRIPTION

Distributed Database Applications. COSC 5050 Week Seven. Outline. Dynamic SQL and dynamic PL/SQL NDS statements EXCUTE IMMEDIATE OPEN FOR Oracle's object features Globalization and localization. Dynamic SQL and PL/SQL. Constructed and executed at runtime - PowerPoint PPT Presentation

Citation preview

Distributed Database Applications

COSC 5050Week Seven

Jiangping WangWebster University Distributed Database Applications

Outline

Dynamic SQL and dynamic PL/SQLNDS statements

EXCUTE IMMEDIATEOPEN FOR

Oracle's object featuresGlobalization and localization

Jiangping WangWebster University Distributed Database Applications

Dynamic SQL and PL/SQL

Constructed and executed at runtime

Stored in character strings that are input to, or built by, the program at runtime Execute DDL statementsBuild back-ends applications

DBMS_SQL packageNative Dynamic SQL (NDS)

Jiangping WangWebster University Distributed Database Applications

NDS Statement

Native dynamic SQLIs an integral part of the PL/SQL language itselfSignificantly simpler to user and faster

EXECUTE IMMEDIATE statementExecute a specified SQL statement immediately

OPEN FOR statementPerform multiple-row dynamic queries

Jiangping WangWebster University Distributed Database Applications

DDL, DML, Anonymous Blocks

declare l_sqlstring varchar2(200); l_plsqlblock varchar2(200);begin execute immediate 'create table execute_table (col1 varchar(10))'; for l_counter in 1..10 loop l_sqlstring := 'insert into execute_table values (''row ' || l_counter || ''')'; execute immediate l_sqlstring; end loop; l_plsqlblock := 'begin for l_rec in (select * from execute_table) loop dbms_output.put_line(l_rec.col1); end loop; end;'; execute immediate l_plsqlblock; execute immediate 'drop table execute_table';end;

Jiangping WangWebster University Distributed Database Applications

EXECUTE IMMEDIATE Statement

execute immediate

'create index emp_u_1 on employee (last_name)';

create or replace procedure execddl

(ddl_string in varchar2)

is

begin

execute immediate ddl_string;

end;

exec execddl(

'create index emp_u_i on employee(last_name)');

Jiangping WangWebster University Distributed Database Applications

EXECUTE IMMEDIATE Statement

CREATE OR REPLACE FUNCTION tabCount ( tab IN VARCHAR2, whr IN VARCHAR2 := NULL, sch IN VARCHAR2 := NULL) RETURN INTEGERIS retval INTEGER;BEGIN EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ' || NVL (sch, USER) || '.' || tab || ' WHERE ' || NVL (whr, '1=1') INTO retval; RETURN retval;END;/

if tabcount ('emp', 'deptno = ' || v_dept) > 100 then dbms_output.put_line('growing fast!');end if;

Jiangping WangWebster University Distributed Database Applications

EXECUTE IMMEDIATE Statement

Bind VariableCREATE OR REPLACE FUNCTION updNVal ( tab IN VARCHAR2, col IN VARCHAR2, val IN NUMBER, whr IN VARCHAR2 := NULL, sch IN VARCHAR2 := NULL) RETURN PLS_INTEGERISBEGIN EXECUTE IMMEDIATE 'UPDATE ' || NVL (sch, USER) || '.' || tab || ' SET ' || col || ' = :the_value WHERE ' || NVL (whr, '1=1') USING val; RETURN SQL%ROWCOUNT;END;/

PL/SQL engine replaces the various placeholders with the values in the USING clause

Jiangping WangWebster University Distributed Database Applications

EXECUTE IMMEDIATE Statement

Bind VariableCREATE OR REPLACE PROCEDURE run_9am_procedure ( id_in IN employee.employee_id%TYPE, hour_in IN INTEGER)IS v_apptcount INTEGER; v_name VARCHAR2 (100);BEGIN EXECUTE IMMEDIATE 'BEGIN ' || TO_CHAR (SYSDATE, 'DAY') || '_set_schedule (:id, :hour, :name, :appts); END;' USING IN id_in, IN hour_in, OUT v_name, OUT v_apptcount;

DBMS_OUTPUT.put_line ( 'Employee ' || v_name || ' has ' || v_apptcount || ' appointments on ' || TO_CHAR (SYSDATE));END;/

Jiangping WangWebster University Distributed Database Applications

OPEN FOR Statement

create or replace procedure show_parts_inventory (

parts_table in varchar2,

where_n in varchar2 := null)

is

type query_curtype is ref cursor;

dyncur query_curtype;

begin

open dyncur for

‘select * from ’ || parts_table

‘where ’ || nvl(where_in, ‘1=1’);

end;

Extend cursor variables to support dynamic SQL

Jiangping WangWebster University Distributed Database Applications

OPEN FOR Statementcreate or replace procedure show_employee ( table_in in varchar2, where_in in varchar2 := null)is type query_curtype is ref cursor; dyncur query_curtype; emp employee%rowtype;begin open dyncur for 'select * from ' || table_in || ' where ' || nvl (where_in, '1=1'); dbms_output.put_line('Employee list:'); loop fetch dyncur into emp; exit when dyncur%notfound; dbms_output.put_line(emp.lname || ' ' || emp.fname); end loop; close dyncur;end;/

Jiangping WangWebster University Distributed Database Applications

Multirow Queries with Cursor Variables

CREATE OR REPLACE PROCEDURE showcol ( tab IN VARCHAR2, col IN VARCHAR2, whr IN VARCHAR2 := NULL)IS TYPE cv_type IS REF CURSOR; cv cv_type; val VARCHAR2(32767); BEGIN OPEN cv FOR 'SELECT ' || col || ' FROM ' || tab || ' WHERE ' || NVL (whr, '1 = 1'); LOOP FETCH cv INTO val; EXIT WHEN cv%NOTFOUND; IF cv%ROWCOUNT = 1 THEN DBMS_OUTPUT.PUT_LINE (RPAD ('-', 60, '-')); DBMS_OUTPUT.PUT_LINE ('Contents of '||UPPER(tab)||'.'||UPPER(col)); DBMS_OUTPUT.PUT_LINE (RPAD ('-', 60, '-')); END IF; DBMS_OUTPUT.PUT_LINE (val); END LOOP; CLOSE cv;END;/

Jiangping WangWebster University Distributed Database Applications

FETCH into VariablesDeclare

type cv_type is ref cursor;

cv cv_type;

mega_bucks company.ceo_compensation%type;

achieved_by company.cost_cutting%type;

Begin

Open cv for

‘select ceo_compensation, cost_curtting from company where ’ || nvl (whr, ‘1=1’);

loop

fetch cv into mega_bucks, achieved_by;

Jiangping WangWebster University Distributed Database Applications

FETCH into RecordsDeclare

type cv_type is ref cursor;

cv cv_type;

ceo_info company%rowtype;

Begin

Open cv for

‘select * from from company where ’ || nvl (whr, ‘1=1’);

loop

fetch cv into ceo_info;

Jiangping WangWebster University Distributed Database Applications

FETCH into Recordscreate or replace package company_strucis type dynsql_curtype is ref cursor; type ceo_info_rt is record ( mega_bucks company.ceo_compensation%type, achieved_by company.cost_cutting%type);

declare cv company_struc.dynsql_curtype; rec company_struc.ceo_info_rt;begin open cv for ‘select ceo_eompensatin, cost_cutting from company

where ’ || nvl (whr, ‘1=1’); loop fetch cv into rec;

Jiangping WangWebster University Distributed Database Applications

The USING Clause in OPEN FOR

OPEN cv FOR 'SELECT ' || col || ' FROM ' || tab || ' WHERE ' || dtcol || ' BETWEEN TRUNC (:startdt) AND TRUNC (:enddt)' USING dt1, NVL (dt2, dt1+1); LOOP FETCH cv INTO val; EXIT WHEN cv%NOTFOUND; IF cv%ROWCOUNT = 1 THEN …

Jiangping WangWebster University Distributed Database Applications

Binding Variables

Binding utilizes placeholders and USING clauseEXECUTE IMMEDIATE

'UPDATE ' || tab || ' SET sal = :new_sal' USING v_sal;

Concatenation adds values directly to the SQL stringEXECUTE IMMEDIATE

'UPDATE ' || tab || ' SET sal = ' || v_sal;

Binding is fasterBinding is easier to write and maintainBinding negates the chance of code injection

Jiangping WangWebster University Distributed Database Applications

Code InjectionCREATE OR REPLACE PROCEDURE get_rows ( ssn_in in VARCHAR2)IS l_where VARCHAR2(32767);BEGIN l_where := 'ssn = ' || ssn_in; EXECUTE IMMEDIATE 'DECLARE l_row employee%ROWTYPE; BEGIN SELECT * INTO l_row FROM employee WHERE ' || l_where || '; dbms_output.put_line(l_row.lname); END;';END get_rows;/

Jiangping WangWebster University Distributed Database Applications

Avoid Code InjectionCREATE OR REPLACE PROCEDURE get_rows ( ssn_in in VARCHAR2)IS l_where VARCHAR2(32767);BEGIN l_where := 'ssn = :ssnumber'; EXECUTE IMMEDIATE 'DECLARE l_row employee%ROWTYPE; BEGIN SELECT * INTO l_row FROM employee WHERE ' || l_where || '; dbms_output.put_line(l_row.lname); END;' USING ssn_in;END get_rows;/

Jiangping WangWebster University Distributed Database Applications

Argument ModesIN, OUT, IN OUT

create or replace procedure wrong_incentive( company_in in integer, new_layoffs in number)is sql_string varchar2(2000); sal_after_layoffs number;begin sql_string := ‘update ceo_compensation set salary = salary + 10 * :layoffs where company_id = :company returning salary into :newsal’; execute immediate sql_string using new_layoffs, company_in, out sal_after_layoffs; dbms_output.put_line (ceo compensation after latest round of layoffs $’ || sal_after_layoffs);end;

Jiangping WangWebster University Distributed Database Applications

Dynamic SQL and Static SQL

More versatile than plain embedded SQL programsCan be built interactively with input from users having little or no knowledge of SQL

For highly flexible applications

Require complex codingUse of special data structuresMore runtime processing

Jiangping WangWebster University Distributed Database Applications

Oracle's Object Features

Object programming featuresCreating base type and subtypeCreating objectStoring, retrieving, and using persistent objects

Jiangping WangWebster University Distributed Database Applications

Object Programming Features

Jiangping WangWebster University Distributed Database Applications

Object Programming Features

Jiangping WangWebster University Distributed Database Applications

Library Catalog Type Hierarchy

Jiangping WangWebster University Distributed Database Applications

Creating Base Type

CREATE OR REPLACE TYPE catalog_item_t AS OBJECT ( id INTEGER, title VARCHAR2(4000), NOT INSTANTIABLE MEMBER FUNCTION ck_digit_okay RETURN BOOLEAN, MEMBER FUNCTION print RETURN VARCHAR2) NOT INSTANTIABLE NOT FINAL;/

Jiangping WangWebster University Distributed Database Applications

Creating Subtype

CREATE OR REPLACE TYPE book_t UNDER catalog_item_t ( isbn VARCHAR2(13), pages INTEGER, CONSTRUCTOR FUNCTION book_t ( id IN INTEGER DEFAULT NULL, title IN VARCHAR2 DEFAULT NULL, isbn IN VARCHAR2 DEFAULT NULL, pages IN INTEGER DEFAULT NULL) RETURN SELF AS RESULT, OVERRIDING MEMBER FUNCTION ck_digit_okay RETURN BOOLEAN, OVERRIDING MEMBER FUNCTION print RETURN VARCHAR2);/

Jiangping WangWebster University Distributed Database Applications

Creating Subtype

CREATE OR REPLACE TYPE serial_t UNDER catalog_item_t ( issn VARCHAR2(10), open_or_closed VARCHAR2(1), CONSTRUCTOR FUNCTION serial_t ( id IN INTEGER DEFAULT NULL, title IN VARCHAR2 DEFAULT NULL, issn IN VARCHAR2 DEFAULT NULL, open_or_closed IN VARCHAR2 DEFAULT NULL) RETURN SELF AS RESULT, OVERRIDING MEMBER FUNCTION ck_digit_okay RETURN BOOLEAN, OVERRIDING MEMBER FUNCTION print RETURN VARCHAR2) NOT FINAL;/

Jiangping WangWebster University Distributed Database Applications

Creating Object

DECLARE generic_item catalog_item_t; abook book_t;BEGIN abook := NEW book_t(title => 'Out of the Silent Planet', isbn => '0-6848-238-02'); generic_item := abook; DBMS_OUTPUT.PUT_LINE('BOOK: ' || abook.print()); DBMS_OUTPUT.PUT_LINE('ITEM: ' || generic_item.print());END;

Jiangping WangWebster University Distributed Database Applications

Storing Persistent Objects CREATE TABLE catalog_items OF catalog_item_t (CONSTRAINT catalog_items_pk PRIMARY KEY (id));

CREATE TABLE my_writing_projects ( project_id INTEGER NOT NULL PRIMARY KEY, start_date DATE, working_title VARCHAR2(4000), catalog_item catalog_item_t);

DESC catalog_itemsdesc my_writing_projects

INSERT INTO catalog_items VALUES (NEW book_t(10003, 'Perelandra', '0-684-82382-9', 222));

INSERT INTO catalog_items VALUES (NEW serial_t(10004, 'Time', '0040-781X', 'O'));

Jiangping WangWebster University Distributed Database Applications

The VALUE functionAccepts a single argument, which must be a table alias in the current FROM clauseReturns an object of the type on which the table is defined

Retrieving Persistent Objects

SELECT VALUE(c) FROM catalog_items c;

SELECT VALUE(c).id, VALUE(c).print() FROM catalog_items c;

Jiangping WangWebster University Distributed Database Applications

Retrieving Persistent Objects

DECLARE catalog_item catalog_item_t; CURSOR ccur IS SELECT VALUE(c) FROM catalog_items c;BEGIN OPEN ccur; FETCH ccur INTO catalog_item; DBMS_OUTPUT.PUT_LINE('I fetched item #' || catalog_item.id); CLOSE ccur;END;

Jiangping WangWebster University Distributed Database Applications

The TREAT functionTreat a generic base type object as the more narrowly defined subtype object

Object Downcasting

DECLARE book book_t; catalog_item catalog_item_t := NEW book_t();BEGIN book := TREAT(catalog_item AS book_t);END;/

Jiangping WangWebster University Distributed Database Applications

Test Object Type DECLARE CURSOR ccur IS SELECT VALUE(c) item FROM catalog_items c; arec ccur%ROWTYPE;BEGIN FOR arec IN ccur LOOP CASE WHEN arec.item IS OF (book_t) THEN DBMS_OUTPUT.PUT_LINE('Found a book with ISBN ' || TREAT(arec.item AS book_t).isbn); WHEN arec.item IS OF (serial_t) THEN DBMS_OUTPUT.PUT_LINE('Found a serial with ISSN ' || TREAT(arec.item AS serial_t).issn); ELSE DBMS_OUTPUT.PUT_LINE('Found unknown catalog item'); END CASE; END LOOP;END;

Jiangping Wang

Globalization and Localization

Unicode supportVariable precision

Single-byte vs. multi-byte

Sorting orderNon-character data

Date and timeCurrency

Webster University Distributed Database Applications

Jiangping Wang

Character CodesASCII

The ASCII Character set: characters 32 – 127.

Webster University Distributed Database Applications

Jiangping Wang

ASCII 19670 1 2 3 4 5 6 7 8 9 A B C D E F

0 NUL SOH STX ETX EOT ENQ ACK BEL BS HT LF VT FF CR SO SI

1 DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAL EM SUB ESC FS GS RS US

2 sp ! ” # $ % & ’ ( ) * + , - . /

3 0 1 2 3 4 5 6 7 8 9 : ; < = > ?

4 @ A B C D E F G H I J K L M N O

5 P Q R S T U V W X Y Z [ \ ] ^ _6 ` a b c d e f g h i j k l m n o

7 p q r s t y v w x y z { | } ~ DEL

Webster University Distributed Database Applications

Jiangping Wang

ISO 8859-10 1 2 3 4 5 6 7 8 9 A B C D E F

0

1

2 sp ! ” # $ % & ’ ( ) * + , - . /

3 0 1 2 3 4 5 6 7 8 9 : ; < = > ?

4 @ A B C D E F G H I J K L M N O

5 P Q R S T U V W X Y Z [ \ ] ^ _6 ` a b c d e f g h i j k l m n o

7 p q r s t y v w x y z { | } ~ DEL

8

9

A NBSP ¡ ¢ £ ¤ ¥ ¦ § ¨ © ª « ¬ - ® ¯

B ° ± ² ³ ´ µ ¶ · ¸ ¹ º » ¼ ½ ¾ ¿

C À Á Â Ã Ä Å Æ Ç È É Ê Ë Ì Í Î Ï

D Ð Ñ Ò Ó Ô Õ Ö × Ø Ù Ú Û Ü Ý Þ ß

E à á â ã ä å æ ç è é ê ë ì í î ï

F ð ñ ò ó ô õ ö ÷ ø ù ú û ü ý þ ÿWebster University Distributed Database Applications

Jiangping Wang

Unicode Support

Unicode is a standard for representing charactersCharacter encoding with UTF

UTF-8UTF-16UTF-32

Webster University Distributed Database Applications

Jiangping Wang

Unicode Encoding Space

0: Basic Multilingual Plane

1: Supplementary Multilingual Plane2: Supplementary Ideographic Plane

E: Supplementary Special-Purpose Plane

F, 10: Private Use Planes

Unassigned

Webster University Distributed Database Applications

Jiangping Wang

Associating characters with values in the code space

Encoding Characters

Webster University Distributed Database Applications

Jiangping Wang

Three equivalent and interconvertible binary representations

Encoding Forms

Webster University Distributed Database Applications

Jiangping Wang

Oracle Character Sets

Character setNLS_CHARACTERSETNLS_NCHAR_CHARACTERSET

Data typesCHAR and VARCHARNCHAR and NVARCHAR

Fixed-length Variable-length

Database character set

CHAR VARCHAR2

National character set NCHAR NVARCHAR2

Webster University Distributed Database Applications

Jiangping Wang

Oracle Character Sets

Webster University Distributed Database Applications

Jiangping Wang

Unicode Support

Webster University Distributed Database Applications

Recommended