Friday, November 18, 2016

48 Testing ORACLE SQL Programming


1. Design and carry out tests to check the following:

a.  The business rule that requires that employees have a job_id
targets:
"JOB_ID" VARCHAR2(10) CONSTRAINT "EMP_JOB_NN" NOT NULL ENABLE,
Test No.
 101
Date
11/15/2016
Test Description
Confirm NOT NULL constraint on job_id
Input
INSERT INTO employees(employee_id,first_name,last_name,email,phone_number,hire_date,job_id,salary,commission_pct,manager_id,department_id)
VALUES(300,'Hemant','Kumar','HKUMAR',NULL,TO_DATE('2016-11-16','yyyy-mm-dd'),NULL,17000,null,100,90 );
Expected Output
Should not be able to insert NULL
Result/Discrepancy
ORA-01400: cannot insert NULL into ("HKUMAR"."EMPLOYEES"."JOB_ID")

Action

None

b.  The business rule that requires that the end date of an employment is after a start date in the job history table.
targets:
CONSTRAINT "JHIST_DATE_INTERVAL" CHECK (end_date > start_date) ENABLE,
Test No.
 102
Date
11/15/2016
Test Description
End date must be greater than start date
Input
INSERT INTO job_history(employee_id,start_date,end_date,job_id,department_id)
VALUES(102,TO_DATE('11-15-2016','mm-dd-yyyy'),TO_DATE('06-17-1993','mm-dd-yyyy'),'AD_ASST',90 );
Expected Output
Should not be able to insert since start_date is greater than end_date
Result/Discrepancy
ORA-02290: check constraint (HKUMAR.JHIST_DATE_INTERVAL) violated

Action

None

c.  The business rule that states that departments can be closed down with employees in that department (resulting in the department_id becoming unknown).
targets:
ALTER TABLE  "EMPLOYEES" ADD CONSTRAINT "EMP_DEPT_FK" FOREIGN KEY ("DEPARTMENT_ID")
              REFERENCES  "DEPARTMENTS" ("DEPARTMENT_ID") ENABLE
Test No.
 103
Date
11/15/2016
Test Description
When department is deleted from departments table, department_id in employees table is set to NULL for the corresponding rows.
Input
DELETE FROM departments WHERE department_id = 10;
(Why I chose 10:
SELECT CONSTRAINT_NAME , table_name from user_constraints where r_constraint_name = (SELECT r_constraint_name from user_constraints where CONSTRAINT_NAME= 'EMP_DEPT_FK');

select department_id from employees WHERE department_id  not in ( select nvl(department_id , 0) from job_history);

)
Expected Output
Department with id 10 is deleted and employee with id 200 gets department_id as null.
Result/Discrepancy
ORA-02292: integrity constraint (HKUMAR.EMP_DEPT_FK) violated - child record found

Action

Need to update the constraint, see problem 2

d.  The minimum salary of an employee is 1000.
targets:
CONSTRAINT "EMP_SALARY_MIN" CHECK (salary > 0) ENABLE,
Test No.
 104
Date
11/15/2016
Test Description
The minimum salary of an employee is 1000. Should not be able to edit salary to NULL or less than 1000.
Input
UPDATE employees
SET salary = NULL
WHERE employee_id = 144;
UPDATE employees
SET salary = 999
WHERE employee_id = 144;
Expected Output
Both of the update statements should fail.
Result/Discrepancy
“1 row(s) updated.” In both cases.
Action

Need to apply/update the constraint, see problem 2




2.  If one of the above tests fails, write out the SQL statement(s) that would be needed to correct the test. With the permission of your teacher, implement the change and then rerun the test with the same input and confirm that it works.
Problem 1 c Action:
ALTER TABLE employees
DROP CONSTRAINT emp_dept_fk;
ALTER TABLE  employees
ADD CONSTRAINT emp_dept_fk   FOREIGN KEY (department_id)
REFERENCES  departments (department_id) ON DELETE SET NULL ;
Now execute test id 103 again:
DELETE FROM departments WHERE department_id = 10;

SELECT department_id FROM employees WHERE employee_id = 200;

Problem 1 d action:
ALTER TABLE employees
MODIFY salary CONSTRAINT emp_salary_nn NOT NULL;

ALTER TABLE employees
DROP CONSTRAINT emp_salary_min;

UPDATE employees
SET salary = 1000 WHERE NVL(salary,0) < 1000;

ALTER TABLE employees
ADD CONSTRAINT emp_salary_min CHECK (salary >= 1000);


Execute test 104 again:

UPDATE employees
SET salary = NULL
WHERE employee_id = 144;

ORA-01407: cannot update ("HKUMAR"."EMPLOYEES"."SALARY") to NULL

UPDATE employees
SET salary = 999
WHERE employee_id = 144;
ORA-02290: check constraint (HKUMAR.EMP_SALARY_MIN) violated




