SlideShare a Scribd company logo
Optimal Use of Oracle Database 10g and Oracle Database 11g for Modern Application Development Lucas Jellema  AMIS, The Netherlands Oracle Open World, San Francisco September 2008
What is  Modern ? SOA (operational) Analytics event XML SAAS S-Ox/Audit Service MultiMedia Tera Byte 24/7 Global Asynchronous Fuzzy I18n (internationalization) Business Rules Data Integrity Share/Collaboration Enterprise 2.0 Message OO Decoupling Security Personalization Scalability B2B
What is  Modern ? What becomes  possible New functionality in software, new facilities in infrastructure Support for Cloud Computing, Database Accelerator What becomes  affordable Promotion of features from Extra Cost Option to EE to SE What becomes  desirable Encapsulation of SQL, Service Orientation, Active Database  What becomes  inevitable Sarbanes Oxley, 24/7 & global What becomes  visible Subquery Factoring, Instead of Trigger, Ref Cursors, Flashback
Some valuable 11g examples ‘ Total recall’ – Flashback Data Archive Makes Historical Data reliably available, which in turn puts Flashback in the hands of application developers Virtual Columns – organized redundancy and PL/SQL expression based constraints and indexes Compound Trigger – clean work-around for mutating table violation Result Cache – declarative caching of calculated results SQL Query Result Cache & PL/SQL Function Result Cache DBMS_COMPARISON – compare and merge records Continuous Query Notification – alert listeners (PL/SQL and external) of relevant data changes
Several often neglected features Large Volume, Batch Processing Single SQL statement bulk DML/ETL:  Multi Table Insert, Merge,  (pipelined) Table Functions DML error logging Analytical functions Compare between rows  (look forward: lead, look back: lag) Aggregation along several axes and levels in a single query Sub-query factoring Implementing complex query requirements using clear, managable and reusable pieces Case Expression Real If-Then-Else in SQL and PL/SQL (forget DECODE)
Several often neglected features ‘ new’ join syntax  and  outer join functionality Readability, functionality, standardization ‘ Hierarchical Queries’ (especially with sys_connect_by_path and connect_by_root) traverse any network data structure Object Types and Collections Improved integration between SQL and PL/SQL through Bulk Operations, Table & Multiset operators Ref Cursors Make query results available without revealing the SQL for virtually any client (PL/SQL, C, .Net, Java, Ruby, PHP, …) Instead-Of triggers on Views Decouple DML from database design
Other gems worth mentioning Virtual Private Database – foundation for SaaS Database Event Triggers (logon, create/drop/alter, …) COLLECT operator – aggregate into collections dbms_job – key to asynchronous processing Application Context – context sensitive bind-parameter injection in frequently used queries DBMS_APPLICATION_INFO – for instrumentation dbms_epg – publish PL/SQL package through URL Unpivot – turn multiple columns into multiple rows to untangle unfortunate database design Rollup – aggregate at multiple levels in a single query
Statements with regard to Database Database is nothing but a filing cabinet: Data goes in, data comes out; that’s it We should strive for database independence We may want to replace the (relational) database with ‘another data store’ Database portability must be maintained at any cost (vendor independence) We must be able to switch to another database vendor Therefore we should only use functionality that is available in all (mainstream) database products
Trends in the world… Global – multi-timezone, multi-lingual Multi-tier – web user <> database user Resuable functionality available through services SaaS – Software as a Service Single instance of application and database Multiple remote organizations, many remote users Operational BI – analytics on the fly Fading Application boundaries vs. Enterprise Data Standardization – XML, SQL Design Patterns – OO, Encapsulation, Decoupling, Asynchronous, Dependency Injection, Reuse, …
Typical Architecture J(2)EE Application Server Batch Batch Batch Client Enterprise Service Bus DWH ?
What goes where? What is the best place to do things? And what the very worst! Criteria: Functionality Robustness Performance Ease of implementation  and  maintenance Required skills Agility (License) Costs
Some proposed guidelines… No SQL in application Or at the very least centralized No HTML rendering in the database No Data stored on the file system Or anywhere outside the database Except certain application meta-data Database handles data  access authorization Client sets user identity, locale, time and date Database is not accessed from outside the firewall  Bulk data manipulation in the database SQL ?
Developing in the Oracle Database Prepare to be reused, e.g. from web-applications, the SOA environment, batch programs and other clients Hide implementation details (shield from change) Publish reusable APIs Consider REF Cursor and XML Leverage services offered outside the database Guarantee data integrity in the database Do not rely on the clients to implement data rules Instrument – indicate what is going on (and where) Avoid hard coded references and dependencies Including SYSDATE and USER and references to supplied packages – use configurable parameters and wrappers
The client is always right What time is it or at least what is the client’s timezone What locale is it  which language/regional settings apply Where is it located what is the geographical location Who is it web user’s identity <> any database user Note: The database can only serve! Following the client’s lead
Single schema, light weight users End user authenticates through Client with the Mid-tier Mid-tier connects to  RDBMS through pooled  connections to fixed  application schema Mid-tier informs the  database of the ‘client identifier’:  the light-weight client-user-identity, to be read with  SYS_CONTEXT('USERENV‘ ,'CLIENT_IDENTIFIER') J(2)EE Application Server Client LDAP APPLICATION_ SCHEMA USERENV
Set Client Identifier with Light Weight User In Java using Oracle JDBC Driver In PL/SQL Or use a logon trigger to derive the client identifier conn. setClientIdentifier(&quot;john.doe&quot;) DBMS_SESSION.SET_IDENTIFIER( 'john.doe'); CREATE OR REPLACE TRIGGER logon_trigger AFTER LOGON ON DATABASE DECLARE  uid  VARCHAR2(64); BEGIN   SELECT ora_login_user ||':'   ||SYS_CONTEXT('USERENV', 'OS_USER')   INTO uid   FROM dual;   dbms_session.set_identifier(uid); END logon_trigger;
Set Client Identifier with Light Weight User In the database – SQL or PL/SQL – the current client identifier can be read like this: The Client Identifier is also available in V$SESSION as well as V$SQLAREA DBMS_MONITOR. CLIENT_ID_TRACE_ENABLE allows for tracing all activity of a CLIENT_I DENTIIER aka light-weight user Note: Oracle standard auditing does  not  use CLIENT_IDENTIFIER SYS_CONTEXT('USERENV','CLIENT_IDENTIFIER') SELECT sid, client_identifier, service_name FROM  v_$session;
Current User Context Client can set applicable Locale, Organization Id, Timezone in a similar way in an Application Context Or have them derived from the user’s profile that is linked to the user identity The overall user context is  potentially used in many ways Set audit columns (no more USER) Set database (session) timezone Return messages in appropriate language Enforce data authorization Expose Virtual Private Database Attribute Value OrgId 14 Locale fr_ca Timezone +2.00 UserId ljellema
Virtual Private Database and SaaS SaaS applications (pka ASP) have a single application & database instance, used by many remote users Users share the application and the database, yet: Do not share (all) data May have specific application customizations Can define personal translations/renditions of boilerplate Have their own set of user preferences or settings When asked for data from such tables as USER_PREFERENCES, FLEX_ITEMS and MESSAGES the database should apply the current user context to return the appropriate slice of the data
SAAS – MultiOrg - Authorization J(2)EE Application Server A B C Customer C Customer B Customer C setClientIdentifier ORG USER Web Application blindly queries a table for ‘all’ records Based on User Identifier, (in current context) determine Organization Only return records associated with that organization
Implementing ‘Context Awareness’ Oracle Enterprise Edition: Virtual Private Database aka Fine Grained Access Control and Row Level Security define policy and policy function to dynamically add to  where Poor man’s VPD (Standard Edition/Express) Create a view for every  context aware  table Add where clause that filters based on context Have the applications access data through views Create DML triggers on each  context aware   table that raise access violation exception when DML occurs outside of the current user context (e.g. delete data owned by other organization) set context specific columns on newly inserted record – such as USER_ID and/or ORGANIZATION_ID
 
Fuzzy Search - From = to ≈ Many searches do not require only exact matches For example:  we are looking for employees who earn approximately 1500 and started in 1982 or thereabouts Exact match: select * from emp where salary = 1500  AND  extract (year from hiredate) = 1982 Everything in a bandwidth matches: where salary between 1000 and 2000 AND  extract (year from hiredate)   between 1981 and 1983 However: the closer the better Example: Oracle Text (score) and Google
Fuzzy Search - From = to ≈ Our criteria are: Say the salary should be as close as possible to 1500 and be at least between 1000 and 2000  The hiredate should ideally be in 1982; however, 1983 is somewhat acceptable (half the score for 1982) We value a match on salary higher than one on hiredate (twice as important) We want the top 5 scoring Employees score salary 1500 0 1 1000 2000
Scoring on Salary
Scoring on Hiredate
Left Outer Join Left Outer Join is used to state that: After taking every record from EMP Optionally add the sal_around_1500 score Optionally add the emp_hiredate_1982 score Note how the ISO/ANSI SQL (Oracle 9i) join syntax allows continuous joining to multiple sources We can throw in  right outer join  and  full outer join  as well Separate the Join condition and the Where clause
The top 5 of best matching records select * from  ( select ename, score, ...  order by  score desc ) where rownum < 6
Using the number_range_score function
Add the analysis of the score… We appreciate the top5 list of scores However, we would like to see  why  each employee scores as it does How are the scores of 2.2 and 2 for Miller and Turner composed? What if we change the relative weights of the search criteria?
Collecting Employee’s score per criteria For every employee record, we will have multiple scores – one for each search criterium To collect multiple records per single record in one query, we can use the COLLECT aggregator Collecting OBJECT TYPES into a TABLE OF OBJECT TYPE
Collecting Employee’s score per criteria
Slightly nicer layout
Search results – top scoring employees
Add a new search criteria We would prefer CLERKS but can live with ANALYSTS (60%) and SALESMEN (40%) This criteria weighs 1.5 compared Query to add:
Fuzzy Search outcome with 3 criteria - Salary close to 1500 and within 1000-2000 - Hiredate 1982 (or less desirable) 1983 - Job is CLERK, or ANALYST or SALESMAN
Some features used Scalar Subquery select x, (select from) from Collection of Object Type and  Cast operator Collect Aggregator Left outer join In-line subquery:  select x, from (select x from order by) where …
RSS feeds are used to publish “events”
RSS Aggregator Archive Access RSS Feed on the internet Interpret and transform the XML data Publish the RSS Feed as queryable view in the database Combine multiple RSS Feeds Archive the RSS Feeds in a central table – updating changed items, inserting new ones Periodically scan RSS Feeds and update archive Complete transaction even in the face of constraint violations
The browser in your database Introducing UTL_HTTP ≈ select  utl_http.request ( 'http://technology.amis.nl/blog/?feed=rss2' , null ) from  dual
Whatever the browser recives from a URL, the UTL_HTTP receives too
Example UTL_HTTP code: processing response SET serveroutput ON SIZE 40000  DECLARE pieces utl_http.html_pieces; n  number default 0; resp utl_http.resp; BEGIN pieces := utl_http.request_pieces ( url => 'www.someurl.com' , max_pieces => 9999 , proxy => null ); for i in 1..pieces.count loop loop exit when pieces(i) is null; dbms_output.put_line(substr(pieces(i),1,255)); pieces(i):= substr(pieces(i),256); END LOOP; end loop; END;
Database can call out through UTL_HTTP Application Server Servlet (intranet) WebService BPEL Process ESB Service These services in turn can do many things, such as Send email, send chat-message, access database, call external WebService, read/write file system, access EJB or .NET based services, contact FTP server, deal with SAP Internet (though that is not a decoupled thing to do) RSS feed WebService Web Site  Note: HTTP Get requests can also be performed by: dbms_xmlparser.parse(url) HTTPURITYPE(url) Oracle Text (index external docs) utl_tcp, stored Java
Publish RSS as “view” inside database create view AMIS_WEBLOG_FEED as select title ,  link ,  author ,  to_date(substr(publication_date,6,20)   ,'dd mon yyyy hh24:mi:ss') timest from  xmltable   ( XMLNAMESPACES('http://purl.org/dc/elements/1.1/' AS &quot;dc&quot;)   , 'for $i in //item return <Article>{$i/title}{$i/dc:creator}   {$i/pubDate}{$i/link}   </Article> '  passing   httpuritype('http://technology.amis.nl/blog/?feed=rss2').getXML() COLUMNS title  varchar2(100) path 'title' , link  varchar2(100) path 'link' , author  varchar2(100) path 'dc:creator' , publication_date varchar2(100) path 'pubDate' )
Publish RSS as “view” inside database create view AMIS_WEBLOG_FEED as select title ,  link ,  author ,  to_date(substr(publication_date,6,20)   ,'dd mon yyyy hh24:mi:ss') timest from  xmltable   ( XMLNAMESPACES('http://purl.org/dc/elements/1.1/' AS &quot;dc&quot;)   , 'for $i in //item return <Article>{$i/title}{$i/dc:creator}   {$i/pubDate}{$i/link}   </Article> '  passing   httpuritype('http://technology.amis.nl/blog/?feed=rss2').getXML() COLUMNS title  varchar2(100) path 'title' , link  varchar2(100) path 'link' , author  varchar2(100) path 'dc:creator' , publication_date varchar2(100) path 'pubDate' )
Aggregating Feeds into Central Archive Central table to archive all RSS News Items Keep items available after  RSS feed ‘has moved on’ RSS_ARCHIVE
Aggregating Feeds into Central Archive New(s) items must be inserted, existing can be updated Source is join between RSS_FEEDS and XMLTable based on external RSS feed
Aggregating Feeds into Central Archive Run a job – scheduled, in the background Create Schedule – when to trigger execution Create stored procedure SCAN_RSS_FEEDS that executes the MERGE statement and commits Create Program – what action to take
Aggregating Feeds into Central Archive Run a job – scheduled, in the background Create Job – link Schedule (when) and Program (what) Sit back and relax  (and perhaps  check on job)
Please, no more stories on … Create a check constraint on the RSS_ARCHIVE: No stories with Palin, Biden, Obama or McCain in the title! However, the background job issues a single MERGE statement to refresh the archive table That will fail as long as the collective feeds contain only one article that violates the CHECK CONSTRAINT Surely that is not what you would want to happen?
Complete DML statement – log errors Oracle 10gR2 introduced ‘DML Error log’ Create an error log  table Indicate for a DML  statement that exceptions should be logged to the table while the statement may continue and complete successfully
RSS Archive – Features Used UTL_HTTP, httpuritype XMLDB: XMLTable, XQuery DBMS_SCHEDULER Regular Expression in Check Constraint (REGEXP_LIKE) MERGE DML ERROR LOG
Expose recent HRM Data Changes Several parties are interested in all changes in the area of Human Resources  (table EMP & DEPT) We have received a request to make an overview of all recent changes available, preferably in XML format
Our first thought – using triggers After Insert/Update/Delete trigger for each row Record change in table EMP_CHANGE_LOG Part of the same transaction as the change(s) However: Adds overhead to the DML operation Requires a trigger on every table for which changes must be exposed And if a trigger is disabled, changes are not logged Requires an additional (log) table for each table And it can be done much more elegantly….
Flashback Versions Retrieve all states each record has been in Every transaction that touched a row left a version of it Pseudocolumns: xid, operation, starttime, endtime Note: depends on the availability of UNDO or Flashback data; using 11g Flashback Archive is a way to ensure that on a per table basis
Example of Employee Versions
Finding the biggest salary raise ever Analytical Function LEAD (looks to the next row) Get SALARY in the version that comes after the current row (when sorted by starttime descending)
Expose HRM Changes in XML document Create package HRM_CHANGE_HISTORY Containing procedure EMP_HISTORY that writes an XML document to htp.p with Employee change records Using DBMS_EPG Create DAD  hrmhistory  on path /hrm/* Authorize DAD  hrmhistory  for schema SCOTT Access URL  http://localhost:2100/hrm/scott. hrm_change_history.emp_history J(2)EE Application Server http://host/../emp_history
Pull EMP change overview from browser
Pull model: DBMS_EPG/Web Toolkit Pull model means create on request Always the most fresh data Potentially large load on the database  as for every request the  XML document is recreated Document is retrieved  through a download by  an HTTP client Alternative: push (publish) model Periodically create the XML document Make it available to various clients On the file system, on the web J(2)EE Application Server XDB Folder WEBDAV FTP HTTP PL/SQL SQL
Periodically publish XML Report Create XML DB Folder Is also a ‘directory page’ via HTTP And a WEBDAV folder And an FTP directory Schedule Job to Create  Resource in the XDB Folder Based on XMLType: the result of  a query that collects the desired data To access: Go to URL & open in browser Map Network Drive via WEBDAV Open FTP session J(2)EE Application Server XDB Folder WEBDAV FTP HTTP PL/SQL SQL
Create XML Resource DECLARE CURSOR xmlcur IS   SELECT xmlelement(&quot;EMPHISTORY&quot;, ...   l_xml_dir  VARCHAR2(30) := '/public/hrmData'; l_doc_name VARCHAR2(30) := 'EmpChangeHistory.xml'; l_emp  xmltype;  l_res  boolean BEGIN IF dbms_xdb.CreateFolder(l_xml_dir)  THEN ... some ACL setting up END IF;   open xmlcur; fetch xmlcur into l_emp; close xmlcur; l_res := dbms_xdb.createResource ( abspath=> l_xml_dir||l_doc_name  , data=> l_emp ); COMMIT; end;
HRM Report via WEBDAV, SQL & HTTP
Viewing&Editing XDB Resource in Excel
Uploading data from file to database
Some features used Flashback Versions Analytical Functions  SQL/XML and XMLType Publish database service on the web: DBMS_EPG XML DB Publish (FTP/WebDav/HTTP) Resource Access XMLDB resource through SQL, PL/SQL, WebDAV (Excel, Windows Explorer) and HTML (Browser)
Summary Modern  is determined by what you can do, can afford, have a need or demand for and consider best practice Main trend: Service or Interface orientation Clear, reusable interface Hide implementation details Loose coupling, reduced dependency Standardized contract, communication Cater for various client technologies & protocols SQL/PLSQL, .NET, Java/JDBC, XML, HTTP, WebDAV,  Inside database, benefit from external services through HTTP Make database  context aware  (who, when, where)  Continually appreciate the power and richness of SQL
Want to know more? Find this presentation and all scripts Or read our articles at Oracle Database,  SQL & PL/SQL ADF APEX SOA Suite: BPEL,  EBS, BAM, … and many other  Oracle related  topics…
 

More Related Content

PPT
The Story of How an Oracle Classic Stronghold successfully embraced SOA
PPTX
The Story of How an Oracle Classic Stronghold successfully embraced SOA (ODTU...
PPTX
PPTX
Roles y Responsabilidades en SQL Azure
PPTX
PPTX
PPTX
CloudConnect 2011 - Building Highly Scalable Java Applications on Windows Azure
PPT
Introduction To Sql Services
The Story of How an Oracle Classic Stronghold successfully embraced SOA
The Story of How an Oracle Classic Stronghold successfully embraced SOA (ODTU...
Roles y Responsabilidades en SQL Azure
CloudConnect 2011 - Building Highly Scalable Java Applications on Windows Azure
Introduction To Sql Services

What's hot (20)

PDF
dvprimer-concepts
PPTX
Kaashiv SQL Server Interview Questions Presentation
PPTX
Building applications using sql azure
PPTX
Overview of atg framework
PPTX
ATG Architecture
PPTX
Introduction to microsoft sql server 2008 r2
ODP
ZK MVVM, Spring & JPA On Two PaaS Clouds
PDF
Data Virtualization Primer -
PPTX
ATG Framework,Formhandlers,Pricing
PDF
As 400
PPTX
JAX-RS. Developing RESTful APIs with Java
PPTX
Microsoft SQL Azure - Building Applications Using SQL Azure Presentation
PPTX
EMC ECD Documentum D2
PPT
Oracle SOA Suite 11g Mediator vs. Oracle Service Bus (OSB)
ODP
Creating Flexible Data Services For Enterprise Soa With Wso2 Data Services
DOCX
Kiran_Patil_JavaDeveloper
PPTX
ATG - Web Commerce @ Your Figertips
PPTX
Representational State Transfer
PDF
quickguide-einnovator-5-springxd
PPTX
dvprimer-concepts
Kaashiv SQL Server Interview Questions Presentation
Building applications using sql azure
Overview of atg framework
ATG Architecture
Introduction to microsoft sql server 2008 r2
ZK MVVM, Spring & JPA On Two PaaS Clouds
Data Virtualization Primer -
ATG Framework,Formhandlers,Pricing
As 400
JAX-RS. Developing RESTful APIs with Java
Microsoft SQL Azure - Building Applications Using SQL Azure Presentation
EMC ECD Documentum D2
Oracle SOA Suite 11g Mediator vs. Oracle Service Bus (OSB)
Creating Flexible Data Services For Enterprise Soa With Wso2 Data Services
Kiran_Patil_JavaDeveloper
ATG - Web Commerce @ Your Figertips
Representational State Transfer
quickguide-einnovator-5-springxd
Ad

Viewers also liked (14)

PPT
Chap02: The database Development process
PDF
数据库Sharding专题
PDF
基于MySQL的分布式数据库实践
PPTX
大型电商的数据服务的要点和难点
PPT
Database Design Process
PPT
Modern database management jeffrey a. hoffer, mary b. prescott,
PPTX
Database design process
PDF
唯品会大数据实践 Sacc pub
PDF
豆瓣数据架构实践
PDF
MySQL数据库设计、优化
PPS
Database Design Slide 1
PDF
MySQL技术分享:一步到位实现mysql优化
PPT
964 database development process intro1
PPT
Database Development Process
Chap02: The database Development process
数据库Sharding专题
基于MySQL的分布式数据库实践
大型电商的数据服务的要点和难点
Database Design Process
Modern database management jeffrey a. hoffer, mary b. prescott,
Database design process
唯品会大数据实践 Sacc pub
豆瓣数据架构实践
MySQL数据库设计、优化
Database Design Slide 1
MySQL技术分享:一步到位实现mysql优化
964 database development process intro1
Database Development Process
Ad

Similar to Modern Database Development Oow2008 Lucas Jellema (20)

PPTX
The Evolution of the Oracle Database - Then, Now and Later (Fontys Hogeschool...
PPT
High Performance Jdbc
PPT
PDoolan Oracle Overview PPT Version
PDF
PPTX
The Very Very Latest In Database Development - Lucas Jellema - Oracle OpenWor...
PPTX
The Very Very Latest in Database Development - Oracle Open World 2012
PPT
SQL Server 2008 for .NET Developers
PPT
Tech Days09 Sqldev
PPT
SQL Server 2008 for Developers
PDF
PPTX
An AMIS Overview of Oracle database 12c (12.1)
PPTX
Fontys Lecture - The Evolution of the Oracle Database 2016
PPTX
Oracle's history
PDF
Are we there Yet?? (The long journey of Migrating from close source to opens...
PPT
PPT
Offshore Recruiting Training Material
PDF
19 features you will miss if you leave Oracle Database
PPTX
ODTUG_NoPlsql_vs_SmartDB_Part1_and_2.pptx
DOC
DBMS Practical File
PPT
Jdbc Dao it-slideshares.blogspot.com
The Evolution of the Oracle Database - Then, Now and Later (Fontys Hogeschool...
High Performance Jdbc
PDoolan Oracle Overview PPT Version
The Very Very Latest In Database Development - Lucas Jellema - Oracle OpenWor...
The Very Very Latest in Database Development - Oracle Open World 2012
SQL Server 2008 for .NET Developers
Tech Days09 Sqldev
SQL Server 2008 for Developers
An AMIS Overview of Oracle database 12c (12.1)
Fontys Lecture - The Evolution of the Oracle Database 2016
Oracle's history
Are we there Yet?? (The long journey of Migrating from close source to opens...
Offshore Recruiting Training Material
19 features you will miss if you leave Oracle Database
ODTUG_NoPlsql_vs_SmartDB_Part1_and_2.pptx
DBMS Practical File
Jdbc Dao it-slideshares.blogspot.com

More from Lucas Jellema (20)

PPTX
Introduction to web application development with Vue (for absolute beginners)...
PPTX
Making the Shift Left - Bringing Ops to Dev before bringing applications to p...
PPTX
Lightweight coding in powerful Cloud Development Environments (DigitalXchange...
PPTX
Apache Superset - open source data exploration and visualization (Conclusion ...
PPTX
CONNECTING THE REAL WORLD TO ENTERPRISE IT – HOW IoT DRIVES OUR ENERGY TRANSI...
PPTX
Help me move away from Oracle - or not?! (Oracle Community Tour EMEA - LVOUG...
PPTX
Op je vingers tellen... tot 1000!
PPTX
IoT - from prototype to enterprise platform (DigitalXchange 2022)
PPTX
Who Wants to Become an IT Architect-A Look at the Bigger Picture - DigitalXch...
PPTX
Steampipe - use SQL to retrieve data from cloud, platforms and files (Code Ca...
PPTX
Automation of Software Engineering with OCI DevOps Build and Deployment Pipel...
PPTX
Introducing Dapr.io - the open source personal assistant to microservices and...
PPTX
How and Why you can and should Participate in Open Source Projects (AMIS, Sof...
PPTX
Microservices, Apache Kafka, Node, Dapr and more - Part Two (Fontys Hogeschoo...
PPTX
Microservices, Node, Dapr and more - Part One (Fontys Hogeschool, Spring 2022)
PPTX
6Reinventing Oracle Systems in a Cloudy World (RMOUG Trainingdays, February 2...
PPTX
Help me move away from Oracle! (RMOUG Training Days 2022, February 2022)
PPTX
Tech Talks 101 - DevOps (jan 2022)
PPTX
Conclusion Code Cafe - Microcks for Mocking and Testing Async APIs (January 2...
PPTX
Cloud Native Application Development - build fast, low TCO, scalable & agile ...
Introduction to web application development with Vue (for absolute beginners)...
Making the Shift Left - Bringing Ops to Dev before bringing applications to p...
Lightweight coding in powerful Cloud Development Environments (DigitalXchange...
Apache Superset - open source data exploration and visualization (Conclusion ...
CONNECTING THE REAL WORLD TO ENTERPRISE IT – HOW IoT DRIVES OUR ENERGY TRANSI...
Help me move away from Oracle - or not?! (Oracle Community Tour EMEA - LVOUG...
Op je vingers tellen... tot 1000!
IoT - from prototype to enterprise platform (DigitalXchange 2022)
Who Wants to Become an IT Architect-A Look at the Bigger Picture - DigitalXch...
Steampipe - use SQL to retrieve data from cloud, platforms and files (Code Ca...
Automation of Software Engineering with OCI DevOps Build and Deployment Pipel...
Introducing Dapr.io - the open source personal assistant to microservices and...
How and Why you can and should Participate in Open Source Projects (AMIS, Sof...
Microservices, Apache Kafka, Node, Dapr and more - Part Two (Fontys Hogeschoo...
Microservices, Node, Dapr and more - Part One (Fontys Hogeschool, Spring 2022)
6Reinventing Oracle Systems in a Cloudy World (RMOUG Trainingdays, February 2...
Help me move away from Oracle! (RMOUG Training Days 2022, February 2022)
Tech Talks 101 - DevOps (jan 2022)
Conclusion Code Cafe - Microcks for Mocking and Testing Async APIs (January 2...
Cloud Native Application Development - build fast, low TCO, scalable & agile ...

Recently uploaded (20)

PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Approach and Philosophy of On baking technology
PDF
cuic standard and advanced reporting.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
NewMind AI Monthly Chronicles - July 2025
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Empathic Computing: Creating Shared Understanding
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
The Rise and Fall of 3GPP – Time for a Sabbatical?
“AI and Expert System Decision Support & Business Intelligence Systems”
Diabetes mellitus diagnosis method based random forest with bat algorithm
Chapter 3 Spatial Domain Image Processing.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
The AUB Centre for AI in Media Proposal.docx
Approach and Philosophy of On baking technology
cuic standard and advanced reporting.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
NewMind AI Monthly Chronicles - July 2025
MYSQL Presentation for SQL database connectivity
Review of recent advances in non-invasive hemoglobin estimation
Advanced methodologies resolving dimensionality complications for autism neur...
Spectral efficient network and resource selection model in 5G networks
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Digital-Transformation-Roadmap-for-Companies.pptx
Empathic Computing: Creating Shared Understanding
Unlocking AI with Model Context Protocol (MCP)
Encapsulation_ Review paper, used for researhc scholars
Dropbox Q2 2025 Financial Results & Investor Presentation

Modern Database Development Oow2008 Lucas Jellema

  • 1. Optimal Use of Oracle Database 10g and Oracle Database 11g for Modern Application Development Lucas Jellema AMIS, The Netherlands Oracle Open World, San Francisco September 2008
  • 2. What is Modern ? SOA (operational) Analytics event XML SAAS S-Ox/Audit Service MultiMedia Tera Byte 24/7 Global Asynchronous Fuzzy I18n (internationalization) Business Rules Data Integrity Share/Collaboration Enterprise 2.0 Message OO Decoupling Security Personalization Scalability B2B
  • 3. What is Modern ? What becomes possible New functionality in software, new facilities in infrastructure Support for Cloud Computing, Database Accelerator What becomes affordable Promotion of features from Extra Cost Option to EE to SE What becomes desirable Encapsulation of SQL, Service Orientation, Active Database What becomes inevitable Sarbanes Oxley, 24/7 & global What becomes visible Subquery Factoring, Instead of Trigger, Ref Cursors, Flashback
  • 4. Some valuable 11g examples ‘ Total recall’ – Flashback Data Archive Makes Historical Data reliably available, which in turn puts Flashback in the hands of application developers Virtual Columns – organized redundancy and PL/SQL expression based constraints and indexes Compound Trigger – clean work-around for mutating table violation Result Cache – declarative caching of calculated results SQL Query Result Cache & PL/SQL Function Result Cache DBMS_COMPARISON – compare and merge records Continuous Query Notification – alert listeners (PL/SQL and external) of relevant data changes
  • 5. Several often neglected features Large Volume, Batch Processing Single SQL statement bulk DML/ETL: Multi Table Insert, Merge, (pipelined) Table Functions DML error logging Analytical functions Compare between rows (look forward: lead, look back: lag) Aggregation along several axes and levels in a single query Sub-query factoring Implementing complex query requirements using clear, managable and reusable pieces Case Expression Real If-Then-Else in SQL and PL/SQL (forget DECODE)
  • 6. Several often neglected features ‘ new’ join syntax and outer join functionality Readability, functionality, standardization ‘ Hierarchical Queries’ (especially with sys_connect_by_path and connect_by_root) traverse any network data structure Object Types and Collections Improved integration between SQL and PL/SQL through Bulk Operations, Table & Multiset operators Ref Cursors Make query results available without revealing the SQL for virtually any client (PL/SQL, C, .Net, Java, Ruby, PHP, …) Instead-Of triggers on Views Decouple DML from database design
  • 7. Other gems worth mentioning Virtual Private Database – foundation for SaaS Database Event Triggers (logon, create/drop/alter, …) COLLECT operator – aggregate into collections dbms_job – key to asynchronous processing Application Context – context sensitive bind-parameter injection in frequently used queries DBMS_APPLICATION_INFO – for instrumentation dbms_epg – publish PL/SQL package through URL Unpivot – turn multiple columns into multiple rows to untangle unfortunate database design Rollup – aggregate at multiple levels in a single query
  • 8. Statements with regard to Database Database is nothing but a filing cabinet: Data goes in, data comes out; that’s it We should strive for database independence We may want to replace the (relational) database with ‘another data store’ Database portability must be maintained at any cost (vendor independence) We must be able to switch to another database vendor Therefore we should only use functionality that is available in all (mainstream) database products
  • 9. Trends in the world… Global – multi-timezone, multi-lingual Multi-tier – web user <> database user Resuable functionality available through services SaaS – Software as a Service Single instance of application and database Multiple remote organizations, many remote users Operational BI – analytics on the fly Fading Application boundaries vs. Enterprise Data Standardization – XML, SQL Design Patterns – OO, Encapsulation, Decoupling, Asynchronous, Dependency Injection, Reuse, …
  • 10. Typical Architecture J(2)EE Application Server Batch Batch Batch Client Enterprise Service Bus DWH ?
  • 11. What goes where? What is the best place to do things? And what the very worst! Criteria: Functionality Robustness Performance Ease of implementation and maintenance Required skills Agility (License) Costs
  • 12. Some proposed guidelines… No SQL in application Or at the very least centralized No HTML rendering in the database No Data stored on the file system Or anywhere outside the database Except certain application meta-data Database handles data access authorization Client sets user identity, locale, time and date Database is not accessed from outside the firewall Bulk data manipulation in the database SQL ?
  • 13. Developing in the Oracle Database Prepare to be reused, e.g. from web-applications, the SOA environment, batch programs and other clients Hide implementation details (shield from change) Publish reusable APIs Consider REF Cursor and XML Leverage services offered outside the database Guarantee data integrity in the database Do not rely on the clients to implement data rules Instrument – indicate what is going on (and where) Avoid hard coded references and dependencies Including SYSDATE and USER and references to supplied packages – use configurable parameters and wrappers
  • 14. The client is always right What time is it or at least what is the client’s timezone What locale is it which language/regional settings apply Where is it located what is the geographical location Who is it web user’s identity <> any database user Note: The database can only serve! Following the client’s lead
  • 15. Single schema, light weight users End user authenticates through Client with the Mid-tier Mid-tier connects to RDBMS through pooled connections to fixed application schema Mid-tier informs the database of the ‘client identifier’: the light-weight client-user-identity, to be read with SYS_CONTEXT('USERENV‘ ,'CLIENT_IDENTIFIER') J(2)EE Application Server Client LDAP APPLICATION_ SCHEMA USERENV
  • 16. Set Client Identifier with Light Weight User In Java using Oracle JDBC Driver In PL/SQL Or use a logon trigger to derive the client identifier conn. setClientIdentifier(&quot;john.doe&quot;) DBMS_SESSION.SET_IDENTIFIER( 'john.doe'); CREATE OR REPLACE TRIGGER logon_trigger AFTER LOGON ON DATABASE DECLARE  uid  VARCHAR2(64); BEGIN   SELECT ora_login_user ||':' ||SYS_CONTEXT('USERENV', 'OS_USER')   INTO uid   FROM dual;   dbms_session.set_identifier(uid); END logon_trigger;
  • 17. Set Client Identifier with Light Weight User In the database – SQL or PL/SQL – the current client identifier can be read like this: The Client Identifier is also available in V$SESSION as well as V$SQLAREA DBMS_MONITOR. CLIENT_ID_TRACE_ENABLE allows for tracing all activity of a CLIENT_I DENTIIER aka light-weight user Note: Oracle standard auditing does not use CLIENT_IDENTIFIER SYS_CONTEXT('USERENV','CLIENT_IDENTIFIER') SELECT sid, client_identifier, service_name FROM v_$session;
  • 18. Current User Context Client can set applicable Locale, Organization Id, Timezone in a similar way in an Application Context Or have them derived from the user’s profile that is linked to the user identity The overall user context is potentially used in many ways Set audit columns (no more USER) Set database (session) timezone Return messages in appropriate language Enforce data authorization Expose Virtual Private Database Attribute Value OrgId 14 Locale fr_ca Timezone +2.00 UserId ljellema
  • 19. Virtual Private Database and SaaS SaaS applications (pka ASP) have a single application & database instance, used by many remote users Users share the application and the database, yet: Do not share (all) data May have specific application customizations Can define personal translations/renditions of boilerplate Have their own set of user preferences or settings When asked for data from such tables as USER_PREFERENCES, FLEX_ITEMS and MESSAGES the database should apply the current user context to return the appropriate slice of the data
  • 20. SAAS – MultiOrg - Authorization J(2)EE Application Server A B C Customer C Customer B Customer C setClientIdentifier ORG USER Web Application blindly queries a table for ‘all’ records Based on User Identifier, (in current context) determine Organization Only return records associated with that organization
  • 21. Implementing ‘Context Awareness’ Oracle Enterprise Edition: Virtual Private Database aka Fine Grained Access Control and Row Level Security define policy and policy function to dynamically add to where Poor man’s VPD (Standard Edition/Express) Create a view for every context aware table Add where clause that filters based on context Have the applications access data through views Create DML triggers on each context aware table that raise access violation exception when DML occurs outside of the current user context (e.g. delete data owned by other organization) set context specific columns on newly inserted record – such as USER_ID and/or ORGANIZATION_ID
  • 22.  
  • 23. Fuzzy Search - From = to ≈ Many searches do not require only exact matches For example: we are looking for employees who earn approximately 1500 and started in 1982 or thereabouts Exact match: select * from emp where salary = 1500 AND extract (year from hiredate) = 1982 Everything in a bandwidth matches: where salary between 1000 and 2000 AND extract (year from hiredate) between 1981 and 1983 However: the closer the better Example: Oracle Text (score) and Google
  • 24. Fuzzy Search - From = to ≈ Our criteria are: Say the salary should be as close as possible to 1500 and be at least between 1000 and 2000 The hiredate should ideally be in 1982; however, 1983 is somewhat acceptable (half the score for 1982) We value a match on salary higher than one on hiredate (twice as important) We want the top 5 scoring Employees score salary 1500 0 1 1000 2000
  • 27. Left Outer Join Left Outer Join is used to state that: After taking every record from EMP Optionally add the sal_around_1500 score Optionally add the emp_hiredate_1982 score Note how the ISO/ANSI SQL (Oracle 9i) join syntax allows continuous joining to multiple sources We can throw in right outer join and full outer join as well Separate the Join condition and the Where clause
  • 28. The top 5 of best matching records select * from ( select ename, score, ... order by score desc ) where rownum < 6
  • 30. Add the analysis of the score… We appreciate the top5 list of scores However, we would like to see why each employee scores as it does How are the scores of 2.2 and 2 for Miller and Turner composed? What if we change the relative weights of the search criteria?
  • 31. Collecting Employee’s score per criteria For every employee record, we will have multiple scores – one for each search criterium To collect multiple records per single record in one query, we can use the COLLECT aggregator Collecting OBJECT TYPES into a TABLE OF OBJECT TYPE
  • 34. Search results – top scoring employees
  • 35. Add a new search criteria We would prefer CLERKS but can live with ANALYSTS (60%) and SALESMEN (40%) This criteria weighs 1.5 compared Query to add:
  • 36. Fuzzy Search outcome with 3 criteria - Salary close to 1500 and within 1000-2000 - Hiredate 1982 (or less desirable) 1983 - Job is CLERK, or ANALYST or SALESMAN
  • 37. Some features used Scalar Subquery select x, (select from) from Collection of Object Type and Cast operator Collect Aggregator Left outer join In-line subquery: select x, from (select x from order by) where …
  • 38. RSS feeds are used to publish “events”
  • 39. RSS Aggregator Archive Access RSS Feed on the internet Interpret and transform the XML data Publish the RSS Feed as queryable view in the database Combine multiple RSS Feeds Archive the RSS Feeds in a central table – updating changed items, inserting new ones Periodically scan RSS Feeds and update archive Complete transaction even in the face of constraint violations
  • 40. The browser in your database Introducing UTL_HTTP ≈ select utl_http.request ( 'http://technology.amis.nl/blog/?feed=rss2' , null ) from dual
  • 41. Whatever the browser recives from a URL, the UTL_HTTP receives too
  • 42. Example UTL_HTTP code: processing response SET serveroutput ON SIZE 40000 DECLARE pieces utl_http.html_pieces; n number default 0; resp utl_http.resp; BEGIN pieces := utl_http.request_pieces ( url => 'www.someurl.com' , max_pieces => 9999 , proxy => null ); for i in 1..pieces.count loop loop exit when pieces(i) is null; dbms_output.put_line(substr(pieces(i),1,255)); pieces(i):= substr(pieces(i),256); END LOOP; end loop; END;
  • 43. Database can call out through UTL_HTTP Application Server Servlet (intranet) WebService BPEL Process ESB Service These services in turn can do many things, such as Send email, send chat-message, access database, call external WebService, read/write file system, access EJB or .NET based services, contact FTP server, deal with SAP Internet (though that is not a decoupled thing to do) RSS feed WebService Web Site Note: HTTP Get requests can also be performed by: dbms_xmlparser.parse(url) HTTPURITYPE(url) Oracle Text (index external docs) utl_tcp, stored Java
  • 44. Publish RSS as “view” inside database create view AMIS_WEBLOG_FEED as select title , link , author , to_date(substr(publication_date,6,20) ,'dd mon yyyy hh24:mi:ss') timest from xmltable ( XMLNAMESPACES('http://purl.org/dc/elements/1.1/' AS &quot;dc&quot;) , 'for $i in //item return <Article>{$i/title}{$i/dc:creator} {$i/pubDate}{$i/link} </Article> ' passing httpuritype('http://technology.amis.nl/blog/?feed=rss2').getXML() COLUMNS title varchar2(100) path 'title' , link varchar2(100) path 'link' , author varchar2(100) path 'dc:creator' , publication_date varchar2(100) path 'pubDate' )
  • 45. Publish RSS as “view” inside database create view AMIS_WEBLOG_FEED as select title , link , author , to_date(substr(publication_date,6,20) ,'dd mon yyyy hh24:mi:ss') timest from xmltable ( XMLNAMESPACES('http://purl.org/dc/elements/1.1/' AS &quot;dc&quot;) , 'for $i in //item return <Article>{$i/title}{$i/dc:creator} {$i/pubDate}{$i/link} </Article> ' passing httpuritype('http://technology.amis.nl/blog/?feed=rss2').getXML() COLUMNS title varchar2(100) path 'title' , link varchar2(100) path 'link' , author varchar2(100) path 'dc:creator' , publication_date varchar2(100) path 'pubDate' )
  • 46. Aggregating Feeds into Central Archive Central table to archive all RSS News Items Keep items available after RSS feed ‘has moved on’ RSS_ARCHIVE
  • 47. Aggregating Feeds into Central Archive New(s) items must be inserted, existing can be updated Source is join between RSS_FEEDS and XMLTable based on external RSS feed
  • 48. Aggregating Feeds into Central Archive Run a job – scheduled, in the background Create Schedule – when to trigger execution Create stored procedure SCAN_RSS_FEEDS that executes the MERGE statement and commits Create Program – what action to take
  • 49. Aggregating Feeds into Central Archive Run a job – scheduled, in the background Create Job – link Schedule (when) and Program (what) Sit back and relax (and perhaps check on job)
  • 50. Please, no more stories on … Create a check constraint on the RSS_ARCHIVE: No stories with Palin, Biden, Obama or McCain in the title! However, the background job issues a single MERGE statement to refresh the archive table That will fail as long as the collective feeds contain only one article that violates the CHECK CONSTRAINT Surely that is not what you would want to happen?
  • 51. Complete DML statement – log errors Oracle 10gR2 introduced ‘DML Error log’ Create an error log table Indicate for a DML statement that exceptions should be logged to the table while the statement may continue and complete successfully
  • 52. RSS Archive – Features Used UTL_HTTP, httpuritype XMLDB: XMLTable, XQuery DBMS_SCHEDULER Regular Expression in Check Constraint (REGEXP_LIKE) MERGE DML ERROR LOG
  • 53. Expose recent HRM Data Changes Several parties are interested in all changes in the area of Human Resources (table EMP & DEPT) We have received a request to make an overview of all recent changes available, preferably in XML format
  • 54. Our first thought – using triggers After Insert/Update/Delete trigger for each row Record change in table EMP_CHANGE_LOG Part of the same transaction as the change(s) However: Adds overhead to the DML operation Requires a trigger on every table for which changes must be exposed And if a trigger is disabled, changes are not logged Requires an additional (log) table for each table And it can be done much more elegantly….
  • 55. Flashback Versions Retrieve all states each record has been in Every transaction that touched a row left a version of it Pseudocolumns: xid, operation, starttime, endtime Note: depends on the availability of UNDO or Flashback data; using 11g Flashback Archive is a way to ensure that on a per table basis
  • 57. Finding the biggest salary raise ever Analytical Function LEAD (looks to the next row) Get SALARY in the version that comes after the current row (when sorted by starttime descending)
  • 58. Expose HRM Changes in XML document Create package HRM_CHANGE_HISTORY Containing procedure EMP_HISTORY that writes an XML document to htp.p with Employee change records Using DBMS_EPG Create DAD hrmhistory on path /hrm/* Authorize DAD hrmhistory for schema SCOTT Access URL http://localhost:2100/hrm/scott. hrm_change_history.emp_history J(2)EE Application Server http://host/../emp_history
  • 59. Pull EMP change overview from browser
  • 60. Pull model: DBMS_EPG/Web Toolkit Pull model means create on request Always the most fresh data Potentially large load on the database as for every request the XML document is recreated Document is retrieved through a download by an HTTP client Alternative: push (publish) model Periodically create the XML document Make it available to various clients On the file system, on the web J(2)EE Application Server XDB Folder WEBDAV FTP HTTP PL/SQL SQL
  • 61. Periodically publish XML Report Create XML DB Folder Is also a ‘directory page’ via HTTP And a WEBDAV folder And an FTP directory Schedule Job to Create Resource in the XDB Folder Based on XMLType: the result of a query that collects the desired data To access: Go to URL & open in browser Map Network Drive via WEBDAV Open FTP session J(2)EE Application Server XDB Folder WEBDAV FTP HTTP PL/SQL SQL
  • 62. Create XML Resource DECLARE CURSOR xmlcur IS SELECT xmlelement(&quot;EMPHISTORY&quot;, ... l_xml_dir VARCHAR2(30) := '/public/hrmData'; l_doc_name VARCHAR2(30) := 'EmpChangeHistory.xml'; l_emp xmltype; l_res boolean BEGIN IF dbms_xdb.CreateFolder(l_xml_dir) THEN ... some ACL setting up END IF; open xmlcur; fetch xmlcur into l_emp; close xmlcur; l_res := dbms_xdb.createResource ( abspath=> l_xml_dir||l_doc_name , data=> l_emp ); COMMIT; end;
  • 63. HRM Report via WEBDAV, SQL & HTTP
  • 65. Uploading data from file to database
  • 66. Some features used Flashback Versions Analytical Functions SQL/XML and XMLType Publish database service on the web: DBMS_EPG XML DB Publish (FTP/WebDav/HTTP) Resource Access XMLDB resource through SQL, PL/SQL, WebDAV (Excel, Windows Explorer) and HTML (Browser)
  • 67. Summary Modern is determined by what you can do, can afford, have a need or demand for and consider best practice Main trend: Service or Interface orientation Clear, reusable interface Hide implementation details Loose coupling, reduced dependency Standardized contract, communication Cater for various client technologies & protocols SQL/PLSQL, .NET, Java/JDBC, XML, HTTP, WebDAV, Inside database, benefit from external services through HTTP Make database context aware (who, when, where) Continually appreciate the power and richness of SQL
  • 68. Want to know more? Find this presentation and all scripts Or read our articles at Oracle Database, SQL & PL/SQL ADF APEX SOA Suite: BPEL, EBS, BAM, … and many other Oracle related topics…
  • 69.  

Editor's Notes

  • #2: This presentation goes into the many--relatively unknown--features in the recent Oracle Database releases that can help complex Web application development. You can do so much more in the database than most Java developers realize. The session shows some useful tricks for leveraging the database, such as view and IOT, PL/SQL collections and table function/MULTISET, application context, factored (inline) queries, outer joins.