Views, PL/SQL, Functions,Triggers 8.1 Views and View Updates 8.2

Views, PL/SQL, Functions,Triggers 8.1 Views and View Updates 8.2

SQL Views 8. More SQL features: May be defined on base tables (ordinary tables) Views, PL/SQL, Functions,Triggers or on views (or both) CREATE VIEW LargeCities (name,population,country, code,fraction) 8.1 Views and view updates AS (SELECT ci.name, ci.population, co.name, co.code, 8.2 Application architectures ci.population/co.population 8.3 PL/SQL – PL/pgSQL FROM City ci JOIN Country co ON ci.country = co.code 8.4 Functions and Procedures WHERE ci.population > 1000000) 8.5 Triggers implicite 8.6 Abstract Data Types CREATE VIEW VeryLargeCities AS (SELECT name, population, country column FROM LargeCities l names see Kemper/Eickler chap. 14, Elmasri chap. 6.8, O'Neill: Chap. 4, WHERE l.population >= 3000000) Melton: SQL99, Postgres and Oracle Manuals (PL/PGSQL,PL/SQL) © HS-2010 08-PLSQLetc-4 8.1 Views Views and privacy Def.: A view is a named SQL-query, which Very large American cities: becomes part of the schema as a virtual table JOIN with encompasses(continent,country...) Intention CREATE OR REPLACE VIEW VLAmeriCities AS • Casting the database schema for different (SELECT c.name, c.population, c.country FROM LargeCities c JOIN Encompasses e applications ON c.code =e.country • Access protection WHERE e.continent = 'America' •Privacy AND c.population >= 3000000) • Structuring of SQL programs Views may be used like ordinary table in queries. ⇒ The RDM concept for external schemas ("3-schema-architecture") Privacy: column access may be granted even if access to base table is not allowed ! © HS-2010 08-PLSQLetc-2 © HS-2010 08-PLSQLetc-5 Materialized Views Views and code readability .. simplify SQL queries Def.: A materialized view is a temporary Table , which contains the result set of an SQL query Countries having more inhabitants than all american big cities • Not in all DBMS • Often used in replication scenarios SELECT c.name, c.population FROM country c • No way to insert / delete data WHERE c.population < ALL(SELECT population • But refreshing of the view makes sense FROM VLAmeriCities) • Sometimes called snapshot • Different from temporary tables CREATE TEMPORARY TABLE Temp AS (<Query>) • Insertion / Deletion allowed Operator tree of query more complicated... • Dropped at the end of a session © HS-2010 08-PLSQLetc-3 © HS-2010 08-PLSQLetc-6 1 Query plan 8.2 Updatable views View updates Many views are not updatable. Obviously: CREATE OR REPLACE VIEW PopulInCities (country, cityPop) AS (SELECT co.name, sum(ci.population) FROM City ci JOIN Country co ON Joint optimization of ci.country=co.code views and query GROUP BY co.name) View not updatable if defined using: • Aggregation • Arithmetic in Projection • DISTINCT © HS-2010 08-PLSQLetc-7 © HS-2010 08-PLSQLetc-10 Evaluation of views Semantic characterization of updatable views Steps: Def: A view V is updatable if for every update u (*) [1. Transform query on view using its definition] there exist one or more updates cu which applied to 2. Construct operator tree including view definitions the base relations and the subsequent application of the and query view definition result in the same result: 3. Optimize plan u (V(D)) = V (cu (D) ) 4. Execute query on base tables • Semantic characterization, • Wanted: syntactic criteria for updatability (*) as if it were materialized © HS-2010 08-PLSQLetc-8 © HS-2010 08-PLSQLetc-11 Views in Postgres Syntactic criteria More general substitution concept in Postgres Read only views may be arbitrarily defined, Rules are "first class objects": CREATE RULE... Update is rejected, if view not updatable. CREATE VIEW myview AS SELECT * FROM mytab; Syntactic criteria equivalent to Not updatable (SQL 92) • if grouped (GROUP BY), HAVING or aggregated CREATE TABLE myview (<same column list as mytab>); • DISTINCT in SELECT clause • set operators (INTERSECT, EXCEPT, UNION) CREATE RULE "_RETURN" AS ON SELECT TO myview DO • more than one table in FROM clause INSTEAD SELECT * FROM mytab; • No updates on join views (restrictive!) Kind of dynamic view evaluation compared to static rewrite of query or query tree © HS-2010 08-PLSQLetc-9 © HS-2010 08-PLSQLetc-12 2 Views and joins Find updatable columns Find updatable columns by querying the CREATE VIEW CCP AS catalogue (SELECT c.name, c.capital, ci.population FROM Country c JOIN City ci ON c.capital=ci.name and c.code=ci.country SELECT column_name, updatable WHERE ci.population > 1000000 FROM user_updatable_columns This is a (system) view ORDER BY c.name) WHERE table_name ='LARGECITIES' -- Oracle must be upper case Base tables: Country, City, COLUMN_NAME UPDATABLE Join on key: row insertion in one table (Country) may ------------------------------ --------- generate one new row in in the other (City), if not NAME YES already present. POPULATION YES COUNTRY NO CODE NO FRACTION NO © HS-2010 08-PLSQLetc-13 © HS-2010 08-PLSQLetc-16 Syntactic criteria (2) Views WITH CHECK OPTION SQL 1999 Issue: side effects on base table rows, no effect on view Columns (of views) are potentially updatable if ... CREATE VIEW CCLarge(ctryName, capital, population) AS no DISTINCT operator (SELECT c.name as ctryName, c.capital, ci.population FROM Country c JOIN City ci no GROUP BY, HAVING clause ON c.capital=ci.name and c.code=ci.country no derived columns (e.g. arithmetic expressions) and c.province = ci.province WHERE ci.population > 1000000) WITH CHECK OPTION (1) Column is updatable if potentially updatable and one table in FROM clause (!) UPDATE TABLE CC_Large SET population = population - 20000 WHERE capital = 'Amsterdam' --has 1011000 inhabitants What happens? © HS-2010 08-PLSQLetc-14 © HS-2010 08-PLSQLetc-17 Key preserved tables CHECK OPTION … SQL 1999: more than one table in FROM clause (2) Column c is updatable if potentially updatable and Update may result in insertion and deletion (!) of rows - c belongs to exactly one table - the key of the table is preserved, i.e. the update of c CHECK OPTION: update and insert must result in rows the may be traced back to exactly one row. view can select , otherwise exception raised Table is key preserved if every key of the table can also Example above: update has to be performed on base table be a key of the join result table. A key-preserved table has its keys preserved through a join. © HS-2010 08-PLSQLetc-15 © HS-2010 08-PLSQLetc-18 3 View update by triggers Business logic Triggers: Event – Condition – Action rules Big question: where sits the "business logic" ? Event: Update, insert, delete (basically) Condition: WHEN < some conditon on table> • Business logic: the steps which have to be Action: some operation ( expressed as DML, DB- made in order to process a user query. Script language expression, even Java) e.g. "go to check out" in an Internet shop is implemented by several steps, most of them access the DB: User logged in? if not..., perform stock keeping operations, prepare INSTEAD OF Triggers (Postgres: rules) invoice, charge client, ..... - defined on views • Two tier or Three tier: ~ business logic separated - specify what to do in case of an update from user interaction as well as data access? of the view details on triggers: see below © HS-2010 08-PLSQLetc-19 © HS-2010 08-PLSQLetc-22 Summary views Architectures • Views: important mechanism for Client server model access protection / privacy – Business logic sits in application program simplyfy SQL application programming – Runs on a machine different from database server – Interaction by means of SQL queries, inserts, updates • The mechanism for defining external schemas in the RDM • Useful for modeling generalization hierarchies • Disadvantage: updates (inserts, deletes) not always Application code possible DB- • Criteria for updatable views complex ... Server • INSTEAD OF triggers are a convenient work around Application code SQL, Result sets User interaction: web browser or integrated (e.g. Swing) © HS-2010 08-PLSQLetc-20 © HS-2010 08-PLSQLetc-23 8.2 Application Architectures Client server example class JdbcTest { • SQL is an interactive language, but... public static void main (String args []) throws SQLException { • Main usage: access database from application program // Load driver DriverManager.registerDriver (new oracle.jdbc.OracleDriver()); Means basically: SQL-statements statically // Connect to the local database Connection conn = known, but parameterized: DriverManager.getConnection ("jdbc:oracle:thin:@myhost:1521:orcl", SELECT name INTO :ctryName "hr", "hr"); FROM Country JOIN Economy ON... // Query the employee names WHERE gdp < :threshold Statement stmt = conn.createStatement (); ResultSet rset = stmt.executeQuery ("SELECT last_name FROM "Impedance mismatch": tuple sets vs records or objects employees"); // Print the name out • Typical database usage: while (rset.next ()) System.out.println (rset.getString (1)); independent applications concurrently access DB // Close the result set, statement, and the connection • Web based user interface is standard today rset.close(); stmt.close(); ⇒ Big differences of (application) system conn.close(); } architectures } © HS-2010 08-PLSQLetc-21 © HS-2010 08-PLSQLetc-24 4 Persistence abstraction mechanisms Server side architectures Object oriented programming model with persistence abstraction hides SQL database access user interaction request handling in web server "Business Logic" Object Basically Generated stored by OR- DB access interface procedures mapping tool Table interface (JDBC) request handling in DB server © HS-2010 08-PLSQLetc-25 © HS-2010 08-PLSQLetc-28 Server side application logic Pros and Cons • Business logic in stored procedures Server based code: +

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    11 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us