Advanced SQL Lecture 4 Advanced SQL n SQL

  • Slides: 73
Download presentation
Advanced SQL Lecture 4

Advanced SQL Lecture 4

Advanced SQL n SQL Data Types and Schemas n Integrity Constraints n Authorization n

Advanced SQL n SQL Data Types and Schemas n Integrity Constraints n Authorization n Functions and Procedural Constructs n Recursive Queries n Advanced SQL Features 2

Built-in Data Types in SQL n date: Dates, containing a (4 digit) year, month

Built-in Data Types in SQL n date: Dates, containing a (4 digit) year, month and date H Example: date ‘ 2005 -7 -27’ n time: Time of day, in hours, minutes and seconds. H Example: time ‘ 09: 00: 30’ time ‘ 09: 00: 30. 75’ n timestamp: date plus time of day H Example: timestamp ‘ 2005 -7 -27 09: 00: 30. 75’ n interval: period of time H Example: interval ‘ 1’ day H Subtracting a date/timestamp value from another gives an interval value H Interval values can be added to date/timestamp values 3

Build-in Data Types in SQL n Can extract values of individual fields from date/timestamp

Build-in Data Types in SQL n Can extract values of individual fields from date/timestamp H Example: extract (year from r. starttime) n Can cast string types to date/timestamp H Example: cast <string-valued-expression> as date H Example: cast <string-valued-expression> as time 4

User-Defined Types n create type construct in SQL creates user-defined type create type Dollars

User-Defined Types n create type construct in SQL creates user-defined type create type Dollars as numeric (12, 2) final n create domain construct in SQL-92 creates user-defined domain types create domain person_name char(20) not null n Types and domains are similar. Domains can have constraints, such as not null, specified on them. 5

Domain Constraints n Domain constraints are the most elementary form of integrity constraint. They

Domain Constraints n Domain constraints are the most elementary form of integrity constraint. They test values inserted in the database, and test queries to ensure that the comparisons make sense. n New domains can be created from existing data types H Example: create domain Dollars numeric(12, 2) create domain Pounds numeric(12, 2) n We cannot assign or compare a value of type Dollars to a value of type Pounds. H However, we can convert type as below (cast r. A as Pounds) (Should also multiply by the dollar-to-pound conversion-rate) 6

Large-Object Types n Large objects (photos, videos, CAD files, etc. ) are stored as

Large-Object Types n Large objects (photos, videos, CAD files, etc. ) are stored as a large object: H blob: binary large object -- object is a large collection of uninterpreted binary data (whose interpretation is left to an application outside of the database system) H clob: character large object -- object is a large collection of character data H When a query returns a large object, a pointer is returned rather than the large object itself. 7

Integrity Constraints n Integrity constraints guard against accidental damage to the database, by ensuring

Integrity Constraints n Integrity constraints guard against accidental damage to the database, by ensuring that authorized changes to the database do not result in a loss of data consistency. H A checking account must have a balance greater than $10, 000. 00 H A salary of a bank employee must be at least $4. 00 an hour H A customer must have a (non-null) phone number 8

Constraints on a Single Relation n not null n primary key n unique n

Constraints on a Single Relation n not null n primary key n unique n check (P ), where P is a predicate 9

Not Null Constraint n Declare branch_name for branch is not null branch_name char(15) not

Not Null Constraint n Declare branch_name for branch is not null branch_name char(15) not null n Declare the domain Dollars to be not null create domain Dollars numeric(12, 2) not null 10

The Unique Constraint n unique ( A 1, A 2, …, Am) The unique

The Unique Constraint n unique ( A 1, A 2, …, Am) The unique specification states that the attributes A 1, A 2, … A m Form a candidate key. Candidate keys are permitted to be non null (in contrast to primary keys). 11

The check clause n check (P ), where P is a predicate Example: Declare

The check clause n check (P ), where P is a predicate Example: Declare branch_name as the primary key for branch and ensure that the values of assets are nonnegative. create table branch (branch_name char(15), branch_city char(30), assets integer, primary key (branch_name), check (assets >= 0)) 12

The check clause n The check clause in SQL-92 permits domains to be restricted:

The check clause n The check clause in SQL-92 permits domains to be restricted: H Use check clause to ensure that an hourly_wage domain allows only values greater than a specified value. create domain hourly_wage numeric(5, 2) constraint value_test check(value > = 4. 00) H The domain has a constraint that ensures that the hourly_wage is greater than 4. 00 H The clause constraint value_test is optional; useful to indicate which constraint an update violated. 13

Referential Integrity n Ensures that a value that appears in one relation for a

Referential Integrity n Ensures that a value that appears in one relation for a given set of attributes also appears for a certain set of attributes in another relation. H Example: If “Perryridge” is a branch name appearing in one of the tuples in the account relation, then there exists a tuple in the branch relation for branch “Perryridge”. n Formal Definition H Let r 1(R 1) and r 2(R 2) be relations with primary keys K 1 and K 2 respectively. H The subset of R 2 is a foreign key referencing K 1 in relation r 1, if for every t 2 in r 2 there must be a tuple t 1 in r 1 such that t 1[K 1] = t 2[ ]. H Referential integrity constraint also called subset dependency since its can be written as (r 2) K 1 (r 1) 14

Checking Referential Integrity on Database Modification n The following tests must be made in

Checking Referential Integrity on Database Modification n The following tests must be made in order to preserve the following referential integrity constraint: (r 2) K (r 1) n Insert. If a tuple t 2 is inserted into r 2, the system must ensure that there is a tuple t 1 in r 1 such that t 1[K] = t 2[ ]. That is t 2 [ ] K (r 1) n Delete. If a tuple, t 1 is deleted from r 1, the system must compute the set of tuples in r 2 that reference t 1: = t 1[K] (r 2) If this set is not empty H either the delete command is rejected as an error, or H the tuples that reference t 1 must themselves be deleted (cascading deletions are possible). 15

Referential Integrity in SQL n Primary and candidate keys and foreign keys can be

Referential Integrity in SQL n Primary and candidate keys and foreign keys can be specified as part of the SQL create table statement: H The primary key clause lists attributes that comprise the primary key. H The unique key clause lists attributes that comprise a candidate key. H The foreign key clause lists the attributes that comprise the foreign key and the name of the relation referenced by the foreign key. n By default, a foreign key references the primary key attributes of the referenced table foreign key (account-number) references account n Short form for specifying a single column as foreign key account-number char (10) references account n Reference columns in the referenced table can be explicitly specified H but must be declared as primary/candidate keys foreign key (account-number) references account(account-number) 16

Referential Integrity in SQL n Alternative to cascading: H on delete set null H

Referential Integrity in SQL n Alternative to cascading: H on delete set null H on delete set default n Null values in foreign key attributes complicate SQL referential integrity semantics, and are best prevented using not null H if any attribute of a foreign key is null, the tuple is defined to satisfy the foreign key constraint! 17

