SlideShare a Scribd company logo
Reaching Out From PL/SQL (OPP 2010)
Reaching Out
from PL/SQL
Engaging with the world
Do not ask what your
country can do for
you
Ask what you can do for your
country?!
By all means, ask what
the world around you can
mean for your PL/SQL
application
and Also Ask what you (through
PL/SQL & the Database) can do for
your “environment”?!
Database
(SQL & PL/SQL)
Blogger
Presenter
Author
Database
(SQL & PL/SQL)
SOA
Database
(SQL & PL/SQL)
• Channel
• Initiative
• Frequency
• Format
• Synchronous vs Asynchronous
• Volume
Database
(SQL & PL/SQL)
Email
User
Interface
Chat
(IM)
File
(Excel, PDF,…)
RSS
Queue
REST
Web
Servic
e
File, O/S
JDBC,
SQL Net,
DB Link
Database
(SQL & PL/SQL)
Email
User
Interface
Chat
(IM)
File
(Excel, PDF,…)
RSS
Queue
REST
Web
Servic
e
File, O/S
JDBC,
SQL Net,
DB Link
The Human Side of
Things
Challenges
Reaching Out From PL/SQL (OPP 2010)
Q
Reaching Out From PL/SQL (OPP 2010)
Demo steps
• Java to receive email
• Load Java and Expose as JSP
• Create AQ
• Create Job & Schedule that calls JSP
and puts results on AQ
• Create AQ listener
–That sends email with response
1
• Write Functional Java
2
• Wrap with PL/SQL
3
• Load into Database
4
• Set appropriate Privs
5
• Invoke JSP via PL/SQL
Interface
Database Asking
Questions
Other scenario with database as
initiator of the dialog
• An Update of an Employee’s Salary takes place
• After Update Row level trigger fires
– creates job to send out an email to
have someone approve the salary raise
– Sets the status of the salary to ‘awaiting approval’
• Email is sent to approver
• Approvers sends an answer
– Decision and comments
• Answer is received & processed by database
– Status of salary record is updated
Reaching Out From PL/SQL (OPP 2010)
dbms_epg
(mod_plsql)
http
XMLDB
http
ftp
webdav
utl_mailutl_file
external
table
Expose recent HRM Data
Changes• Several parties are interested in all changes in
the area of Human Resources
– We have received a request to make an overview of
all recent changes available, preferably in XML format
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
Example of Employee Versions
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
Service
http://host/../emp_history
Pull EMP change overview from browser
Publish Changes in Pretty
Format• A simple XSLT style sheet can be applied
in the hrm_change_history package
– To transform XML data to an XHTML human
readable format
Expose EMP Changes as RSS
feed
• RSS feed is an
HTTP response
in a predefined
XML format
(ATOM)
• DBMS_EPG can
be used to produce
RSS feeds
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
Service
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
Service
XDB
Folder
WEBDAV
FTP
HTTP
PL/SQL
SQL
Create XML Resource
DECLARE
CURSOR xmlcur IS
SELECT xmlelement("EMPHISTORY", ...
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
APEX
The Ultimate Database
User Interface
dbms_epg
(mod_plsql)
Database Reaching Out
to Human partners
• DBMS_EPG (or good old mod_plsql)
– Expose HTML and RSS & Process HTTP
requests
• XMLDB
– Expose and allow manipulation of resources
through HTTP, FTP and WEBDAV
• Stored Java Procedures to
– Interact with Mail Server, Chat; leverage
– Process human file formats (PDF, Excel,
images, …)
Machinations
Database
(SQL & PL/SQL)
Email
Chat
(IM)
RSS
Queue
REST
Web
Servic
e
File, O/S
JDBC,
SQL Net,
DB Link
dbms_epg
(mod_plsql)
http
XMLDB
http
ftp
webdav
utl_mailutl_file
external
table
utl_http
(httpuritype
)
http
JDBC/ODBC
OCI, DB Link
utl_tcp
Advanced
Queuing
AQ
jms
native
dbws
Tables & Business Rules
Views
PL/SQL “Services”
Oracle
Forms
Forms
DWH
External Partners
Web Application
Email
Server
Java based
SQL*
Loader
Modern Architecture
and the role of the database
Tables & Business Rules
Views
PL/SQL “Services”
Oracle
Forms
Forms
External Partners
Web Application
Email
Server
Java based
(extranet)
Web Application
Internal Users
(outside
intranet/firewall)
“Mobile
Enabled”
ADF 11g
ADF 11g
Enterprise Service and Process Bus
(SOA Suite 11g: BPEL, Mediator,
Human Task, Business Rules, Technology Adapters)
file
s
UCM
(Document
Management)
DWH
Operational
Dashboard
APEX
Tables & Business Rules
Views
PL/SQL “Services”
Oracle
Forms
Forms
External Partners
Web Application
Email
Server
Java based
(extranet)
Web Application
Internal Users
(outside
intranet/firewall)
“Mobile
Enabled”
ADF 11g
ADF 11g
Enterprise Service and Process Bus
(SOA Suite 11g: BPEL, Mediator,
Human Task, Business Rules, Technology Adapters)
file
s
UCM
(Document
Management)
DWH
Operational
Dashboard
APEX
Be a good host
• Provide services
–Views for easy querying
–Stored Procedure based APIs
• For data retrieval and data manipulation
–Queues as way-in (publish) as well as
way-out (allow subscription) for events
–Query Result Change Notification
API Services for consumers
• Views – for encapsulation of (legacy) model,
multi-table join, collection integration, SQL
hiding
• PL/SQL – for encapsulation, cursor based
data retrieval, DML hiding, table decoupling
View
Views hiding data model
USERS
PERSONS EMAIL_
ADDRESSES
EMAIL_TYPE
USERS
Providing a ‘business object’
API
• DML API: still the View – aided by Instead Of
trigger
• Insert of one new row in
USERS_VW can actually
be four new records
– USER, PERSON,
EMAIL_TYPE
EMAIL_ADDRESS
USERS
PERSONS EMAIL_
ADDRESSES
EMAIL_TYPE
USERS
*
* *
*
FIY Data Service API:
returning cursors
• Fetch it Yourself!
• Cursor is opened to be fetched from
– Data is gathered and
pre-processed before being returned
– SQL is wrapped
• And can be constructed at run-time
– Access privileges are taken care of
– Cursors can be handled elegantly
in most client languages and technologies
• For example Java: JDBC ResultSet
Prompt
Prompt
Prompt
Prompt
Prompt
Prompt Prompt Prompt Prompt
A
ct
ie
A
ct
ie
HRM_API
CURSOR
FIY Data Service API for
Employees
• Package HRM_API
– Function get_managers
– Return SYS_REFCURSOR
HRM_AP
I
EMPDEPT
FIY Data Service API for
Employees
HRM_AP
I
EMPDEPT
create or replace package body hrm_api
as
function get_managers
return SYS_REFCURSOR
is
c_mgr sys_refcursor;
begin
open c_mgr for
select empno
, ename
, sal
, hiredate
, deptno
from emp
where job = 'MANAGER'
;
return c_mgr;
end get_managers;
end hrm_api;
Using FIY HRM API from
PL/SQL HRM_AP
I
EMPDEPT
declare
l_mgr sys_refcursor:= hrm_api.get_managers;
l_id number(10);
l_name varchar2(25);
l_salary number(8,2);
l_hiredate date;
l_deptno number(10);
begin
LOOP
FETCH l_mgr
INTO l_id, l_name, l_salary, l_hiredate, l_deptno;
EXIT WHEN l_mgr%NOTFOUND;
dbms_output.put_line
( 'Manager '||l_name
||' started on '||l_hiredate
||' and makes $'||l_salary
);
END LOOP;
CLOSE l_mgr;
end;
Cursor can be for Dynamic
SQL
function get_employees_on_condition
( p_condition in varchar2
) return SYS_REFCURSOR
is
c_emp sys_refcursor;
begin
open c_emp for
' select empno
, ename
, sal
, hiredate
, deptno
from emp
where '||p_condition
;
return c_emp;
end get_employees_on_condition;
declare
c_emp sys_refcursor:=
hrm_api.get_employees_on_condition
( p_condition => 'job=''CLERK''
and sal < 1200'
);
l_id number(10);
...
Cursor can be created inside
SQL• The SQL CURSOR expression
returns sys_refcursor based on
query passed in
– Cursor expressions can be nested
• Cursor can even fetch data from
a Collection (returned for
example
by a PL/SQL function)
• CURSOR expression can be
fetched into PL/SQL variable of
type SYS_REFCURSOR
• Note: SQL*Plus knows how to
deal with cursor-types results
– It automatically opens them and
fetches records
The Super Host
Query Result Change Notification
Query Result Change
Notification• Continuous Query Notification:
– Send an event when the result set for a query changes
– Background process calls PL/SQL Handler or Java Listener or
OCI client when the
commit has occurred
– Event contains rowid
of changed rows
• Used for:
– Refreshing specific
data caches (middle
tier, global context)
– (custom) Replication
PL/SQL
Java
Listener
Implementing QRCN in PL/SQL
• Set up the privileges for the user
– CHANGE NOTIFICATION and EXECUTE on
DBMS_CQ_NOTIFICATION
• Create the Callback Handler procedure
• Create a new QRCN registration
• Add query (or queries) to the registration
– The queries for which a change in the result
set should trigger a call to the Callback
Handler
• Make sure job_queue_processes
parameter is set to a nonzero value
QRCN Callback Handler
• Signature is crucial!
• The CHNF$_DESC type contains a lot
information
– Including operation, queries and rowids
CREATE OR REPLACE PROCEDURE
change_notification_callback
( ntfnds IN SYS.CHNF$_DESC
) IS
...
Registration of QCRN interest
DECLARE
reginfo cq_notification$_reg_info;
l_cursor SYS_REFCURSOR;
regid NUMBER;
qosflags NUMBER;
BEGIN
qosflags := DBMS_CQ_NOTIFICATION.QOS_QUERY+
DBMS_CQ_NOTIFICATION.QOS_ROWIDS;
/* 1. Construct registration information.
'change_notification_callback' is name of
notification handler.
QOS_QUERY specifies result-set-change notifications.
*/
reginfo := cq_notification$_reg_info
( 'scott.change_notification_callback'
, qosflags
, 0
);
Registration of QCRN interest
(2)/* 2. Create registration */
regid :=
DBMS_CQ_NOTIFICATION.NEW_REG_START(reginfo);
OPEN l_cursor FOR
SELECT mgr
FROM emp
WHERE empno = 7902;
CLOSE l_cursor;
DBMS_CQ_NOTIFICATION.REG_END;
END;
...
To look for the registered
QCRNs
• Inspect Data Dictionary View
user_cq_notification_queries
SELECT queryid
, regid
, to_char(querytext)
FROM user_cq_notification_queries
To see the QRCN in action…
• Perform a DML statement that will apply
changes that modify the Query Result
• Look for whatever effect the Callback
Handler should have
– Message to the middle tier via UTL_HTTP
– Event on Advanced Queue
– Audit Table updated
– Asynchronous validations/calculations
performed
– Some custom-built form of replication
– …
More Interaction from & to the
database
• Files into the database
• Database to leverage O/S
• Stored Java for non-human
interactions
• WebServices – publish and consume
• Engage Middle Tier as ‘agent’
File Processing into the
Database
• Files can be
–uploaded through dbms_epg
–put on FTP/WEBDAV through XMLDB
–read by utl_file or dbms_lob (from O/S)
and by utl_http (from intranet/internet)
–exposed into the database via External
Tables
–retrieved by Java Stored Procedure (e.g.
from email attachment or remote FTP
server)
Interaction from Database with
O/S
• Database can interact with operating
system through
–external jobs (through dbms_scheduler)
–the External Table Preprocessor
–utl_file (only for some file manipulation)
–Java Stored Procedures
–(C-based) External Procedures
EJB
JMS
Email
Libraries for:
• Graphical Manipulation
• Translation,
• Calculation,
• Encryption,
• …
Communication
Protocols: http, ftp,
tcp ip, sms, grid, JDBC,
JDBC-ODBC, .Net, …
Operating Syste
& File System
The database can ask the
middle tier to access and
provide services
• Get information from (or to) services on the
intranet or internet
• Publish/Send information to the internet
(RSS, email, chat)
• Can tell the middle tier
– Interesting events
– Alert about (im)pending issues,
attempted rule violations, …
– The outcome of batch calculations
• DB vs. Middle Tier: Security,
Functionality, Load Balance
WebLogic Server 11g
SOA Suite
11g
AQ
Web App
• Database can call a middle
tier service using utl_http
– Passing in the destination
and the message content
• This Service sends it
onwards to the Google
Talk Server
WebLogic Server 11g
Service
CHAT_
MGR
Service
Happy Chatting – IM from the
Database
Database actively informs on
events
WebLogic Server 11g
Service
CHAT_
MGR
Service
EMP
Chat Manager package
create or replace package body chat_mgr
as
c_im_destination CONSTANT varchar2(100):= 'im_account';
c_im_service_base_url CONSTANT varchar2(100):= 'http://host/service?';
c_amp constant varchar2(5) := chr(38);
procedure send_im_message( p_msg in varchar2) is
l_response varchar2(32000);
begin
l_response:= utl_http.request
( c_im_service_base_url
||'imDestination='||c_im_destination
||c_amp||'msgBody='||replace(p_msg,' ', '%20')
, null
);
end send_im_message;
end chat_mgr;
Emp Informer
create or replace trigger mananager_sal_update_watcher
before insert or update of sal
on emp
for each row
when (new.job ='MANAGER'
and new.sal > 4000
and new.sal > nvl(old.sal,0))
declare
l_msg varchar2(32000);
begin
l_msg:= 'Selfenrichment '
||'Salary of '||:new.ename
||' ( manager in Department '||:new.deptno||') '
||'is changed to '||:new.sal
;
chat_mgr.send_im_message
( p_msg => l_msg
);
end;
RESTful WebServices
• Simple, stateless, light weight, http-based
message exchange protocol
– Use standard get, put, post, delete operations
– Use URL to pass resource reference
• Small, easy-to-understand messages
• Typically XML or JSON based
• Not using SOAP, or the WS*-stack
• Often used directly from User Interface –
(AJAX enabled) JavaScript
RESTful architecture
RESTful PL/SQL API
exposed through dbms_epg
RESTful resource navigation
Publish REST-ful HTTP API –
directly on top of the RDBMS
Publish REST-ful HTTP API –
directly on top of the RDBMS
Consuming REST-ful services
• Invoking a REST-ful service is simply
making an HTTP request to some URL
• Can be done through:
– utl_http
– httpuritype
– Stored Java
• Result can be processed as just a string or
as XML, JSON or other format
– Libraries can help with special formats
Calling ‘formal’ WS* and
SOAP based Web Services
• Invoking a SOAP WS* service is making
an HTTP request to some URL
• Can be done through:
– utl_http
– Stored Java
• Request and Response
are both SOAP-wrapped XML messages
– Using XMLDB functionality including XML Type these
can easily by composed, transformed, validated and
parsed
(Expose) Native WebServices
• Publish and PL/SQL Package as externally
available WebService
– WSDL is auto-generated
– SOAP calls over http and https are supported
Summary
Reaching Out From PL/SQL (OPP 2010)
Reaching Out From PL/SQL (OPP 2010)

More Related Content

PPT
Xml Publisher And Reporting To Excel
PPTX
working with PHP & DB's
PDF
Web services in PHP using the NuSOAP library
PPT
Easy rest service using PHP reflection api
PDF
Consuming RESTful services in PHP
PPTX
Restful web services with java
PDF
Fast Web Applications Development with Ruby on Rails on Oracle
PDF
Wizard of ORDS
Xml Publisher And Reporting To Excel
working with PHP & DB's
Web services in PHP using the NuSOAP library
Easy rest service using PHP reflection api
Consuming RESTful services in PHP
Restful web services with java
Fast Web Applications Development with Ruby on Rails on Oracle
Wizard of ORDS

What's hot (19)

PPT
Exchange Server 2010
PPT
Synapseindia dot net development web applications with ajax
KEY
Rails and Legacy Databases - RailsConf 2009
PDF
Native REST Web Services with Oracle 11g
PDF
ePUB 3 and Publishing e-books
PDF
Os Furlong
PDF
Create a Database Application Development Environment with Docker
PDF
Intro to Dynamic Web Pages
PDF
Web services tutorial
PPT
Intro to-html-backbone
PDF
Os Pruett
PPT
Develop webservice in PHP
PDF
Web Development Course: PHP lecture 2
PDF
Introducing RaveJS: Spring Boot concepts for JavaScript applications
PDF
Amsterdam php create a restful api
PPTX
Amp and higher computing science
PDF
jsp tutorial
PPT
SHOW104: Practical Java
PDF
Differential Sync and JSON Patch @ SpringOne2GX 2014
Exchange Server 2010
Synapseindia dot net development web applications with ajax
Rails and Legacy Databases - RailsConf 2009
Native REST Web Services with Oracle 11g
ePUB 3 and Publishing e-books
Os Furlong
Create a Database Application Development Environment with Docker
Intro to Dynamic Web Pages
Web services tutorial
Intro to-html-backbone
Os Pruett
Develop webservice in PHP
Web Development Course: PHP lecture 2
Introducing RaveJS: Spring Boot concepts for JavaScript applications
Amsterdam php create a restful api
Amp and higher computing science
jsp tutorial
SHOW104: Practical Java
Differential Sync and JSON Patch @ SpringOne2GX 2014
Ad

Viewers also liked (15)

PDF
Getting started-with-oracle-so a- lab 11
PPTX
Sql Server 2008 Performance and Scaleability
PDF
Bisp training calendar jan 2012
PPT
Hfm intro v2
PPT
Hyperion analyzer 31 july
PPT
Hyperion Planning Class
PPT
Hfm intro v2
PPT
02 Essbase
PDF
Olap fundamentals
PPT
Expert talk
PDF
Oracle Database SQL Tuning Concept
PDF
Oracle Index
PPT
Back to basics: Simple database web services without the need for SOA
PDF
Oracle database 12c sql tuning
TXT
Oracle sql tuning
Getting started-with-oracle-so a- lab 11
Sql Server 2008 Performance and Scaleability
Bisp training calendar jan 2012
Hfm intro v2
Hyperion analyzer 31 july
Hyperion Planning Class
Hfm intro v2
02 Essbase
Olap fundamentals
Expert talk
Oracle Database SQL Tuning Concept
Oracle Index
Back to basics: Simple database web services without the need for SOA
Oracle database 12c sql tuning
Oracle sql tuning
Ad

Similar to Reaching Out From PL/SQL (OPP 2010) (20)

PDF
AD102 - Break out of the Box
ODP
Ldap Synchronization Connector @ 2011.RMLL
PPT
Dxl As A Lotus Domino Integration Tool
PDF
ODTUG KSCOPE 2018 - REST APIs for FDMEE and Cloud Data Management
PPT
루비가 얼랭에 빠진 날
PDF
Workshop 16: EmberJS Parte I
PPT
OWB11gR2 - Extending ETL
PDF
Introduction to Ajax programming
PDF
03 form-data
PPTX
LRT MoodleMootUK11 Unconf Presentation
PPT
JavaOne 2009 - TS-5276 - RESTful Protocol Buffers
PDF
Python RESTful webservices with Python: Flask and Django solutions
ODP
Exploring Symfony's Code
PPTX
The Story of How an Oracle Classic Stronghold successfully embraced SOA (ODTU...
PPT
Developing node-mdb: a Node.js - based clone of SimpleDB
PPTX
Java Technology
PPT
Mashups
PPT
Intro to web services
PPT
Starting with PHP and Web devepolment
AD102 - Break out of the Box
Ldap Synchronization Connector @ 2011.RMLL
Dxl As A Lotus Domino Integration Tool
ODTUG KSCOPE 2018 - REST APIs for FDMEE and Cloud Data Management
루비가 얼랭에 빠진 날
Workshop 16: EmberJS Parte I
OWB11gR2 - Extending ETL
Introduction to Ajax programming
03 form-data
LRT MoodleMootUK11 Unconf Presentation
JavaOne 2009 - TS-5276 - RESTful Protocol Buffers
Python RESTful webservices with Python: Flask and Django solutions
Exploring Symfony's Code
The Story of How an Oracle Classic Stronghold successfully embraced SOA (ODTU...
Developing node-mdb: a Node.js - based clone of SimpleDB
Java Technology
Mashups
Intro to web services
Starting with PHP and Web devepolment

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?
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Encapsulation theory and applications.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
cuic standard and advanced reporting.pdf
PDF
Electronic commerce courselecture one. Pdf
PPT
Teaching material agriculture food technology
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
Programs and apps: productivity, graphics, security and other tools
Mobile App Security Testing_ A Comprehensive Guide.pdf
MIND Revenue Release Quarter 2 2025 Press Release
Review of recent advances in non-invasive hemoglobin estimation
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Dropbox Q2 2025 Financial Results & Investor Presentation
Encapsulation theory and applications.pdf
Network Security Unit 5.pdf for BCA BBA.
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Chapter 3 Spatial Domain Image Processing.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
cuic standard and advanced reporting.pdf
Electronic commerce courselecture one. Pdf
Teaching material agriculture food technology
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Machine learning based COVID-19 study performance prediction
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
How UI/UX Design Impacts User Retention in Mobile Apps.pdf

Reaching Out From PL/SQL (OPP 2010)

  • 3. Do not ask what your country can do for you Ask what you can do for your country?!
  • 4. By all means, ask what the world around you can mean for your PL/SQL application and Also Ask what you (through PL/SQL & the Database) can do for your “environment”?!
  • 8. Database (SQL & PL/SQL) • Channel • Initiative • Frequency • Format • Synchronous vs Asynchronous • Volume
  • 9. Database (SQL & PL/SQL) Email User Interface Chat (IM) File (Excel, PDF,…) RSS Queue REST Web Servic e File, O/S JDBC, SQL Net, DB Link
  • 10. Database (SQL & PL/SQL) Email User Interface Chat (IM) File (Excel, PDF,…) RSS Queue REST Web Servic e File, O/S JDBC, SQL Net, DB Link
  • 11. The Human Side of Things
  • 14. Q
  • 16. Demo steps • Java to receive email • Load Java and Expose as JSP • Create AQ • Create Job & Schedule that calls JSP and puts results on AQ • Create AQ listener –That sends email with response
  • 17. 1 • Write Functional Java 2 • Wrap with PL/SQL 3 • Load into Database 4 • Set appropriate Privs 5 • Invoke JSP via PL/SQL Interface
  • 19. Other scenario with database as initiator of the dialog • An Update of an Employee’s Salary takes place • After Update Row level trigger fires – creates job to send out an email to have someone approve the salary raise – Sets the status of the salary to ‘awaiting approval’ • Email is sent to approver • Approvers sends an answer – Decision and comments • Answer is received & processed by database – Status of salary record is updated
  • 22. Expose recent HRM Data Changes• Several parties are interested in all changes in the area of Human Resources – We have received a request to make an overview of all recent changes available, preferably in XML format
  • 23. 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
  • 25. 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 Service http://host/../emp_history
  • 26. Pull EMP change overview from browser
  • 27. Publish Changes in Pretty Format• A simple XSLT style sheet can be applied in the hrm_change_history package – To transform XML data to an XHTML human readable format
  • 28. Expose EMP Changes as RSS feed • RSS feed is an HTTP response in a predefined XML format (ATOM) • DBMS_EPG can be used to produce RSS feeds
  • 29. 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 Service XDB Folder WEBDAV FTP HTTP PL/SQL SQL
  • 30. 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 Service XDB Folder WEBDAV FTP HTTP PL/SQL SQL
  • 31. Create XML Resource DECLARE CURSOR xmlcur IS SELECT xmlelement("EMPHISTORY", ... 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;
  • 32. HRM Report via WEBDAV, SQL & HTTP
  • 34. Uploading data from file to database
  • 35. APEX The Ultimate Database User Interface dbms_epg (mod_plsql)
  • 36. Database Reaching Out to Human partners • DBMS_EPG (or good old mod_plsql) – Expose HTML and RSS & Process HTTP requests • XMLDB – Expose and allow manipulation of resources through HTTP, FTP and WEBDAV • Stored Java Procedures to – Interact with Mail Server, Chat; leverage – Process human file formats (PDF, Excel, images, …)
  • 38. Database (SQL & PL/SQL) Email Chat (IM) RSS Queue REST Web Servic e File, O/S JDBC, SQL Net, DB Link dbms_epg (mod_plsql) http XMLDB http ftp webdav utl_mailutl_file external table utl_http (httpuritype ) http JDBC/ODBC OCI, DB Link utl_tcp Advanced Queuing AQ jms native dbws
  • 39. Tables & Business Rules Views PL/SQL “Services” Oracle Forms Forms DWH External Partners Web Application Email Server Java based SQL* Loader Modern Architecture and the role of the database
  • 40. Tables & Business Rules Views PL/SQL “Services” Oracle Forms Forms External Partners Web Application Email Server Java based (extranet) Web Application Internal Users (outside intranet/firewall) “Mobile Enabled” ADF 11g ADF 11g Enterprise Service and Process Bus (SOA Suite 11g: BPEL, Mediator, Human Task, Business Rules, Technology Adapters) file s UCM (Document Management) DWH Operational Dashboard APEX
  • 41. Tables & Business Rules Views PL/SQL “Services” Oracle Forms Forms External Partners Web Application Email Server Java based (extranet) Web Application Internal Users (outside intranet/firewall) “Mobile Enabled” ADF 11g ADF 11g Enterprise Service and Process Bus (SOA Suite 11g: BPEL, Mediator, Human Task, Business Rules, Technology Adapters) file s UCM (Document Management) DWH Operational Dashboard APEX
  • 42. Be a good host • Provide services –Views for easy querying –Stored Procedure based APIs • For data retrieval and data manipulation –Queues as way-in (publish) as well as way-out (allow subscription) for events –Query Result Change Notification
  • 43. API Services for consumers • Views – for encapsulation of (legacy) model, multi-table join, collection integration, SQL hiding • PL/SQL – for encapsulation, cursor based data retrieval, DML hiding, table decoupling View
  • 44. Views hiding data model USERS PERSONS EMAIL_ ADDRESSES EMAIL_TYPE USERS
  • 45. Providing a ‘business object’ API • DML API: still the View – aided by Instead Of trigger • Insert of one new row in USERS_VW can actually be four new records – USER, PERSON, EMAIL_TYPE EMAIL_ADDRESS USERS PERSONS EMAIL_ ADDRESSES EMAIL_TYPE USERS * * * *
  • 46. FIY Data Service API: returning cursors • Fetch it Yourself! • Cursor is opened to be fetched from – Data is gathered and pre-processed before being returned – SQL is wrapped • And can be constructed at run-time – Access privileges are taken care of – Cursors can be handled elegantly in most client languages and technologies • For example Java: JDBC ResultSet Prompt Prompt Prompt Prompt Prompt Prompt Prompt Prompt Prompt A ct ie A ct ie HRM_API CURSOR
  • 47. FIY Data Service API for Employees • Package HRM_API – Function get_managers – Return SYS_REFCURSOR HRM_AP I EMPDEPT
  • 48. FIY Data Service API for Employees HRM_AP I EMPDEPT create or replace package body hrm_api as function get_managers return SYS_REFCURSOR is c_mgr sys_refcursor; begin open c_mgr for select empno , ename , sal , hiredate , deptno from emp where job = 'MANAGER' ; return c_mgr; end get_managers; end hrm_api;
  • 49. Using FIY HRM API from PL/SQL HRM_AP I EMPDEPT declare l_mgr sys_refcursor:= hrm_api.get_managers; l_id number(10); l_name varchar2(25); l_salary number(8,2); l_hiredate date; l_deptno number(10); begin LOOP FETCH l_mgr INTO l_id, l_name, l_salary, l_hiredate, l_deptno; EXIT WHEN l_mgr%NOTFOUND; dbms_output.put_line ( 'Manager '||l_name ||' started on '||l_hiredate ||' and makes $'||l_salary ); END LOOP; CLOSE l_mgr; end;
  • 50. Cursor can be for Dynamic SQL function get_employees_on_condition ( p_condition in varchar2 ) return SYS_REFCURSOR is c_emp sys_refcursor; begin open c_emp for ' select empno , ename , sal , hiredate , deptno from emp where '||p_condition ; return c_emp; end get_employees_on_condition; declare c_emp sys_refcursor:= hrm_api.get_employees_on_condition ( p_condition => 'job=''CLERK'' and sal < 1200' ); l_id number(10); ...
  • 51. Cursor can be created inside SQL• The SQL CURSOR expression returns sys_refcursor based on query passed in – Cursor expressions can be nested • Cursor can even fetch data from a Collection (returned for example by a PL/SQL function) • CURSOR expression can be fetched into PL/SQL variable of type SYS_REFCURSOR • Note: SQL*Plus knows how to deal with cursor-types results – It automatically opens them and fetches records
  • 52. The Super Host Query Result Change Notification
  • 53. Query Result Change Notification• Continuous Query Notification: – Send an event when the result set for a query changes – Background process calls PL/SQL Handler or Java Listener or OCI client when the commit has occurred – Event contains rowid of changed rows • Used for: – Refreshing specific data caches (middle tier, global context) – (custom) Replication PL/SQL Java Listener
  • 54. Implementing QRCN in PL/SQL • Set up the privileges for the user – CHANGE NOTIFICATION and EXECUTE on DBMS_CQ_NOTIFICATION • Create the Callback Handler procedure • Create a new QRCN registration • Add query (or queries) to the registration – The queries for which a change in the result set should trigger a call to the Callback Handler • Make sure job_queue_processes parameter is set to a nonzero value
  • 55. QRCN Callback Handler • Signature is crucial! • The CHNF$_DESC type contains a lot information – Including operation, queries and rowids CREATE OR REPLACE PROCEDURE change_notification_callback ( ntfnds IN SYS.CHNF$_DESC ) IS ...
  • 56. Registration of QCRN interest DECLARE reginfo cq_notification$_reg_info; l_cursor SYS_REFCURSOR; regid NUMBER; qosflags NUMBER; BEGIN qosflags := DBMS_CQ_NOTIFICATION.QOS_QUERY+ DBMS_CQ_NOTIFICATION.QOS_ROWIDS; /* 1. Construct registration information. 'change_notification_callback' is name of notification handler. QOS_QUERY specifies result-set-change notifications. */ reginfo := cq_notification$_reg_info ( 'scott.change_notification_callback' , qosflags , 0 );
  • 57. Registration of QCRN interest (2)/* 2. Create registration */ regid := DBMS_CQ_NOTIFICATION.NEW_REG_START(reginfo); OPEN l_cursor FOR SELECT mgr FROM emp WHERE empno = 7902; CLOSE l_cursor; DBMS_CQ_NOTIFICATION.REG_END; END; ...
  • 58. To look for the registered QCRNs • Inspect Data Dictionary View user_cq_notification_queries SELECT queryid , regid , to_char(querytext) FROM user_cq_notification_queries
  • 59. To see the QRCN in action… • Perform a DML statement that will apply changes that modify the Query Result • Look for whatever effect the Callback Handler should have – Message to the middle tier via UTL_HTTP – Event on Advanced Queue – Audit Table updated – Asynchronous validations/calculations performed – Some custom-built form of replication – …
  • 60. More Interaction from & to the database • Files into the database • Database to leverage O/S • Stored Java for non-human interactions • WebServices – publish and consume • Engage Middle Tier as ‘agent’
  • 61. File Processing into the Database • Files can be –uploaded through dbms_epg –put on FTP/WEBDAV through XMLDB –read by utl_file or dbms_lob (from O/S) and by utl_http (from intranet/internet) –exposed into the database via External Tables –retrieved by Java Stored Procedure (e.g. from email attachment or remote FTP server)
  • 62. Interaction from Database with O/S • Database can interact with operating system through –external jobs (through dbms_scheduler) –the External Table Preprocessor –utl_file (only for some file manipulation) –Java Stored Procedures –(C-based) External Procedures
  • 63. EJB JMS Email Libraries for: • Graphical Manipulation • Translation, • Calculation, • Encryption, • … Communication Protocols: http, ftp, tcp ip, sms, grid, JDBC, JDBC-ODBC, .Net, … Operating Syste & File System
  • 64. The database can ask the middle tier to access and provide services • Get information from (or to) services on the intranet or internet • Publish/Send information to the internet (RSS, email, chat) • Can tell the middle tier – Interesting events – Alert about (im)pending issues, attempted rule violations, … – The outcome of batch calculations • DB vs. Middle Tier: Security, Functionality, Load Balance WebLogic Server 11g SOA Suite 11g AQ Web App
  • 65. • Database can call a middle tier service using utl_http – Passing in the destination and the message content • This Service sends it onwards to the Google Talk Server WebLogic Server 11g Service CHAT_ MGR Service Happy Chatting – IM from the Database
  • 66. Database actively informs on events WebLogic Server 11g Service CHAT_ MGR Service EMP
  • 67. Chat Manager package create or replace package body chat_mgr as c_im_destination CONSTANT varchar2(100):= 'im_account'; c_im_service_base_url CONSTANT varchar2(100):= 'http://host/service?'; c_amp constant varchar2(5) := chr(38); procedure send_im_message( p_msg in varchar2) is l_response varchar2(32000); begin l_response:= utl_http.request ( c_im_service_base_url ||'imDestination='||c_im_destination ||c_amp||'msgBody='||replace(p_msg,' ', '%20') , null ); end send_im_message; end chat_mgr;
  • 68. Emp Informer create or replace trigger mananager_sal_update_watcher before insert or update of sal on emp for each row when (new.job ='MANAGER' and new.sal > 4000 and new.sal > nvl(old.sal,0)) declare l_msg varchar2(32000); begin l_msg:= 'Selfenrichment ' ||'Salary of '||:new.ename ||' ( manager in Department '||:new.deptno||') ' ||'is changed to '||:new.sal ; chat_mgr.send_im_message ( p_msg => l_msg ); end;
  • 69. RESTful WebServices • Simple, stateless, light weight, http-based message exchange protocol – Use standard get, put, post, delete operations – Use URL to pass resource reference • Small, easy-to-understand messages • Typically XML or JSON based • Not using SOAP, or the WS*-stack • Often used directly from User Interface – (AJAX enabled) JavaScript
  • 70. RESTful architecture RESTful PL/SQL API exposed through dbms_epg
  • 72. Publish REST-ful HTTP API – directly on top of the RDBMS
  • 73. Publish REST-ful HTTP API – directly on top of the RDBMS
  • 74. Consuming REST-ful services • Invoking a REST-ful service is simply making an HTTP request to some URL • Can be done through: – utl_http – httpuritype – Stored Java • Result can be processed as just a string or as XML, JSON or other format – Libraries can help with special formats
  • 75. Calling ‘formal’ WS* and SOAP based Web Services • Invoking a SOAP WS* service is making an HTTP request to some URL • Can be done through: – utl_http – Stored Java • Request and Response are both SOAP-wrapped XML messages – Using XMLDB functionality including XML Type these can easily by composed, transformed, validated and parsed
  • 76. (Expose) Native WebServices • Publish and PL/SQL Package as externally available WebService – WSDL is auto-generated – SOAP calls over http and https are supported

Editor's Notes

  • #8: By reaching out I help ensure that the (Oracle) database keeps its rightful place in the IT landscape of organizations ( as well as the database developers)
  • #15: The job is scheduled to run every minuteIt calls upon the Java Stored Procedure to retrieve the newly arrived email-messages – in a specific accountFor each message, an email event is enqueue in the AQ Queue. The new email-messages are subsequently removed.A queue listener has been registered on the queue with email eventsEvery email (event) is dequeued and processedThe email can contain query statements – in some form – that the processor knows how to handleThe reply to the query is then sent in an email message that forms the response to the original email messageNote: other listeners could dequeue the email events and process them in other waysIncoming messages from other sources could be retrieved and processed in a similar way as email messages (VOIP, SMS, IM/Chat, Twitter)The database can both send and retrieve messages from such serversNote: Java is much better equipped than plain PL/SQL (that really only has utl_http, utl_tcp, utl_smtp) for customized, flexible, advanced interaction with a wide range of infrastructures and technologies.
  • #16: Screenshot:Frank sends email to Maggie – with a query on EmployeesAfter some time, a response is sent to this particular email – by the queue listener using the JSP to send(list of employee data, corresponding with “query”)
  • #18: Write functional JavaFor example in JDeveloperUsing the full richness of the IDE and of the Java Language (and libraries)Wrap with PL/SQL Map Java &amp; PL/SQL data types Load into DatabaseCustom classes and libraries (JAR-files)Set appropriate privilegesInvoke JSP through a normal PL/SQL interface
  • #20: Challenge:Link email sent out to response received (some identification is required)Structure of the answer: how to recognize the decision and comment
  • #21: Java is much better equipped than plain PL/SQL (that really only has utl_http, utl_tcp, utl_smtp) for customized, flexible, advanced interaction with a wide range of infrastructures and technologies.Java libraries can help to generate PDF, create and/or read Word and Excel etc.Through JMS – external Java applications can be accessed in a decoupled way. For example: Complex Event Processor
  • #29: http://technology.amis.nl/blog/1201/publishing-data-manipulation-as-an-rss-feed-using-oracle-mod_plsql-and-flashback
  • #32: http://technology.amis.nl/blog/?p=2498
  • #54: 1.8.3.1 Continuous Query Notification EnhancementsContinuous Query Notification has been enhanced to provide notifications when the result set for a query changes on the server. These notifications can be registered at the row-level, rather than just at the table-level. Thus, alerts will only be sent when changes to the specific rows selected have been modified.Applications, such as Radio Frequency Identification (RFID), can now receive notifications directly from the database rather than build this functionality into the application.
  • #62: Mention:11gR1 (11.1.0.7) and 11gR2 external table pre-processor: http://www.oracle.com/technetwork/database/xtables11g2009-preproc-1005-134225.pdfdbms_scheduler File Watcher
  • #63: Mention:11gR1 (11.1.0.7) and 11gR2 external table pre-processor: http://www.oracle.com/technetwork/database/xtables11g2009-preproc-1005-134225.pdfhttp://database.itags.org/oracle/88815/ external jobs
  • #64: Java is much better equipped than plain PL/SQL (that really only has utl_http, utl_tcp, utl_smtp) for customized, flexible, advanced interaction with a wide range of infrastructures and technologies.Java libraries can help to generate PDF, create and/or read Word and Excel etc.Through JMS – external Java applications can be accessed in a decoupled way. For example: Complex Event Processor
  • #68: http://technology.amis.nl/blog/?p=2498
  • #69: http://technology.amis.nl/blog/?p=2498
  • #77: http://www.liberidu.com/blog/?p=244http://tardate.blogspot.com/2007/08/first-tests-of-11g-native-web-services.htmlhttp://download.oracle.com/docs/cd/B28359_01/appdev.111/b28369/xdb_web_services.htm#ADXDB3900