47 Database Transactions


  • ·         Ends the current transaction by discarding all pending data changes- ROLLBACK
  • ·         Enables the user to discard changes made to the database- ROLLBACK
  • ·         Creates a marker in a transaction, which divides the transaction into smaller pieces- SAVEPOINT
  • ·         guarantees a consistent view of the data by all users at all times- Read consistency [Read consistency - is an automatic implementation, guarantees that readers of the data see consistent data that is not currently undergoing change.]
  • ·         Mechanisms that prevent destructive interaction between transactions accessing the same resource that can be granted to the user-Lock [Locking: Implicit locking occurs in oracle in all statements except SELECT to avoid destructive interaction b/w transactions accessing same resource. EXPLICIT locking is also possible in oracle.]
  • ·         a collection of DML statements that form a logical unit of work- Transaction


1.  Define the COMMIT, ROLLBACK, and SAVEPOINT statements as they relate to data transactions.
  • ·         COMMIT, ROLLBACK and SAVEPOINT are known as TCL (Transaction Control Language).
  • ·         COMMIT - make all pending changes permanent.
  • ·         ROLLBACK - discard the pending changes made. Automatic rollback will occur in case of system failure to protect data integrity.
  • ·         SAVEPOINT - marker to divide transaction into smaller pieces, ROLLBACK to SAVEPOINT is possible. SAVEPOINT is not a schema object and can't be referenced in data dictionary, lost after commit or rollback (transaction complete).
  • ·         TRANSACTION-

·         Starts with:
o   DML (INSERT UPDATE DELETE MERGE)
·         And ends with:
o   COMMIT,
o   Exit normally (implicit commit),
o   ROLLBACK,
o   DDL [CREATE DROP ALTER RENAME TRUNCATE]
o   DCL [GRANT OR REVOKE].

2.  What data will be committed after the following statements are issued?

INSERT INTO R values (5, 6);
SAVEPOINT my_savepoint_1;
INSERT INTO R values (7, 8);
SAVEPOINT my_savepoint_2;
INSERT INTO R values (9, 10);
ROLLBACK TO my_savepoint_1;
INSERT INTO R values (11, 12);
COMMIT;
Ideally result should be same as:
INSERT INTO R values (5, 6);
INSERT INTO R values (11, 12);

I tried  in SQL script in APEX:

I get:
ORA-01086: savepoint 'MY_SAVEPOINT_1' never established in this session or is invalid



Now I empty the table
TRUNCATE TABLE r;

And edit the script a little bit (observe BEGIN END;): 





Conclusion: If begin + end is not used I get all the rows, which seems not the purpose of statements above. To achieve the purpose with APEX and SQL scripts I will have to use BEGIN+END

3.  Construct a SQL statement for the DJs on Demand D_SONGS table that deletes the song “All These Years,” inserts a new Country song called ‘Happy Birthday Sunshine’ by “The Sunsets” with a duration of 4 min and an ID = 60. Make sure that all data can be recovered before any changes to the table are made.
type_code is not nullable in d_songs. Purpose of this problem seems to be: show that, since INSERT fails and I am making a transaction, delete will also rollback.
Point  e)  or f) below is the solution to this problem, rest is to understand the issue.
a)      If I use simply below mentioned SQL script, delete is committed, even if insert fails:

DELETE FROM d_songs
WHERE title = 'All These Years';
INSERT INTO d_songs (id, title, duration, artist)
VALUES (60, 'Happy Birthday Sunshine', '4 min',  'The Sunsets');
COMMIT;


SELECT *  FROM d_songs
WHERE title = 'All These Years';

b)      Now I recreated the whole schema using schema creation scripts provided.
c)      The most straight forward way to verify rollback is below mentioned executed as a script:
DELETE FROM d_songs
WHERE title = 'All These Years';
INSERT INTO d_songs (id, title, duration, artist)
VALUES (60, 'Happy Birthday Sunshine', '4 min',  'The Sunsets');
ROLLBACK;

When above mentioned script executed:



How to: when INSERT fails delete should also rollback.
d)      Now I recreated the whole schema using schema creation scripts provided.

e)      Alternative1: Now make both the delete and insert one unit under a block: Save below mentioned code as script in apex:
BEGIN
DELETE FROM d_songs
WHERE title = 'All These Years';
INSERT INTO d_songs (id, title, duration, artist)
VALUES (60, 'Happy Birthday Sunshine', '4 min',  'The Sunsets');
COMMIT;
END;
Even if I skip COMMIT here, I should get same results.


SELECT *  FROM d_songs
WHERE title = 'All These Years';


f)        Alternative2: demo the use of savepoint with begin and end:
BEGIN
SAVEPOINT rollbactobeginning;
DELETE FROM d_songs
WHERE title = 'All These Years';
INSERT INTO d_songs (id, title, duration, artist)
VALUES (60, 'Happy Birthday Sunshine', '4 min',  'The Sunsets');

EXCEPTION
  WHEN OTHERS THEN
    ROLLBACK TO rollbactobeginning;
END;


SELECT *  FROM d_songs
WHERE title = 'All These Years';

SELECT * FROM d_songs WHERE id = 60;

