SlideShare a Scribd company logo
1 of 64
Speed Up Your APEX Apps with JSON
and Handlebars
Marko Gorički
BiLog
About BiLog
• small IT company focused on consulting and business solution development
(using Oracle technologies)
• big APEX company ≈ 25 APEX developers
• our APEX products:
HRMb - HR management software
www.bilog.hr
About Me
• started with Oracle Forms and Reports
• working 8 years with APEX
• APEX related blog - apexbyg.blogspot.com
• @mgoricki
It depends
There are only five questions about the database:
• The answer to the first three questions is “use bind variables.”
• The answer to the fourth question is “do not use bind variables.”
• The answer to the fifth question is “it depends”.
If you know those answers, you can answer any question about the database!
– Tom Kyte
• In APEX: “it depends”
Content
JSON
• JavaScript Object Notation – lightweight data interchange format that consists
of name-value pairs
• key features:
• easy to read and write
• easy to generate and parse
• language independent
• subset of JavaScript notation
JSON format
• {“name”: value, “name”: value…}
• key elements
• Name
• Value
• Object (unordered collection)
• Array (ordered collection)
Name/key/attribute
Value
Object
Array
Value
• string - double quotes(“”), backslash escapes ()
• number - decimal notation (possibly signed and possibly including a decimal
exponent)
• no date data type
• null different to SQL null
Object
• unordered set of name/value pairs
• begins and ends with brace - {…}
• name/string/attribute/key followed by colon
• separated by comma
Array
• ordered collection of values
• begins and ends with brackets - […]
• separated by comma
*Please, don’t use this in your CV !! 
JSON vs XML
JSON XML
Predefined data types
Typless or based on XML Schema or document type
definition (DTD)
Structured data Structured and semi-structured data
Data-centric Data or document-centric
Data representation language Document markup and data representation language
Generate JSON
• prior to APEX 5:
• by manually concatenating strings
• apex_util.json_from_*
• PL/JSON
Generate JSON
• with APEX 5 - APEX_JSON API package
Generate JSON
• Other solutions
• Oracle REST Data Services (ORDS)
• node.js
SQL source
• why short column alias (x, a, b and c)?
• JSON size:
• 500 rows - 29.1KB vs 43.3KB
• less readable vs ≈30% smaller size
SQL source
With short aliasWithout alias
Generate JSON
• Manually by concatenating strings
• apex_util.json_from_*
• PL/JSON library
• APEX_JSON package
• ORDS
Manually by concatenating
strings
• using sys.htp package
• CONS:
• hard to maintain and develop
• manually escape values
• manually define value types
• easy to make mistakes
• no parsing
• PROS
• customizable
• it can be fast
Generate JSON
• Manually by concatenating strings
• apex_util.json_from_*
• PL/JSON library
• APEX_JSON package
• ORDS
Using apex_util.json_from*
• procedures: *_sql, *_array, *_items, *_string
• CONS:
• “not documented”
• no null, true and false values
• hard to create nested JSON objects
• no parsing
• security issue: passing string into json_from_sql
• PROS:
• simple and easy to develop
• auto escaping
• recognizes some value types (number)
• available before APEX 5
Generate JSON
• Manually by concatenating strings
• apex_util.json_from_*
• PL/JSON library
• APEX_JSON package
• ORDS
PL/JSON
• open source library (2009.)
• DB types: JSON (object) and JSON_LIST (array)
• CONS
• complex
• lack of real documentation
• performance issues
• PROS
• can be stored in DB
• parsing
• supports all value types
• open source
• available before APEX 5
Generate JSON
• Manually by concatenating strings
• apex_util.json_from_*
• PL/JSON library
• APEX_JSON package
• ORDS
APEX_JSON API
• PROS:
• native
• generating and parsing
• can be used as standalone (CLOB)
• light footprint
• easy conversion from/to xmltype
• CONS:
• only in APEX 5.0+
APEX_JSON API
• Simple JSON Array
apex_json.open_array;
for emp in (select *
from emp
where deptno = p_deptno)
loop
apex_json.write(emp.ename);
end loop;
apex_json.close_array;
Nested JSON object - with cursor
declare
cur_dept sys_refcursor;
begin
open cur_dept for
select d.dname
, d.loc
, cursor (select e.ename
, e.job
, e.sal
, (select m.ename from emp m where m.empno = e.mgr) manager
, decode(e.comm, null, 'false', 'true') as hasCommision
from emp e
where d.deptno = e.deptno) as emps
from dept d
where d.deptno = nvl(p_deptno, d.deptno);
apex_json.open_object;
apex_json.write('DEPTS',cur_dept);
apex_json.close_object;
end;
Parsing simple JSON object
declare
v_json_object varchar2(100) := '{"dname":"ACCOUNTING","loc":"NEW YORK"}';
begin
apex_json.parse(v_json_object);
dbms_output.put_line(
apex_json.get_varchar2('dname')
);
end;
Parsing nested JSON object
declare
v_json_object clob := ‘{…}’;
begin
apex_json.parse(v_json_object);
dbms_output.put_line(
apex_json.get_varchar2('DEPTS[1].EMPS[2].ENAME')
);
dbms_output.put_line(
apex_json.get_varchar2(p_path => 'DEPTS[%d].EMPS[%d].ENAME’
, p0 => 1
, p1 => 2)
);
end;
Generate JSON
• Manually by concatenating strings
• apex_util.json_from_*
• PL/JSON library
• APEX_JSON package
• ORDS
Oracle REST Data Services (ORDS)
• easy to develop modern REST interfaces
• ways to use it:
• APEX GUI
• SQL Developer (auto-rest)
• PL/SQL API
• Simple Oracle Document Access (SODA) API over REST
• URL format:
• protocol://host:port/ords-name/apex-workspace-name/uri-template/bind-value
• https://apex.oracle.com/pls/apex/mgoricki/dept/10
ORDS Demo
Oracle Rest Data Services (ORDS)
• CONS
• little slower
• you need ORDS
• PROS
• declarative and simple
• many options
• easy to create nested JSON objects
Best method?
• It depends! 
657.80
1574.00
287.00
332.80
254.70
0.00 200.00 400.00 600.00 800.00 1000.00 1200.00 1400.00 1600.00 1800.00
ORDS
PL/JSON
apex_json
apex_util.json_from_sql
Manually
Average execution time (ms)
29.90
29.30
29.30
29.30
29.30
29.00 29.10 29.20 29.30 29.40 29.50 29.60 29.70 29.80 29.90 30.00
ORDS
PL/JSON
apex_json
apex_util.json_from_sql
Manually
Average JSON size (KB)
JSON and Oracle12c
• native support from 12.1.0.2
• store JSON data (with VARCHAR2, CLOB or BLOB data types), index,
query…
• parse JSON data with SQL
JSON and Oracle12c
• storing JSON data
create table my_json(
json_col clob
);
alter table my_json add constraint valid_json
check (json_col is json);
insert into my_json
values ('{"dname":"ACCOUNTING","loc":"NEW YORK"}');
JSON and Oracle12c
• parsing JSON data
SQL> select json.json_col.dname from my_json json;
DNAME
---------
ACCOUNTING
Using JSON
• APEX use it (IR, Page designer)
• New APEX 5.1 grid
• Oracle JET
• fetch asynchronously data with AJAX
• communicate with Web services (REST API - Twitter, Flickr, Google
Apps)
• easy to use with JavaScript
Old HTML way
HTTP Request
HTML page
Client / Browser Server / DB
AJAX partial page
AJAX Request
HTML part
Client / Browser Server / DB
Client side templates
AJAX Request
JSON
HTML Template
Client / Browser Server / DB
• light weighted JavaScript templating engine (Mustache.js,
AngularJS, Backbone.js, Ember.js, Marko.js…) used for client-side
data binding
• subset of Mustache.js + minimal logic
• works by expanding tags in a template using values provided by
JSON object
• tags can be replaced with value, nothing or series of values
Handlebars.js
Handlebars.js
Example
Handlebars.js templates
• tags start and end with double braces (mustaches) {{…}}
• two simple types of tags:
• variables - basic tag type
{{title}}
• sections/block expressions - render block of text one or more times
{{#posts}}…{{/posts}}
In APEX
• Add JS library
• Create template item
• Define HTML object where to put result
• Fetch JSON and run render function
In APEX
Example
Classic report example
578.80
657.80
1574.00
287.00
332.80
254.70
0.00 200.00 400.00 600.00 800.00 1000.00 1200.00 1400.00 1600.00 1800.00
Report region
ORDS
PL/JSON
apex_json
apex_util.json_from_sql
Manually
Average execution time (ms)
122.00
29.90
29.30
29.30
29.30
29.30
0.00 20.00 40.00 60.00 80.00 100.00 120.00 140.00
Report region
ORDS
PL/JSON
apex_json
apex_util.json_from_sql
Manually
Average JSON size (KB)
Real-life example
Generation time: 2 minutes
Response time: 2.3 MB
Only first 700 rows
Real-life example
Generation time: 2.9s vs 2 minutes
Response time: 500KB vs 2.3 MB
All 2422 rows vs 700 rows
Q&A
Speed Up Your APEX Apps with JSON and Handlebars
Speed Up Your APEX Apps with JSON and Handlebars

More Related Content

What's hot

What's hot (20)

JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 
Oracle Forms Introduction
Oracle Forms IntroductionOracle Forms Introduction
Oracle Forms Introduction
 
Spring framework Controllers and Annotations
Spring framework   Controllers and AnnotationsSpring framework   Controllers and Annotations
Spring framework Controllers and Annotations
 
Get the Look and Feel You Want in Oracle APEX
Get the Look and Feel You Want in Oracle APEXGet the Look and Feel You Want in Oracle APEX
Get the Look and Feel You Want in Oracle APEX
 
10 Creating Triggers
10 Creating Triggers10 Creating Triggers
10 Creating Triggers
 
Oracle REST Data Services: Options for your Web Services
Oracle REST Data Services: Options for your Web ServicesOracle REST Data Services: Options for your Web Services
Oracle REST Data Services: Options for your Web Services
 
Second Level Cache in JPA Explained
Second Level Cache in JPA ExplainedSecond Level Cache in JPA Explained
Second Level Cache in JPA Explained
 
Step-by-Step: APEX Installation on Tomcat (Windows Server 2016)
Step-by-Step: APEX Installation on Tomcat (Windows Server 2016)Step-by-Step: APEX Installation on Tomcat (Windows Server 2016)
Step-by-Step: APEX Installation on Tomcat (Windows Server 2016)
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
ORDS - Oracle REST Data Services
ORDS - Oracle REST Data ServicesORDS - Oracle REST Data Services
ORDS - Oracle REST Data Services
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
Clean Code
Clean CodeClean Code
Clean Code
 
Postman
PostmanPostman
Postman
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Testing with JUnit 5 and Spring - Spring I/O 2022
Testing with JUnit 5 and Spring - Spring I/O 2022Testing with JUnit 5 and Spring - Spring I/O 2022
Testing with JUnit 5 and Spring - Spring I/O 2022
 
Tweaking the interactive grid
Tweaking the interactive gridTweaking the interactive grid
Tweaking the interactive grid
 
Visual studio
Visual studioVisual studio
Visual studio
 
Exploring the details of APEX sessions
Exploring the details of APEX sessionsExploring the details of APEX sessions
Exploring the details of APEX sessions
 
TestNG - The Next Generation of Unit Testing
TestNG - The Next Generation of Unit TestingTestNG - The Next Generation of Unit Testing
TestNG - The Next Generation of Unit Testing
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
 

Similar to Speed Up Your APEX Apps with JSON and Handlebars

Meetup#2: Building responsive Symbology & Suggest WebService
Meetup#2: Building responsive Symbology & Suggest WebServiceMeetup#2: Building responsive Symbology & Suggest WebService
Meetup#2: Building responsive Symbology & Suggest WebService
Minsk MongoDB User Group
 
module 2.pptx for full stack mobile development application on backend applic...
module 2.pptx for full stack mobile development application on backend applic...module 2.pptx for full stack mobile development application on backend applic...
module 2.pptx for full stack mobile development application on backend applic...
HemaSenthil5
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHP
Zoran Jeremic
 
Using Ruby on Rails with legacy Oracle databases
Using Ruby on Rails with legacy Oracle databasesUsing Ruby on Rails with legacy Oracle databases
Using Ruby on Rails with legacy Oracle databases
Raimonds Simanovskis
 

Similar to Speed Up Your APEX Apps with JSON and Handlebars (20)

Json - ideal for data interchange
Json - ideal for data interchangeJson - ideal for data interchange
Json - ideal for data interchange
 
Database@Home - Data Driven : Loading, Indexing, and Searching with Text and ...
Database@Home - Data Driven : Loading, Indexing, and Searching with Text and ...Database@Home - Data Driven : Loading, Indexing, and Searching with Text and ...
Database@Home - Data Driven : Loading, Indexing, and Searching with Text and ...
 
Meetup#2: Building responsive Symbology & Suggest WebService
Meetup#2: Building responsive Symbology & Suggest WebServiceMeetup#2: Building responsive Symbology & Suggest WebService
Meetup#2: Building responsive Symbology & Suggest WebService
 
No sql way_in_pg
No sql way_in_pgNo sql way_in_pg
No sql way_in_pg
 
JSON-LD and SHACL for Knowledge Graphs
JSON-LD and SHACL for Knowledge GraphsJSON-LD and SHACL for Knowledge Graphs
JSON-LD and SHACL for Knowledge Graphs
 
NoSQL and Spatial Database Capabilities using PostgreSQL
NoSQL and Spatial Database Capabilities using PostgreSQLNoSQL and Spatial Database Capabilities using PostgreSQL
NoSQL and Spatial Database Capabilities using PostgreSQL
 
Json
JsonJson
Json
 
Json tutorial, a beguiner guide
Json tutorial, a beguiner guideJson tutorial, a beguiner guide
Json tutorial, a beguiner guide
 
Oracle adapters for Ruby ORMs
Oracle adapters for Ruby ORMsOracle adapters for Ruby ORMs
Oracle adapters for Ruby ORMs
 
DEVNET-2005 Using the Cisco Open SDN Controller RESTCONF APIs
DEVNET-2005	Using the Cisco Open SDN Controller RESTCONF APIsDEVNET-2005	Using the Cisco Open SDN Controller RESTCONF APIs
DEVNET-2005 Using the Cisco Open SDN Controller RESTCONF APIs
 
module 2.pptx for full stack mobile development application on backend applic...
module 2.pptx for full stack mobile development application on backend applic...module 2.pptx for full stack mobile development application on backend applic...
module 2.pptx for full stack mobile development application on backend applic...
 
Consuming RESTful Web services in PHP
Consuming RESTful Web services in PHPConsuming RESTful Web services in PHP
Consuming RESTful Web services in PHP
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHP
 
Using Ruby on Rails with legacy Oracle databases
Using Ruby on Rails with legacy Oracle databasesUsing Ruby on Rails with legacy Oracle databases
Using Ruby on Rails with legacy Oracle databases
 
Data Science with Solr and Spark
Data Science with Solr and SparkData Science with Solr and Spark
Data Science with Solr and Spark
 
Postgres vs Mongo / Олег Бартунов (Postgres Professional)
Postgres vs Mongo / Олег Бартунов (Postgres Professional)Postgres vs Mongo / Олег Бартунов (Postgres Professional)
Postgres vs Mongo / Олег Бартунов (Postgres Professional)
 
JSON in Oracle 18c and 19c
JSON in Oracle 18c and 19cJSON in Oracle 18c and 19c
JSON in Oracle 18c and 19c
 
Json in 18c and 19c
Json in 18c and 19cJson in 18c and 19c
Json in 18c and 19c
 
The NoSQL Way in Postgres
The NoSQL Way in PostgresThe NoSQL Way in Postgres
The NoSQL Way in Postgres
 
Json the-x-in-ajax1588
Json the-x-in-ajax1588Json the-x-in-ajax1588
Json the-x-in-ajax1588
 

Recently uploaded

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Recently uploaded (20)

%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 

Speed Up Your APEX Apps with JSON and Handlebars

  • 1.
  • 2. Speed Up Your APEX Apps with JSON and Handlebars Marko Gorički BiLog
  • 3. About BiLog • small IT company focused on consulting and business solution development (using Oracle technologies) • big APEX company ≈ 25 APEX developers • our APEX products: HRMb - HR management software www.bilog.hr
  • 4. About Me • started with Oracle Forms and Reports • working 8 years with APEX • APEX related blog - apexbyg.blogspot.com • @mgoricki
  • 5. It depends There are only five questions about the database: • The answer to the first three questions is “use bind variables.” • The answer to the fourth question is “do not use bind variables.” • The answer to the fifth question is “it depends”. If you know those answers, you can answer any question about the database! – Tom Kyte • In APEX: “it depends”
  • 7.
  • 8. JSON • JavaScript Object Notation – lightweight data interchange format that consists of name-value pairs • key features: • easy to read and write • easy to generate and parse • language independent • subset of JavaScript notation
  • 9. JSON format • {“name”: value, “name”: value…} • key elements • Name • Value • Object (unordered collection) • Array (ordered collection) Name/key/attribute Value Object Array
  • 10. Value • string - double quotes(“”), backslash escapes () • number - decimal notation (possibly signed and possibly including a decimal exponent) • no date data type • null different to SQL null
  • 11. Object • unordered set of name/value pairs • begins and ends with brace - {…} • name/string/attribute/key followed by colon • separated by comma
  • 12. Array • ordered collection of values • begins and ends with brackets - […] • separated by comma
  • 13. *Please, don’t use this in your CV !! 
  • 14. JSON vs XML JSON XML Predefined data types Typless or based on XML Schema or document type definition (DTD) Structured data Structured and semi-structured data Data-centric Data or document-centric Data representation language Document markup and data representation language
  • 15.
  • 16. Generate JSON • prior to APEX 5: • by manually concatenating strings • apex_util.json_from_* • PL/JSON
  • 17. Generate JSON • with APEX 5 - APEX_JSON API package
  • 18. Generate JSON • Other solutions • Oracle REST Data Services (ORDS) • node.js
  • 19. SQL source • why short column alias (x, a, b and c)? • JSON size: • 500 rows - 29.1KB vs 43.3KB • less readable vs ≈30% smaller size
  • 20. SQL source With short aliasWithout alias
  • 21. Generate JSON • Manually by concatenating strings • apex_util.json_from_* • PL/JSON library • APEX_JSON package • ORDS
  • 22. Manually by concatenating strings • using sys.htp package • CONS: • hard to maintain and develop • manually escape values • manually define value types • easy to make mistakes • no parsing • PROS • customizable • it can be fast
  • 23. Generate JSON • Manually by concatenating strings • apex_util.json_from_* • PL/JSON library • APEX_JSON package • ORDS
  • 24. Using apex_util.json_from* • procedures: *_sql, *_array, *_items, *_string • CONS: • “not documented” • no null, true and false values • hard to create nested JSON objects • no parsing • security issue: passing string into json_from_sql • PROS: • simple and easy to develop • auto escaping • recognizes some value types (number) • available before APEX 5
  • 25. Generate JSON • Manually by concatenating strings • apex_util.json_from_* • PL/JSON library • APEX_JSON package • ORDS
  • 26. PL/JSON • open source library (2009.) • DB types: JSON (object) and JSON_LIST (array) • CONS • complex • lack of real documentation • performance issues • PROS • can be stored in DB • parsing • supports all value types • open source • available before APEX 5
  • 27. Generate JSON • Manually by concatenating strings • apex_util.json_from_* • PL/JSON library • APEX_JSON package • ORDS
  • 28. APEX_JSON API • PROS: • native • generating and parsing • can be used as standalone (CLOB) • light footprint • easy conversion from/to xmltype • CONS: • only in APEX 5.0+
  • 29. APEX_JSON API • Simple JSON Array apex_json.open_array; for emp in (select * from emp where deptno = p_deptno) loop apex_json.write(emp.ename); end loop; apex_json.close_array;
  • 30. Nested JSON object - with cursor declare cur_dept sys_refcursor; begin open cur_dept for select d.dname , d.loc , cursor (select e.ename , e.job , e.sal , (select m.ename from emp m where m.empno = e.mgr) manager , decode(e.comm, null, 'false', 'true') as hasCommision from emp e where d.deptno = e.deptno) as emps from dept d where d.deptno = nvl(p_deptno, d.deptno); apex_json.open_object; apex_json.write('DEPTS',cur_dept); apex_json.close_object; end;
  • 31.
  • 32. Parsing simple JSON object declare v_json_object varchar2(100) := '{"dname":"ACCOUNTING","loc":"NEW YORK"}'; begin apex_json.parse(v_json_object); dbms_output.put_line( apex_json.get_varchar2('dname') ); end;
  • 33. Parsing nested JSON object declare v_json_object clob := ‘{…}’; begin apex_json.parse(v_json_object); dbms_output.put_line( apex_json.get_varchar2('DEPTS[1].EMPS[2].ENAME') ); dbms_output.put_line( apex_json.get_varchar2(p_path => 'DEPTS[%d].EMPS[%d].ENAME’ , p0 => 1 , p1 => 2) ); end;
  • 34. Generate JSON • Manually by concatenating strings • apex_util.json_from_* • PL/JSON library • APEX_JSON package • ORDS
  • 35. Oracle REST Data Services (ORDS) • easy to develop modern REST interfaces • ways to use it: • APEX GUI • SQL Developer (auto-rest) • PL/SQL API • Simple Oracle Document Access (SODA) API over REST • URL format: • protocol://host:port/ords-name/apex-workspace-name/uri-template/bind-value • https://apex.oracle.com/pls/apex/mgoricki/dept/10
  • 37. Oracle Rest Data Services (ORDS) • CONS • little slower • you need ORDS • PROS • declarative and simple • many options • easy to create nested JSON objects
  • 38. Best method? • It depends! 
  • 39. 657.80 1574.00 287.00 332.80 254.70 0.00 200.00 400.00 600.00 800.00 1000.00 1200.00 1400.00 1600.00 1800.00 ORDS PL/JSON apex_json apex_util.json_from_sql Manually Average execution time (ms)
  • 40. 29.90 29.30 29.30 29.30 29.30 29.00 29.10 29.20 29.30 29.40 29.50 29.60 29.70 29.80 29.90 30.00 ORDS PL/JSON apex_json apex_util.json_from_sql Manually Average JSON size (KB)
  • 41.
  • 42. JSON and Oracle12c • native support from 12.1.0.2 • store JSON data (with VARCHAR2, CLOB or BLOB data types), index, query… • parse JSON data with SQL
  • 43. JSON and Oracle12c • storing JSON data create table my_json( json_col clob ); alter table my_json add constraint valid_json check (json_col is json); insert into my_json values ('{"dname":"ACCOUNTING","loc":"NEW YORK"}');
  • 44. JSON and Oracle12c • parsing JSON data SQL> select json.json_col.dname from my_json json; DNAME --------- ACCOUNTING
  • 45. Using JSON • APEX use it (IR, Page designer) • New APEX 5.1 grid • Oracle JET • fetch asynchronously data with AJAX • communicate with Web services (REST API - Twitter, Flickr, Google Apps) • easy to use with JavaScript
  • 46.
  • 47. Old HTML way HTTP Request HTML page Client / Browser Server / DB
  • 48. AJAX partial page AJAX Request HTML part Client / Browser Server / DB
  • 49. Client side templates AJAX Request JSON HTML Template Client / Browser Server / DB
  • 50. • light weighted JavaScript templating engine (Mustache.js, AngularJS, Backbone.js, Ember.js, Marko.js…) used for client-side data binding • subset of Mustache.js + minimal logic • works by expanding tags in a template using values provided by JSON object • tags can be replaced with value, nothing or series of values Handlebars.js
  • 52. Handlebars.js templates • tags start and end with double braces (mustaches) {{…}} • two simple types of tags: • variables - basic tag type {{title}} • sections/block expressions - render block of text one or more times {{#posts}}…{{/posts}}
  • 53.
  • 54.
  • 55. In APEX • Add JS library • Create template item
  • 56. • Define HTML object where to put result • Fetch JSON and run render function In APEX Example
  • 58. 578.80 657.80 1574.00 287.00 332.80 254.70 0.00 200.00 400.00 600.00 800.00 1000.00 1200.00 1400.00 1600.00 1800.00 Report region ORDS PL/JSON apex_json apex_util.json_from_sql Manually Average execution time (ms)
  • 59. 122.00 29.90 29.30 29.30 29.30 29.30 0.00 20.00 40.00 60.00 80.00 100.00 120.00 140.00 Report region ORDS PL/JSON apex_json apex_util.json_from_sql Manually Average JSON size (KB)
  • 60. Real-life example Generation time: 2 minutes Response time: 2.3 MB Only first 700 rows
  • 61. Real-life example Generation time: 2.9s vs 2 minutes Response time: 500KB vs 2.3 MB All 2422 rows vs 700 rows
  • 62. Q&A

Editor's Notes

  1. Today I'll speek about how can you improve you apps by using JSON and templating engine called Handlebars.
  2. - specialized in converting old and rusty Oracle Forms to new shiny APEX applications with responsive web design - especially in insurance and banking Some in house apps we’ve had first APEX community qoute BiLog Web Page is build in APEX
  3. - maybe I don't look like this, but I've started working with Oracle Forms and Reports - And I'm thankfull for this because it was a strong background for APEX - last 8 years working with APEX and related web technologies - I like to answer APEX questions and solve complicated problems so I write APEX related blog and tweets
  4. When I talk about APEX I like to mention this quote from Tom Kyte about 3 answers that you have to know to answer any question about Oracle database. In APEX its always it depends. Everything can be solved in so many different ways and you’ll see that this is the case when we talk about JSON
  5. Today I’ll speak about tree things: Basic information about JSON How to generate and parse JSON with PL/SQL And at the end I’ll show interesting example how to use it together with Handlebars.js to IMPROVE your APEX applications basic information about JSON show you the ways how to generate JSON in Oracle and APEX and at the end I’ll show interesting example how can you use it in you APEX app and IMPROVE functionalities
  6. In some languages name-value is called attribute-value / key - value / string – value easy to read and write – for humans easy to generate and parse – for machines Language independent – it’s text format that uses conventions that are familiar to programmers of many programming languages like C, C#, C++, Java, JavaScript, Perl, Python…; A variety of programming languages can parse and generate JSON data. And that makes JSON ideal for data interchange Subset of JavaScript notation – you can natively use it in JavaScript which is ideal for Web Apps, JSON can often be used in JavaScript programs without any need for parsing or serializing • APEX interactive grid uses JSON • Oracle JET report uses JSON
  7. : colon, comma What about JSON format? On the right side you can see sample JSON object that consists of employees from one department. As I said, JSON is data interchange format that consists of name-value pairs. On the left side you can see name part. Name should always be in double quotes (although Oracle DB 12s supports it without qoutes, APEX_JSON package doesn’t). If you compare it to PL SQL: Object - associative array Array - varray Name should always be in double quotes (although Oracle DB supports it without qoutes, but APEX_JSON doesn’t)
  8. Can be 7 different data types. A value can be a string in double quotes, or a number, or true or false or null, or an object or an array you have to be careful about null data type. it’s not the same as SQL null value if you query JSON object IS NULL to null column will return FALSE SQL condition IS NULL condition returns false for a JSON null value, and SQL condition IS NOT NULL returns true.
  9. - A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. - similar to Oracle associative arrays
  10. An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence. similar to PL SQL varray and thats all you have to know about JSON
  11. JSON is sticked to predefine datatypes in XML you can define custom ones by using XML Schema, DTD. It can be advantage but on the other side it becomes more complex and difficult to read JSON is structured (in arrays and objects) and that makes JSON easy to handle in many programming languages. In other hand, XML is structured in trees You can send files with XML, but not with JSON-on, its data centric and used only for sending data With JSON you are sending only data, but with XML you are sending also the metadata that describes data that you are sending In a case of Oracle DB, both JSON and XML can be used similar - stored, queried, indexed but it’s a bit different in UI (JavaScript) I can say that JSON is best tool for sending data in AJAX communication
  12. It’s like you have to dig a hole and only thing that you have it’s shovel lopata = shovel
  13. bager - dredge
  14. higher level solutions that you’ll use when creating some API for others Oracle REST Data Services (ORDS) - (mid tier Java application) makes it easy to develop modern REST interfaces for relational data in the Oracle Database and now node.js - Node.js is an open-source, cross-platform runtime environment for developing server-side Web applications. driver for Oracle DB When it comes to generating JSON, Node.js seems like a natural choice as JSON is based on JavaScript objects. However, it’s not exactly fair to compare a solution crafted in Node.js to the PL/SQL solutions as Node.js has a clear disadvantage: it runs on a separate server. That means we have to bring the data across the network before we can transform it to the desired output.
  15. In this examples I’ve used this query for generating JSON If you are using JSON internally, and in most cases in APEX you will, use short aliases. You can document the code where you generate it When you will use this – it depends – if you are creating pubic API
  16. Name string is repeating and it takes unnecessary space
  17. manually deal with escaping values It can be fast – no additional engine logic
  18. In case of JSON_FROM_SQL it can be dangerous: can’t pass parameters or add bind variables - vulnerable to SQL injection you can have problems with invalid SQL Query (if you remove column, drop table…) - in most cases I’ve used this apex_util.json_from_array because its safer
  19. Originally started in 2009 bigger foot print – 9 packages, and 4 object types It uses some of object-oriented features of Oracle DB PL/JSON can take some time to learn and get used to Not documented – learn by looking at the examples
  20. - comes with APEX 5, but it can be used as standalone (INITIALIZE_CLOB_OUTPUT procedure) - parsing and generating utilities - build and supported by Oracle -JSON content to a HTP buffer - it’s possible to redirect the output to a CLOB buffer instead
  21. apex_json.open_array; for emp in (select * from emp where deptno = p_deptno) loop apex_json.write(emp.ename); end loop; apex_json.close_array;
  22. 2 ways to do it: 1) manually writing logic 2) using sys_Refcursor
  23. APEX_JSON.PARSE - two signature procedures: 1) parses a JSON-formatted varchar2 or clob to package global variable g_values 2) has different parameters, and outputs JSON into output variable GET functions GET_VALUE GET_VARCHAR2 GET_NUMBER GET_DATE
  24. - dot notation - more than one signature
  25. - released in 2010 as APEX Listener - REST support for JSON was added in 2011 The ORDS PL/SQL package contains subprograms (procedures and functions) for developing RESTful services using Oracle REST Data Services. with ORDS 3.0 ships with the Oracle Database 12c Document Store JSON documents can now be stored in and retrieved from document collections managed by Oracle Database. SODA for REST provides an interface to the Oracle Database Document Store for NoSQL style application development.
  26. APEX_JSON adds unnecessary blank spaces – only in debug mode
  27. - stored, indexed, and queried - Oracle Database queries are declarative Functions json_value, json_query, and json_table. Conditions json_exists, is json, is not json, and json_textcontains. A dot notation that acts similar to a combination of json_value and json_query and resembles a SQL object access expression, that is, attribute dot notation for an abstract data type (ADT).
  28. Oracle recommends that you always use an is_json check constraint to ensure that column values are valid JSON instances
  29. Minimal Templating on Steroids
  30. To better understand templating engines, lets look how HTML data can be fetched
  31. I’ve googled about it Minimal Templating on Steroids Handlebars helpers, expressions, share templates, precompile templates You can write JavaScript in helpers HTML values are auto escaped
  32. double braces {{ }}
  33. half the time faster
  34. size of JSON is 4 times smaller
  35. Real life example - calendar with monthly working hours log