Referential Integrity in SQL – Example create table customer (customer_name char(20), customer_street char(30), customer_city

Referential Integrity in SQL – Example create table customer (customer_name char(20), customer_street char(30), customer_city char(30), primary key (customer_name )) create table branch (branch_name char(15), branch_city char(30), assets numeric(12, 2), primary key (branch_name )) 18

Referential Integrity in SQL – Example create table account (account_number char(10), branch_name char(15), balance

Referential Integrity in SQL – Example create table account (account_number char(10), branch_name char(15), balance integer, primary key (account_number), foreign key (branch_name) references branch ) create table depositor (customer_name char(20), account_number char(10), primary key (customer_name, account_number), foreign key (account_number ) references account, foreign key (customer_name ) references customer ) 19

Cascading Actions in SQL create table account. . . foreign key(branch-name) on delete cascade

Cascading Actions in SQL create table account. . . foreign key(branch-name) on delete cascade on update cascade. . . ) references branch n Due to the on delete cascade clauses, if a delete of a tuple in branch results in referential-integrity constraint violation, the delete “cascades” to the account relation, deleting the tuple that refers to the branch that was deleted. n Cascading updates are similar. 20

Cascading Actions in SQL (Cont. ) n If there is a chain of foreign-key

Cascading Actions in SQL (Cont. ) n If there is a chain of foreign-key dependencies across multiple relations, with on delete cascade specified for each dependency, a deletion or update at one end of the chain can propagate across the entire chain. n If a cascading update to delete causes a constraint violation that cannot be handled by a further cascading operation, the system aborts the transaction. H As a result, all the changes caused by the transaction and its cascading actions are undone. n Referential integrity is only checked at the end of a transaction H Intermediate steps are allowed to violate referential integrity provided later steps remove the violation H Otherwise it would be impossible to create some database states, e. g. insert two tuples whose foreign keys point to each other 4 E. g. spouse attribute of relation marriedperson(name, address, spouse) 21

Assertions n An assertion is a predicate expressing a condition that we wish the

Assertions n An assertion is a predicate expressing a condition that we wish the database always to satisfy. n An assertion in SQL takes the form create assertion <assertion-name> check <predicate> n When an assertion is made, the system tests it for validity, and tests it again on every update that may violate the assertion H This testing may introduce a significant amount of overhead; hence assertions should be used with great care. n Asserting for all X, P(X) is achieved in a round-about fashion using not exists X such that not P(X) 22

Assertion Example n Every loan has at least one borrower who maintains an account

Assertion Example n Every loan has at least one borrower who maintains an account with a minimum balance or $1000. 00 create assertion balance_constraint check (not exists ( select * from loan where not exists ( select * from borrower, depositor, account where loan_number = borrower. loan_number and borrower. customer_name = depositor. customer_name and depositor. account_number = account_number and account. balance >= 1000))) 23

Assertion Example n The sum of all loan amounts for each branch must be

Assertion Example n The sum of all loan amounts for each branch must be less than the sum of all account balances at the branch. create assertion sum_constraint check (not exists (select * from branch where (select sum(amount ) from loan where loan. branch_name = branch_name ) >= (select sum (amount ) from account where loan. branch_name = branch_name ))) 24

Triggers n A trigger is a statement that is executed automatically by the system

Triggers n A trigger is a statement that is executed automatically by the system as a side effect of a modification to the database. n To design a trigger mechanism, we must: H Specify the conditions under which the trigger is to be executed. H Specify the actions to be taken when the trigger executes. n Triggers introduced to SQL standard in SQL: 1999, but supported even earlier using non-standard syntax by most databases. 25

Trigger Example n Suppose that instead of allowing negative account balances, the bank deals

Trigger Example n Suppose that instead of allowing negative account balances, the bank deals with overdrafts by H setting the account balance to zero H creating a loan in the amount of the overdraft H giving this loan a loan number identical to the account number of the overdrawn account n The condition for executing the trigger is an update to the account relation that results in a negative balance value. 26

Trigger Example in SQL: 1999 create trigger overdraft-trigger after update on account referencing new

Trigger Example in SQL: 1999 create trigger overdraft-trigger after update on account referencing new row as nrow for each row when nrow. balance < 0 begin atomic insert into borrower (select customer-name, account-number from depositor where nrow. account-number = depositor. account-number); insert into loan values (n. row. account-number, nrow. branch-name, – nrow. balance); update account set balance = 0 where account-number = nrow. account-number end 27

Triggering Events and Actions in SQL n Triggering event can be insert, delete or

Triggering Events and Actions in SQL n Triggering event can be insert, delete or update n Triggers on update can be restricted to specific attributes H E. g. create trigger overdraft-trigger after update of balance on account n Values of attributes before and after an update can be referenced H referencing old row as : for deletes and updates H referencing new row as : for inserts and updates n Triggers can be activated before an event, which can serve as extra constraints. E. g. convert blanks to null. create trigger setnull-trigger before update on r referencing new row as nrow for each row when nrow. phone-number = ‘ ‘ set nrow. phone-number = null 28

Statement Level Triggers n Instead of executing a separate action for each affected row,

Statement Level Triggers n Instead of executing a separate action for each affected row, a single action can be executed for all rows affected by a transaction H Use for each statement instead of for each row H Use referencing old table or referencing new table to refer to temporary tables (called transition tables) containing the affected rows H Can be more efficient when dealing with SQL statements that update a large number of rows 29

External World Actions n We sometimes require external world actions to be triggered on

External World Actions n We sometimes require external world actions to be triggered on a database update H E. g. re-ordering an item whose quantity in a warehouse has become small, or turning on an alarm light, n Triggers cannot be used to directly implement external-world actions, BUT H Triggers can be used to record actions-to-be-taken in a separate table H Have an external process that repeatedly scans the table, carries out external-world actions and deletes action from table n E. g. Suppose a warehouse has the following tables H inventory(item, level): How much of each item is in the warehouse H minlevel(item, level) : What is the minimum desired level of each item H reorder(item, amount): What quantity should we re-order at a time H orders(item, amount) : Orders to be placed (read by external process) 30

External World Actions create trigger reorder-trigger after update of amount on inventory referencing old

External World Actions create trigger reorder-trigger after update of amount on inventory referencing old row as orow, new row as nrow for each row when nrow. level < = (select level from minlevel where minlevel. item = orow. item) and orow. level > (select level from minlevel where minlevel. item = orow. item) begin insert into orders (select item, amount from reorder where reorder. item = orow. item) end 31

Triggers in MS-SQLServer Syntax create trigger overdraft-trigger on account for update as if inserted.

Triggers in MS-SQLServer Syntax create trigger overdraft-trigger on account for update as if inserted. balance < 0 begin insert into borrower (select customer-name, account-number from depositor, inserted where inserted. account-number = depositor. account-number) insert into loan values (inserted. account-number, inserted. branch-name, – inserted. balance) update account set balance = 0 from account, inserted where account-number = inserted. account-number end 32

When Not To Use Triggers n Triggers were used earlier for tasks such as

When Not To Use Triggers n Triggers were used earlier for tasks such as H maintaining summary data (e. g. total salary of each department) H Replicating databases by recording changes to special relations (called change or delta relations) and having a separate process that applies the changes over to a replica n There are better ways of doing these now: H Databases today provide built in materialized view facilities to maintain summary data H Databases provide built-in support for replication n Encapsulation facilities can be used instead of triggers in many cases H Define methods to update fields H Carry out actions as part of the update methods instead of through a trigger 33

Procedural Extensions and Stored Procedures n SQL provides a module language H Permits definition

Procedural Extensions and Stored Procedures n SQL provides a module language H Permits definition of procedures in SQL, with if-then-else statements, for and while loops, etc. H more in Chapter 9 n Stored Procedures H Can store procedures in the database H then execute them using the call statement H permit external applications to operate on the database without knowing about internal details 34

Functions and Procedures n SQL: 1999 supports functions and procedures H Functions/procedures can be

Functions and Procedures n SQL: 1999 supports functions and procedures H Functions/procedures can be written in SQL itself, or in an external programming language H Functions are particularly useful with specialized data types such as images and geometric objects 4 Example: functions to check if polygons overlap, or to compare images for similarity H Some database systems support table-valued functions, which can return a relation as a result n SQL: 1999 also supports a rich set of imperative constructs, including H Loops, if-then-else, assignment n Many databases have proprietary procedural extensions to SQL that differ from SQL: 1999 35

SQL Functions n Define a function that, given the name of a customer, returns

SQL Functions n Define a function that, given the name of a customer, returns the count of the number of accounts owned by the customer. create function account_count (customer_name varchar(20)) returns integer begin declare a_count integer; select count (* ) into a_count from depositor where depositor. customer_name = customer_name return a_count; end n Find the name and address of each customer that has more than one account. select customer_name, customer_street, customer_city from customer where account_count (customer_name ) > 1 36

Table Functions n SQL: 2003 added functions that return a relation as a result

Table Functions n SQL: 2003 added functions that return a relation as a result n Example: Return all accounts owned by a given customer create function accounts_of (customer_name char(20) returns table ( account_number char(10), branch_name char(15), balance numeric(12, 2)) return table (select account_number, branch_name, balance from account where exists ( select * from depositor where depositor. customer_name = accounts_of. customer_name and depositor. account_number = 37 account_number ))

Table Functions (cont’d) n Usage select * from table (accounts_of (‘Smith’)) 38

Table Functions (cont’d) n Usage select * from table (accounts_of (‘Smith’)) 38

SQL Procedures n The author_count function could instead be written as procedure: create procedure

SQL Procedures n The author_count function could instead be written as procedure: create procedure account_proc (in title varchar(20), out a_count integer) begin select count(author) into a_count from depositor where depositor. customer_name = account_proc. customer_name end n Procedures can be invoked either from an SQL procedure or from embedded SQL, using the call statement. declare a_count integer; call account_proc( ‘Smith’, a_count); n SQL: 1999 allows more than one function/procedure of the same name (called name overloading), as long as the number of arguments differ, or at least the types of the arguments differ 39

Procedural Constructs n Compound statement: begin … end, H May contain multiple SQL statements

Procedural Constructs n Compound statement: begin … end, H May contain multiple SQL statements between begin and end. H Local variables can be declared within a compound statements n While and repeat statements: declare n integer default 0; while n < 10 do set n = n + 1 end while repeat set n = n – 1 until n = 0 end repeat 40

Procedural Constructs (Cont. ) n For loop H Permits iteration over all results of

Procedural Constructs (Cont. ) n For loop H Permits iteration over all results of a query H Example: find total of all balances at the Perryridge branch declare n integer default 0; for r as select balance from account where branch_name = ‘Perryridge’ do set n = n + r. balance end for 41

Procedural Constructs (cont. ) n Conditional statements (if-then-else) E. g. To find sum of

Procedural Constructs (cont. ) n Conditional statements (if-then-else) E. g. To find sum of balances for each of three categories of accounts (with balance <1000, >=1000 and <5000, >= 5000) if r. balance < 1000 then set l = l + r. balance elseif r. balance < 5000 then set m = m + r. balance else set h = h + r. balance end if n SQL: 1999 also supports a case statement similar to C case statement 42

External Language Functions/Procedures n SQL: 1999 permits the use of functions and procedures written

External Language Functions/Procedures n SQL: 1999 permits the use of functions and procedures written in other languages such as C or C++ n Declaring external language procedures and functions create procedure account_proc(in customer_name varchar(20), out count integer) language C external name ’ /usr/avi/bin/account_proc’ create function account_count(customer_name varchar(20)) returns integer language C external name ‘/usr/avi/bin/author_count’ 43

External Language Routines (Cont. ) n Benefits of external language functions/procedures: H more efficient

External Language Routines (Cont. ) n Benefits of external language functions/procedures: H more efficient for many operations, and more expressive power n Drawbacks H Code to implement function may need to be loaded into database system and executed in the database system’s address space 4 risk of accidental corruption of database structures 4 security risk, allowing users access to unauthorized data H There alternatives, which give good security at the cost of potentially worse performance H Direct execution in the database system’s space is used when efficiency is more important than security 44

Security with External Language Routines n To deal with security problems H Use sandbox

Security with External Language Routines n To deal with security problems H Use sandbox techniques 4 that is use a safe language like Java, which cannot be used to access/damage other parts of the database code H Or, run external language functions/procedures in a separate process, with no access to the database process’ memory 4 Parameters and results communicated via inter-process communication n Both have performance overheads n Many database systems support both above approaches as well as direct executing in database system address space 45

Recursion in SQL: 1999 permits recursive view definition n Example: find all employee-manager pairs,

Recursion in SQL: 1999 permits recursive view definition n Example: find all employee-manager pairs, where the employee reports to the manager directly or indirectly (that is manager’s manager, etc. ) with recursive empl (employee_name, manager_name ) as ( select employee_name, manager_name from manager union select manager. employee_name, empl. manager_name from manager, empl where manager_name = employe_name) select * from empl This example view, empl, is called the transitive closure of the manager relation 46

The Power of Recursion n Recursive views make it possible to write queries, such

The Power of Recursion n Recursive views make it possible to write queries, such as transitive closure queries, that cannot be written without recursion or iteration. H Intuition: Without recursion, a non-recursive non-iterative program can perform only a fixed number of joins of manager with itself 4 This can give only a fixed number of levels of managers 4 Given a program we can construct a database with a greater number of levels of managers on which the program will not work H The next slide shows a manager relation and each step of the iterative process that constructs empl from its recursive definition. The final result is called the fixed point of the recursive view definition. n Recursive views are required to be monotonic. That is, if we add tuples to manger the view contains all of the tuples it contained before, plus possibly more 47

Example of Fixed-Point Computation 48

Example of Fixed-Point Computation 48

Security n Security - protection from malicious attempts to steal or modify data. H

Security n Security - protection from malicious attempts to steal or modify data. H Database system level 4 Authentication and authorization mechanisms to allow specific users access only to required data 4 We concentrate on authorization in the rest of this chapter H Operating system level 4 Operating system super-users can do anything they want to the database! Good operating system level security is required. H Network level: must use encryption to prevent 4 Eavesdropping (unauthorized reading of messages) 4 Masquerading (pretending to be an authorized user or sending messages supposedly from authorized users) 49

Physical Level Security n Protection of equipment from floods, power failure, etc. n Protection

Physical Level Security n Protection of equipment from floods, power failure, etc. n Protection of disks from theft, erasure, physical damage, etc. n Protection of network and terminal cables from wiretaps non- invasive electronic eavesdropping, physical damage, etc. Solutions: n Replicated hardware: H mirrored disks, dual busses, etc. H multiple access paths between every pair of devises n Physical security: locks, police, etc. n Software techniques to detect physical security breaches. 50

Human Level Security n Protection from stolen passwords, sabotage, etc. n Primarily a management

Human Level Security n Protection from stolen passwords, sabotage, etc. n Primarily a management problem: H Frequent change of passwords H Use of “non-guessable” passwords H Log all invalid access attempts H Data audits H Careful hiring practices 51

Operating System Level Security n Protection from invalid logins n File-level access protection (often

Operating System Level Security n Protection from invalid logins n File-level access protection (often not very helpful for database security) n Protection from improper use of “superuser” authority. n Protection from improper use of privileged machine intructions. 52

Network-Level Security n Each site must ensure that it communicate with trusted sites (not

Network-Level Security n Each site must ensure that it communicate with trusted sites (not intruders). n Links must be protected from theft or modification of messages n Mechanisms: H Identification protocol (password-based), H Cryptography. 53

Database-Level Security n Assume security at network, operating system, human, and physical levels. n

Database-Level Security n Assume security at network, operating system, human, and physical levels. n Database specific issues: H each user may have authority to read only part of the data and to write only part of the data. H User authority may correspond to entire files or relations, but it may also correspond only to parts of files or relations. n Local autonomy suggests site-level authorization control in a distributed database. n Global control suggests centralized control. 54

Authorization Forms of authorization on parts of the database: n Read - allows reading,

Authorization Forms of authorization on parts of the database: n Read - allows reading, but not modification of data. n Insert - allows insertion of new data, but not modification of existing data. n Update - allows modification, but not deletion of data. n Delete - allows deletion of data. Forms of authorization to modify the database schema (covered in Chapter 8): n Index - allows creation and deletion of indices. n Resources - allows creation of new relations. n Alteration - allows addition or deletion of attributes in a relation. n Drop - allows deletion of relations. 55

Authorization Specification in SQL n The grant statement is used to confer authorization grant

Authorization Specification in SQL n The grant statement is used to confer authorization grant <privilege list> on <relation name or view name> to <user list> n <user list> is: H a user-id H public, which allows all valid users the privilege granted H A role (more on this in Chapter 8) n Granting a privilege on a view does not imply granting any privileges on the underlying relations. n The grantor of the privilege must already hold the privilege on the specified item (or be the database administrator). 56

Statistical Databases n Problem: how to ensure privacy of individuals while allowing use of

Statistical Databases n Problem: how to ensure privacy of individuals while allowing use of data for statistical purposes (e. g. , finding median income, average bank balance etc. ) n Solutions: H System rejects any query that involves fewer than some predetermined number of individuals. Still possible to use results of multiple overlapping queries to deduce data about an individual H Data pollution -- random falsification of data provided in response to a query. H Random modification of the query itself. n There is a tradeoff between accuracy and security. 57

Extra Material 58

Extra Material 58

Embedded SQL n The SQL standard defines embeddings of SQL in a variety of

Embedded SQL n The SQL standard defines embeddings of SQL in a variety of programming languages such as C, Java, and Cobol. n A language to which SQL queries are embedded is referred to as a host language, and the SQL structures permitted in the host language comprise embedded SQL. n The basic form of these languages follows that of the System R embedding of SQL into PL/I. n EXEC SQL statement is used to identify embedded SQL request to the preprocessor EXEC SQL <embedded SQL statement > END_EXEC Note: this varies by language (for example, the Java embedding uses # SQL { …. }; ) 59

Embedded SQL n The open statement causes the query to be evaluated EXEC SQL

Embedded SQL n The open statement causes the query to be evaluated EXEC SQL open c END_EXEC n The fetch statement causes the values of one tuple in the query result to be placed on host language variables. EXEC SQL fetch c into : cn, : cc END_EXEC Repeated calls to fetch get successive tuples in the query result n A variable called SQLSTATE in the SQL communication area (SQLCA) gets set to ‘ 02000’ to indicate no more data is available n The close statement causes the database system to delete the temporary relation that holds the result of the query. EXEC SQL close c END_EXEC Note: above details vary with language. For example, the Java embedding defines Java iterators to step through result tuples. 60

Updates Through Cursors n Can update tuples fetched by cursor by declaring that the

Updates Through Cursors n Can update tuples fetched by cursor by declaring that the cursor is for update declare c cursor for select * from account where branch_name = ‘Perryridge’ for update n To update tuple at the current location of cursor c update account set balance = balance + 100 where current of c 61

Example Query n From within a host language, find the names and cities of

Example Query n From within a host language, find the names and cities of customers with more than the variable amount dollars in some account. n Specify the query in SQL and declare a cursor for it EXEC SQL declare c cursor for select customer_name, customer_city from depositor, customer, account where depositor. customer_name = customer_name and depositor account_number = account_number and account. balance > : amount END_EXEC 62

Dynamic SQL n Allows programs to construct and submit SQL queries at run time.

Dynamic SQL n Allows programs to construct and submit SQL queries at run time. n Example of the use of dynamic SQL from within a C program. char * sqlprog = “update account set balance = balance * 1. 05 where account_number = ? ” EXEC SQL prepare dynprog from : sqlprog; char account [10] = “A-101”; EXEC SQL execute dynprog using : account; n The dynamic SQL program contains a ? , which is a place holder for a value that is provided when the SQL program is executed. 63

ODBC and JDBC n API (application-program interface) for a program to interact with a

ODBC and JDBC n API (application-program interface) for a program to interact with a database server n Application makes calls to H Connect with the database server H Send SQL commands to the database server H Fetch tuples of result one-by-one into program variables n ODBC (Open Database Connectivity) works with C, C++, C#, and Visual Basic n JBDC (Java Database Connectivity) works with Java 64

ODBC n Open Data. Base Connectivity(ODBC) standard H standard for application program to communicate

ODBC n Open Data. Base Connectivity(ODBC) standard H standard for application program to communicate with a database server. H application program interface (API) to 4 open a connection with a database, 4 send queries and updates, 4 get back results. n Applications such as GUI, spreadsheets, etc. can use ODBC 65

ODBC (Cont. ) n Each database system supporting ODBC provides a "driver" library that

ODBC (Cont. ) n Each database system supporting ODBC provides a "driver" library that must be linked with the client program. n When client program makes an ODBC API call, the code in the library communicates with the server to carry out the requested action, and fetch results. n ODBC program first allocates an SQL environment, then a database connection handle. n Opens database connection using SQLConnect(). Parameters for SQLConnect: H H connection handle, the server to which to connect the user identifier, password n Must also specify types of arguments: H SQL_NTS denotes previous argument is a null-terminated string. 66

ODBC Code n int ODBCexample() { RETCODE error; HENV env; /* environment */ HDBC

ODBC Code n int ODBCexample() { RETCODE error; HENV env; /* environment */ HDBC conn; /* database connection */ SQLAlloc. Env(&env); SQLAlloc. Connect(env, &conn); SQLConnect(conn, "aura. bell-labs. com", SQL_NTS, "avipasswd", SQL_NTS); { …. Do actual work … } SQLDisconnect(conn); SQLFree. Connect(conn); SQLFree. Env(env); } 67

ODBC Code (Cont. ) n Program sends SQL commands to the database by using

ODBC Code (Cont. ) n Program sends SQL commands to the database by using SQLExec. Direct n Result tuples are fetched using SQLFetch() n SQLBind. Col() binds C language variables to attributes of the query result H When a tuple is fetched, its attribute values are automatically stored in corresponding C variables. H Arguments to SQLBind. Col() 4 ODBC stmt variable, attribute position in query result 4 The type conversion from SQL to C. 4 The address of the variable. 4 For variable-length types like character arrays, – The maximum length of the variable – Location to store actual length when a tuple is fetched. – Note: A negative value returned for the length field indicates null value n Good programming requires checking results of every function call 68 for errors; we have omitted most checks for brevity.

ODBC Code (Cont. ) n Main body of program char branchname[80]; float balance; int

ODBC Code (Cont. ) n Main body of program char branchname[80]; float balance; int len. Out 1, len. Out 2; HSTMT stmt; SQLAlloc. Stmt(conn, &stmt); char * sqlquery = "select branch_name, sum (balance) from account group by branch_name"; error = SQLExec. Direct(stmt, sqlquery, SQL_NTS); if (error == SQL_SUCCESS) { SQLBind. Col(stmt, 1, SQL_C_CHAR, branchname , 80, &len. Out 1); SQLBind. Col(stmt, 2, SQL_C_FLOAT, &balance, 0, &len. Out 2); while (SQLFetch(stmt) >= SQL_SUCCESS) { printf (" %s %gn", branchname, balance); } } SQLFree. Stmt(stmt, SQL_DROP); 69

More ODBC Features n Prepared Statement H SQL statement prepared: compiled at the database

More ODBC Features n Prepared Statement H SQL statement prepared: compiled at the database H Can have placeholders: E. g. insert into account values(? , ? ) H Repeatedly executed with actual values for the placeholders n Metadata features H finding all the relations in the database and H finding the names and types of columns of a query result or a relation in the database. n By default, each SQL statement is treated as a separate transaction that is committed automatically. H Can turn off automatic commit on a connection 4 SQLSet. Connect. Option(conn, SQL_AUTOCOMMIT, 0)} H transactions must then be committed or rolled back explicitly by 4 SQLTransact(conn, SQL_COMMIT) or 4 SQLTransact(conn, SQL_ROLLBACK) 70

ODBC Conformance Levels n Conformance levels specify subsets of the functionality defined by the

ODBC Conformance Levels n Conformance levels specify subsets of the functionality defined by the standard. H Core H Level 1 requires support for metadata querying H Level 2 requires ability to send and retrieve arrays of parameter values and more detailed catalog information. n SQL Call Level Interface (CLI) standard similar to ODBC interface, but with some minor differences. 71

Advanced SQL Features n Create a table with the same schema as an existing

Advanced SQL Features n Create a table with the same schema as an existing table: create table temp_account like account n SQL: 2003 allows subqueries to occur anywhere a value is required provided the subquery returns only one value. This applies to updates as well n SQL: 2003 allows subqueries in the from clause to access attributes of other relations in the from clause using the lateral construct: select customer_name, num_accounts from customer, lateral ( select count(*) from account where account. customer_name = customer_name ) as this_customer (num_accounts ) 72

Advanced SQL Features (cont’d) n Merge construct allows batch processing of updates. n Example:

Advanced SQL Features (cont’d) n Merge construct allows batch processing of updates. n Example: relation funds_received (account_number, amount ) has batch of deposits to be added to the proper account in the account relation merge into account as A using (select * from funds_received as F ) on (A. account_number = F. account_number ) when matched then update set balance = balance + F. amount 73