g)       Tweak alternative 2 to understand benefit of SAVEPOINT:
BEGIN
DELETE FROM d_songs
WHERE title = 'All These Years';
SAVEPOINT rollbactobeginning;
INSERT INTO d_songs (id, title, duration, artist)
VALUES (60, 'Happy Birthday Sunshine', '4 min',  'The Sunsets');
EXCEPTION
  WHEN OTHERS THEN
    ROLLBACK TO rollbactobeginning;
END;





So, the row with given title is deleted.
4.  Write an SQL statement that will issue an automatic commit.
DELETE FROM d_songs
WHERE title = 'All These Years';
In apex, above statement will auto-commit in SQL commands window.
I tried  ROLLBACK in SQL commands window:
Rollback statement not applicable. All statements are automatically committed.

5.  Give two examples of businesses other than banks that rely on transaction control processes. Describe why each business needs transaction processing control.
·         Say, I am booking a plane ticket. If this is not a transaction, I could get my money deducted from my debit card, even if the assignment of seat to my unique id failed.

·         Say, a passenger airplane has to take off, and it follows a sequence (which includes right from fuel to weather check kind of activities) before it is actually triggered to run for flying, even if one step fails in the sequence, taking off must be cancelled, if it were not a transaction, I won't ever like to be present in a passenger airplane to die.

46 Regular Expressions



1.  Working with the employees table, and using regular expressions, write a query that returns employees whose first names start with a “S” (uppercase) followed by either a “t” (lowercase) or “h” (lowercase).
SELECT * FROM employees
WHERE REGEXP_LIKE(first_name, '^S(t|h)');


^/$ Matches the start-of-line/end-of-line
() Grouping expression, treated as a single sub-expression
| Alternation operator for specifying alternative matches
2. Investigate the LOCATIONS table:

a.  Describe the table.
DESCRIBE locations;


SELECT constraint_name, constraint_type, r_constraint_name FROM user_constraints WHERE table_name = 'LOCATIONS';


SELECT constraint_name, constraint_type, table_name FROM user_constraints    WHERE r_constraint_name = (SELECT constraint_name FROM user_constraints WHERE  table_name = 'LOCATIONS' AND constraint_type = 'P');

b.  Perform a select that returns all rows and all columns of that table.
SELECT * FROM locations;

c.  Write a query using regular expressions that removes the spaces in the street_address column in the LOCATIONS table.
SELECT street_address, REGEXP_REPLACE(street_address, ' ','')   street_address_changed
FROM locations;



Some most frequently used meta characters:
. (dot) Matches any character in the supported character set,except NULL
?  matches zero or one occurence
* matches zero or more occurences
+ Matches one or more occurences
() Grouping expression, treated as a single sub-expression
\ Escape character
| Alternation operator for specifying alternative matches
^/$ Matches the start-of-line/end-of-line
[] Bracket expression for a matching list matching any one of the expressions represented in the list


Regular expressions used as check constraints are another way to ensure data is formatted correctly prior to being written into the database table.

Regular expression functions:REGEXP_INSTR,  REGEXP_SUBSTR, REGEXP_LIKE,  REGEXP_REPLACE,  REGEXP_COUNT

45 Creating and Revoking Object Privileges


1.  What is a role?
A role is named group of related privileges that can be granted to users.
2.  What are the advantages of a role to a DBA?
It makes easier to grant/revoke/maintain privileges. A user can be given multiple roles and a role could be assigned to multiple users. So, rather than assigning multiple privileges to a user, I may prefer to assign/revoke a role and I am good to go.
It also means, a user having multiple roles get all the privileges in all assigned roles.

3.  Give the ability to another user in your class to look at one of your tables. Give him the right to let other students have that ability.
GRANT SELECT ON hkumar.d_clients to strange_uname
WITH GRANT OPTION;
Verify: SELECT * FROM user_tab_privs_made;

REVOKE  SELECT ON  hkumar.d_clients  FROM strange_uname;

SELECT * FROM user_tab_privs_made;

4.  You are the DBA. You are creating many users who require the same system privileges. What should you use to make your job easier?
I will group together the privileges in role. And grant this role to the user. If there are multiple set of privileges given based on what kind of job user does, I will create multiple roles: As in problem 5 below.
5.  What is the syntax to accomplish the following?

a.  Create a role of manager that has the privileges to select, insert, and update and delete from the employees table
CREATE ROLE manager;
GRANT SELECT, INSERT, UPDATE, DELETE ON employees TO manager;
b.  Create a role of clerk that just has the privileges of select and insert on the employees table
CREATE ROLE clerk;
GRANT SELECT, INSERT ON employees TO clerk;
c.  Grant the manager role to user scott
GRANT manager TO scott;
d.  Revoke the ability to delete from the employees table from the manager role
REVOKE DELETE ON employees FROM manager;
6.  What is the purpose of a database link?
DB link is a pointer that defines a one-way communication path from one oracle DB to another oracle db.
They allow users to access another user's objects in a remote DB, so that they are bounded by the privilege set of the object's owner. A local user gets access to remote database via DB link.  Database Links allow users to work on remote database objects without having to log into the other database.