100% found this document useful (1 vote)
710 views345 pages

ZS4HCDS Complete PDF

Uploaded by

Abid Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
710 views345 pages

ZS4HCDS Complete PDF

Uploaded by

Abid Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 345

ZS4HCDS

S/4HANA Development Fundamentals


SAP Development University
November, 2016 Internal
Welcome And Introduction

Welcome
to the

S/4HANA Development Fundamentals

Classroom, <Month> <Day>, <Year>


09:00 – 17:00 CET

Your instructor: <Name>

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 2


Overview – S/4HANA Development Fundamentals

Day 1
Unit 1 Introduction – Technical Concepts, ADT Exercise 01 Exercise 02

Unit 2 Introduction to Core Data Services Exercise 03 Exercise 04

Lunch Break

Unit 3 Core Data Services: SQL Features Exercise 05 Exercise 06 Exercise 07 Exercise 08

Day 2
Unit 4 Advanced Concepts in CDS Exercise 09 Exercise 10 Exercise 11

Lunch Break

Unit 5 New Features in Open SQL Exercise 12 Exercise 13

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 3


Overview – S/4HANA Development Fundamentals

Day 3
Unit 6 Virtual Data Model (VDM) Exercise 14

Lunch Break

Unit 7 HANA Native Code Push Down Exercise 15 Exercise 16 Exercise 17

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 4


Appendix – S/4HANA Development Fundamentals

Appendix Lessons and Exercises


A1 Helpful ABAP Language Enhancements Exercise 18

A2 Introduction to SAP HANA Studio Exercise A2

A3 Guided Performance Analysis Exercise 19 Exercise 20

A4 VDM Analytical Perspective

A5 CDS Unit Testing

A6 Fiori Programming Model

A7 Miscellaneous

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 5


Unit 1 – Introduction
Unit 1 – Introduction
Lesson 1 – SAP HANA Basics and Technical Concepts
What Made SAP HANA Possible?

HW Technology Innovations SAP SW Technology Innovations


Multi-Core Architecture
(8 CPU x 10 Cores per blade) Row and Column Store

Massive parallel scaling with


many blades Compression

Partitioning
64bit address space –
4 TB in current servers No Aggregate Tables
Dramatic decline in
price/performance
+ Insert Only on Delta
+ ++

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 10


Innovations Shift Bottlenecks

Past: Now:

Still to be considered:
Data transfer via network Application Server Data transfer via network

CPU
Core

CPU Cache
CPU waiting for data to be
loaded from memory into cache
Main Memory
Performance bottleneck in the
past: Disk I/O
Disk

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 11


New Bottlenecks Become Important – How To Avoid Them?

Two Challenges
1. Optimize loading data into the CPU cache
 Introduce columnar data storage
 Use compression for database tables

2. Avoid CPU idle time – make use of parallelism


 Process one request on several cores in parallel
 Distribute table contents across blades (partitioning)

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 12


Row Store

Data in table … … organized in rows

Order Country Product Sales 456 France corn 1000


456 France corn 1000
457 Italy wheat 900 457 Italy wheat 900
458 Italy corn 600
458 Italy corn 600
459 Spain rice 800
459 Spain rice 800

SELECT SINGLE * … SELECT SUM(Sales) …


WHERE ORDER = 457

Works fine in row store Row store not optimal

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 13


Column Store

Data in table … … organized in columns

Order Country Product Sales


456 France corn 1000
456 France corn 1000
457 Italy wheat 900 457 Italy wheat 900 
458 Italy corn 600 458 Italy corn 600
459 Spain rice 800 459 Spain rice 800

SELECT SINGLE * … SELECT SUM(Sales) …


WHERE ORDER = 457

Very expensive on column store Ideal for column store

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 14


Columnar Dictionary Compression

 SAP HANA operates directly on compressed data, using integers


 More in-cache, less main memory access, less data to be loaded into cache & CPU
 More advanced encodings depending on circumstances

Logical Table
Compressed
Order Country Product Sales Dictionary column
456 France corn 1000 1 Belgium 1 3
457 Italy wheat 900 2 Denmark 2 4
3 France 3 5
458 Spain rice 600
4 Italy 4 4
459 Italy rice 800 5 Spain 5 2
460 Denmark corn 500 6 2
5 entries 
461 Denmark rice 600 7 1
3 bits to encode
462 Belgium rice 600 8 4
… …
463 Italy rice 1100
Where was
… … … … order 460?

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 15


Fewer Non-Unique Index Required

 Full column scans are usually fast enough – far fewer non-unique indexes required
 Only if table contains 100 000s of rows consider a non-unique index comprising a single column only
Leads to an “inverted index” in SAP HANA
Create in exceptional
cases only!
Logical Table
Compressed Inverted
Order Country Product Sales Dictionary column index
456 France corn 1000 1 Belgium 1 3 1 7
457 Italy wheat 900 2 Denmark 2 4 2 5,6
3 France 3 5 3 1
458 Spain rice 600
4 Italy 4 4 4 2,4,8
459 Italy rice 800 5 Spain 5 2 5 3
460 Denmark corn 500 6 2 Which orders
5 entries 
461 Denmark rice 600 7 1 in Italy?
3 bits to encode
462 Belgium rice 600 8 4
… …
463 Italy rice 1100
Where was
… … … … order 460?

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 16


When Use Row Store, When Column Store?

Column store is best for: Row store is more suitable when:


 Column based operations on large number  Table mainly contains distinct values
of rows  Low compression rate
 Large number of columns, many unused  All columns of are relevant
 Aggregations and intensive search  No aggregation or search on non-indexed
columns
 Master and transactional data ?  Table is fully buffered
 Table has a minor number of records
 Table contains unstructured data

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 20


© SAP AG 2012
Implications: Code-To-Data Paradigm

Classical Approach
Calculations
l Application Layer

Data Layer
Calculations
New Approach

In-Memory Computing Imperative: Movement calculations into the database


Only transfer results

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 21


Highlights of SAP NetWeaver AS ABAP ≥7.4 – Overview

ABAP
applications using SAP HANA
ABAP development guidelines Guidelines

Improved tools for performance analysis

Extensions to ABAP language


Creating and consuming SAP HANA content
with ABAP
Re-use components optimized for SAP HANA

Transparent optimizations Transparent Optimizations


SAP NetWeaver AS ABAP ≥7.4

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 22


How To Use Column Store Or Row Store For ABAP Table?
ABAP Dictionary Extensions in ABAP 7.4

“Storage type” of ABAP tables can be set with SAP ABAP Dictionary
NetWeaver ABAP 7.4. Table

Use ABAP Dictionary


 Technical settings
 DB-specific properties
?
Default on SAP HANA
 Column store

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 23


Exercise 01: Log on to the ABAP System

In this exercise you will:


 Log on to the ABAP system(s) used during the course
 Determine the SAP HANA store used for ABAP Dictionary table BUT000
 Determine which non-unique indexes for ABAP Dictionary table BUT000 are created on SAP
HANA

Time: 10 min

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 24


Where can you find more information?

ABAP Platform
 ABAP for HANA Group: https://jam4.sapjam.com/groups/Fu55Xg4QjvITMyNjFr5dIT
 ABAP for HANA on SCN: http://scn.sap.com/community/abap-for-hana

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 26


Unit 1 – Introduction
Lesson 2 – Introduction to ABAP Development Tools (ADT)
An Eclipse-based Development Environment

Eclipse™ is SAP’s strategic platform for highly integrated


design-time and development tools.

 SAP ABAP Development Tools are Eclipse-based; tools based on existing Eclipse frameworks
 Common development environment for SAP HANA and ABAP (ADT) going forward
© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 29
ABAP Development Tools for SAP NetWeaver – Architecture

New ABAP Development experience Developer


 Enables cross-platform development, e.g.
SAPUI5, Java, SAP HANA
 One client to connect to several ABAP Eclipse Client SAP Logon
back-ends
And
 ABAP development tools specifically for SAP HANA ABAP Development
Studio Tools (ADT) SAP GUI for
SAP HANA Windows
 UI development tools for Web Dynpro and Eclipse Platform
Floorplan Manager
 ABAP Debugger integrated in Eclipse

ABAP back end 1 ABAP back end N

SAP HANA Database Or Classic Database

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 30


Working with ABAP Projects

ABAP Project
 Connection to ABAP system using a Connection to
particular user ABAP System
 Access any ABAP repository object
 Add frequently used ABAP packages to ABAP Class
Favorite Packages for fast access

Function Pools

ABAP Interface

ABAP
Programs

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 31


Working with ABAP Projects – Editors

Native – with Eclipse Look & Feel Integrated SAP GUI

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 32


Working with ABAP Projects – Shortcuts

https://go.sap.corp/adt_ref_card Navigation: hold Ctrl key

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 33


Working with ABAP Projects – Editing Source Code

Many helpful features


 Keyword completion incl. code templates
 Ctrl+Space: Content Assist (Code completion)
 CtrlL+1: Quick Fix
 Refactoring capabilities e.g. extract method

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 34


Troubleshooting Tools – ABAP Debugger in Eclipse

Debug perspective
 Opens when code runs and hits
breakpoint
 Step over, into, resume …
as usual
 Display variables & tables

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 35


CDS Development Environment

 Based on Eclipse platform and


therefore integrated in ABAP in
Eclipse
 Textual and Graphical
 Rich feature set for fast development
Code completion
Enhanced data preview
Quick-Fix function
Syntax highlighting

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 36


ABAP Development Tools
Data Preview

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 37


Getting ABAP Development Tools for SAP NetWeaver

Get ABAP Development Tools for SAP


NetWeaver from:

SAP Software Download Center


 http://service.sap.com/swdc

SAP Development Tools for Eclipse


 http://tools.hana.ondemand.com/

Also see SAP Community Network


 http://scn.sap.com/community/abap/eclipse
 http://scn.sap.com/community/abap/hana

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 38


Installed Features

Overview of installed features in


Eclipse / SAP HANA Studio / ADT
 Menu item Help  About
 Detailed list of features using
Installation Details

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 39


Installing and Updating Features

Keeping an Eclipse installation up-to-date Installing additional plug-ins


 Menu item  Configure Available Software Sites
Help  Check for Updates  Menu item Help  Install New Software

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 40


Exercise 02: Create an ABAP Project in ADT

In this exercise you will:


 Open ABAP Development Tools and connect to an Application Server ABAP
 Make a development package a favorite in your project
 Write a simple ABAP program and debug it using ADT

Time: 10 min

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 41


Where can you find more information?

ABAP Platform
 ABAP for HANA Group: https://jam4.sapjam.com/groups/Fu55Xg4QjvITMyNjFr5dIT
See e.g. https://jam4.sapjam.com/wiki/show/gX0f6OS0B0ob4pbzC5mWxl for how you can easily install
ADT and SAP HANA Studio within the SAP network.
 ABAP for HANA on SCN: http://scn.sap.com/community/abap-for-hana

ABAP Development Tools for SAP NetWeaver (ABAP in Eclipse)


 ADT Group on SAP Jam: https://jam4.sapjam.com/groups/557144
 ADT Quick Reference Card: https://go.sap.corp/adt_ref_card
 ADT on SCN: http://scn.sap.com/community/abap/eclipse
 ADT on Youtube: http://www.youtube.com/watch?v=BXg7xXrEAUw
 Connecting to customer systems for support: TBA

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 42


Unit 1 – Introduction
Lesson 3 – Introduction to the SFLIGHT Data Model
SAP Flight Data Model Overview

Real World

Data Model

ABAP Dictionary

Relational
Database

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 46


SAP Flight Data Model

Departure City

Departure Airport

Arrival Airport

Destination City

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 47


Relational Data Model

BC_CARRIER T BC_AIRPORT T BC_GEOCITY T


Airline Airport City

H A A
BC_PLANFLI T R R BC_CITAIRP T
Flight Schedule City Airport
Assignment

H
BC_SFLIGHT T BC_CUSTOM T BC_COUNTER T BC_TRAVLAG T
Flight Flight Sales Office Travel Agency
Customer

H
BC_BOOKING T R CR CR

Flight Booking

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 48


Implementation Using Transparent Tables

BC_CARRIER T SCARR
Airline
MANDT CARRID CARRNAME CURRCODE URL

H
BC_PLANFLI T SPFLI
Flight Schedule
MANDT CARRID CONNID AIRPFROM AIRPTO DEPTIME . . .

H
BC_SFLIGHT T SFLIGHT
Flight
MANDT CARRID CONNID FLDATE SEATSMAX SEATSOCC ...

H
BC_BOOKING T SBOOK
Flight Booking
MANDT CARRID CONNID FLDATE BOOKID CUSTOMID COUNTER . . .

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 49


Transparent Tables

Transparent Table

Field
described
by
Data Element
points to

Domain

Table containing data

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 50


Lesson 3: Introduction to the SFLIGHT Data Model
Summary

You should now be able to:


• Describe the SFLIGHT Data Model

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 52


Unit 2 – Introduction to Core Data Services
Unit 2 – Introduction to Core Data Services
Lesson 1 – Motivation and Definition
Transformation of Application Design with SAP HANA

Classic Data-Centric
Applications Applications

UI Rendering UI Tier
UI & Client Side
Application Logic
UI Application Logic

Service Logic Middle Tier


Service Layer

Data-Centric Logic
SAP HANA
Relational Database
Database Database

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 57


Paradigm Changes in Application Programming

Data-To-Code:
Intensive
computations <code>

in APPLICATION
layer

Code-To-Data:
Intensive
computations
in DATABASE
layer

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 58


Motivation for Core Data Services

? Can’t everything be done with SQL

In principle yes, but …


!
© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 59
Issue 1: Large Semantic Gap between Task and SQL Code Today

Conceptual Level

Task: Get the id, name and the respective zip code of the home address for all
employees in org-unit ’Development’

Large Semantic Gap

Implementation Level

SQL: SELECT e.id, e.name, a.zipCode FROM Employee e


INNER JOIN OrgUnit u ON u.id = e.orgid
LEFT OUTER JOIN Address a ON e.id = a.id
AND a.type=’HOMEADDR’
WHERE u.name=‘Development’.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 60


Issue 2: SQL Complexity Leads to Imperative Code

Conceptual Level

Issue: Due to the complexity of SQL, developers are using code instead of SQL

Performance gaps: Loops in loops, nested queries with


many round trips, …

Implementation Level
Code: SELECT * FROM Employee INTO TABLE it_empl WHERE orgunit = 4711. “ I know 4711 is the
LOOP AT it_empl. “ id of the dev unit
WRITE it_empl-id.
WRITE it_empl-name.
SELECT * FROM Addresse INTO TABLE it_addrs WHERE id = it_empl-id.
LOOP AT it_addrs.
IF it_addrs-type = ‘HOMEADDR’.
WRITE it_addrs-zipcode.
ENDIF.
ENDLOOP.
ENDLOOP.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 61


CDS Brings Conceptual and Implementation Level Closer Together

Conceptual Level

Task: Get the id, name and the respective zip code of the home address for all
employees in org-unit 4711

Smaller Semantic Gap,


Less Coding required

Implementation level

CDS: SELECT id, name, homeAddress.zipCode


FROM OrgUnit[ name = ’Development’ ].employees

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 62


Next generation data definition and access for database centric applications

ABAP
CORE DATA SERVICES

</>
Common data model Capture business intend Improved programming model
Semantically rich Reduced complexity For all application domains
Declarative Extending SQL Rich set of build-in functions
Close to conceptual thinking Code pushdown capabilities

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 63


Core Data Services – A Family of Domain Specific Languages

The Core Data Services (CDS) are a collection of domain-specific languages and services for defining and
consuming semantically rich data models.

DDL QL DCL
Data Definition Language Query Language Data Control Language

Model and retrieve data on a Consume CDS entities via Define authorizations for CDS
semantic level higher than SQL Open SQL in ABAP views
Extends native SQL means for Fully transparent SQL extensions Modelled and declarative
increased productivity approach
Integrates with classic
authorization concepts

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 64


ABAP integration

Leverage DDIC semantics SAP NetWeaver ABAP

Infrastructure ensures Any-DB OPEN SQL

Lifecycle Management
support
CDS ABAP
Proven and consistent ABAP
Lifecycle Management and
extensibility
(S)QL Engine
Highly reusable and extensible CDS
artifacts

CDS also available in native Any SAP supported DB


SAP HANA

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 65


Core Data Services at a Glance

Semantically Rich Data-Models Common Basis for Domain-Specific


Domain specific languages (DDL, QL, DCL) Frameworks e.g. UI, Analytics, Odata, BW,…
Declarative, close to conceptual thinking @AnalyticsDetails.aggregationBehaviour: SUM

CDS is completely based on SQL Built-in Functions and Code Pushdown


Any ‘Standard SQL’ features directly available Table Functions for Breakout Scenarios
like joins, unions, build-in functions, … Rich Set of Built-in SQL Functions

Fully Compatible with Any DB Extensible


Generated and managed SQL Views On model level thru extensions
Modern Open SQL On meta-model level thru annotations

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 66


CDS Views in ABAP

Lifecycle ABAP stack as Master for editing, activating


and transporting Core Data Services (CDS) View
AS ABAP

Core Data Standard ABAP HANA view deployed during CDS view activation
Services View Transport (CTS)
Only CDS View definition is transported
deploy Only ABAP Development Tools for
SAP HANA

SAP NetWeaver required


SAP HANA
View ABAP CDS provides
read access to data only

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 67


Benefits of CDS Views Compared to ABAP Dictionary Views

Classical ABAP Support on all DBMSs ABAP Core Data


Dictionary Views Services Views
Join/Union, Projection, Selection
inner join & simple or inner join, outer join,
selection only union

Calculation expressions, aggregation, grouping


not supported

Nested views (on views)

not supported

Prefer CDS Views as the more powerful tool

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 68


CDS View Building At a Glance!!!
SQL View name

@AbapCatalog.sqlViewName: 'WDECDS_CONN3ANN'
@ClientDependent: true
@AbapCatalog.compiler.CompareFilter: true
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'Flight Connection with ABAP Annotations'
Buffering-specific
@AbapCatalog.Buffering.type: #GENERIC
annotation
CDS View entity @AbapCatalog.Buffering.numberOfKeyFields: 1
@AbapCatalog.Buffering.status: #ACTIVE

define view Wdecds_Connection3_Annotations


as select from spfli as c
inner join scarr as a
on c.carrid = a.carrid
inner join sairport as af
Joins
on c.airpfrom = af.id
inner join sairport as at
Alias
on c.airpto = at.id
{ key c.carrid,key c.connid,
a.carrname, a.currcode as currency, And many more…
Select list c.cityfrom, c.cityto, c.airpfrom,
@EndUserText.label: 'Dep.Airp.Name'//Annotations before the field  Diverse annotations
@EndUserText.quickInfo: 'Departure Airport Name'
af.name as airpfrom_name,  Unions
c.airpto, at.name as airpto_name
@<EndUserText.label: 'Dest.Airp.Name' /Annotations after the field  Associations
@<EndUserText.quickInfo: 'Destination Airport Name',
 Path expressions
c.fltime,c.distance @<Semantics.quantity.unitOfMeasure: 'DISTID',
Where clause c.distid @<Semantics.unitOfMeasure: true  View on View Entity
}
where c.fltype <> 'X' //exclude charter flights  …

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 69


Lesson 1 – Motivation and Definition
Summary

You should now be able to:


• Describe the motivation for Core Data Services
• Define Core Data Services

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 70


Unit 2 – Introduction to Core Data Services
Lesson 2 – Basic Syntax of CDS Views
CDS View - Define View

Syntax: DEFINE VIEW <cds_entity> AS @AbapCatalog.sqlViewName:'S4HCDS_BOOK'


define view s4hcds_Booking
CDS View Entity (s4hcds_Booking) as select from sbook
• Carries more semantics than SQL View {
carrid,
• Can be consumed by Open SQL
connid,
fldate,
SQL View (S4HCDS_BOOK) bookid,
• Defined using annotation (@AbapCatalog.sqlViewName) …
• Generated on activation of CDS view }
• Representation on Database

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 73


CDS View - Select *

Select * @AbapCatalog.sqlViewName: 'S4HCDS_SEL_ALL'


selects all columns from the underlying define view S4hcds_Select_All as select from sflight {
*
data source
}

Output in Data Preview:

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 74


CDS View - Select columns

Comma separated list of names @AbapCatalog.sqlViewName:'S4HCDS_SEL_V02'


define view s4hcds_sel_v2 as
optional alias names with keyword AS
select fldate as Flightdate, connid as Flightno
from sflight

Alternative Syntax
@AbapCatalog.sqlViewName:'S4HCDS_SEL_V03'
select list after from clause define view s4hcds_sel_v3 as
Output:
enclosed in curly braces {….} select from sflight
{
fldate as Flightdate,
connid as FlightNumber
}

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 75


CDS Views – Select columns

Literals are only supported: @AbapCatalog.sqlViewName:'S4HCDS_SEL_V04'


as C-Sequence Literals (Max length 1333) define view s4hcds_sel_v4 as select from sflight
{
as signed integer Literals (4-Byte) carrid as FlightCarrierID,
'CarrierDescription' as descr
}

Explicit view signature (name_list) @AbapCatalog.sqlViewName:‘S4HCDS_SEL_V05'


 Typically the signature is derived from select define view s4hcds_sel_v5 (ID, descr)
list but it can be explicitly overwritten by a as select from sflight
separate list of names {
carrid as FlightCarrier,
 A name list can not be specified for select * 'Flight description' as descr
}

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 76


CDS Views – Select distinct

Duplicates can occur when a key column is not included in the projection list

@AbapCatalog.sqlViewName:'S4HCDS_SEL_V06A' Output:
define view s4hcds_sel_v6a as select from spfli
{
cityfrom
}

The keyword DISTINCT ensures that the result table contains no duplicates:
Output:
@AbapCatalog.sqlViewName:'S4HCDS_SEL_V06B'
define view s4hcds_sel_v6b as select distinct from spfli
{
cityfrom
}

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 77


CDS Views - WHERE

You can use compound WHERE clauses. @AbapCatalog.sqlViewName:'S4HCDS_SEL_V07'


define view s4hcds_sel_v7 as select from sflight
{
carrid, connid, planetype, seatsmax
}
where planetype ='A340-600' and seatsmax = 330

You can reference the same column multiple times.


@AbapCatalog.sqlViewName:'S4HCDS_SEL_V08'
define view s4hcds_sel_v8 as select from sflight
{
carrid, connid, planetype, seatsmax
}
where planetype ='A340-600' or planetype = 'A319-100'

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 78


Table Aliases
CDS Views

 Table aliases are defined in the FROM clause. @AbapCatalog.sqlViewName:'S4HCDS_SEL_V09'


 You can use table aliases in the projection list. define view s4hcds_sel_v9 as select from scarr as c
{
c.carrname as Carrier,
c.carrid as ID
}

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 79


CDS View – Key Elements

 Key elements should be continuous and placed at the start


of the list @AbapCatalog.sqlViewName:'S4HCDS_BOOK'
define view s4hcds_Booking
as select from sbook
 CDS View key fields need not be same as of the underlying {
data source key carrid,
key connid,
 Key fields for the generated SQL view is not derived from the fldate,
key fields of the CDS view bookid,
class
}
 Evaluated when “ORDER BY PRIMARY KEY” addition is
used in Open SQL

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 80


CDS - General DDL Syntax Rules
The general syntax rules for the DDL of the CDS are:

 Keywords: Keywords must be all uppercase, all lowercase, or in lowercase with an uppercase initial letter.
Mixed uppercase and lowercase is not allowed.

 Names: Names are not case-sensitive. A name can have a maximum of 30 characters.

 Literals: Number literals must always be specified in full and a decimal point (.) used as a decimal separator if
necessary. Character literals are enclosed in single quotations marks (').

 Comments: Two forward slashes (//) introduce a comment, which continues until the end of the line.
Comments within lines or that span multiple lines are enclosed by the characters /* and */.

 Separators: Statements can be closed using a semicolon (;). This is optional.

 Protected Words: Certain keywords are protected and cannot be used as self-defined names.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 81


Syntax Rules - Examples

 SELECT, select, and Select - Valid ways of specifying a keyword.

 seLect and SeLect – Invalid, produce syntax errors.

 MYVIEW, myview, and myView all identify the same operand.

 0.5 is a valid number literal, but .5 is not.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 82


CDS View Lifecycle – Create

CDS is source based


Activate Consume
Tools:
ABAP Development Tools
(eclipse based)
• Textual CDS source code editor
Create or • Graphical CDS modelling view
Modify
• Dependency Analyzer
• Annotation viewer

@AbapCatalog.sqlViewName:'S4HCDS_BOOK'
define view s4hcds_Booking as select from sbook
{
key carrid,
key connid,
fldate,
bookid,
class
}

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 83


CDS View Lifecycle – Activate

During activation of a DDL


Activate Consume source:
1. Corresponding DDIC view gets
generated
2. The view gets deployed to the
Create or
Modify database

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 84


CDS View Lifecycle – Consume

Open SQL

Activate Consume Application frameworks consuming CDS


annotations
Annotation API

Create or Tools:
Modify ABAP source editors (SE38, SE24, ADT)
Trace Tools (SQLM, ST05)

REPORT Y_CDS_CONSUMPTION_EXAMPLE.

DATA lt_result TYPE STANDARD TABLE OF s4hcds_Booking.


SELECT * UP TO 10 ROWS
FROM s4hcds_Booking
INTO TABLE @lt_result
WHERE bookid BETWEEN '25' and '30'.

cl_demo_output=>display_data( lt_result ).

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 85


Generated SQL Statement for CDS View

Two ways to get the generated CREATE SQL statement in the database for the CDS view
1. Right Click on the CDS source editor in Eclipse and select “Show SQL CREATE Statement”
2. Open the generated database view in SE11 and select Menu -> Extras -> CREATE Statement

Example:

@AbapCatalog.sqlViewName:'S4HCDS_SEL_V09'
CREATE VIEW "S4HCDS_SEL_V09" AS SELECT
define view s4hcds_sel_v9 as select from
scarr as c "C"."MANDT" AS "MANDT",
{ "C"."CARRNAME" AS "CARRIER",
c.carrname as Carrier, "C"."CARRID" AS "ID"
c.carrid as ID FROM "SCARR" "C"
}

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 86


Data Preview

 Eclipse Tool to view the data of the CDS view


 Right click on the CDS source editor and select “Open With” -> “Data
Preview”

@AbapCatalog.sqlViewName:'S4HCDS_SEL_V09'
define view s4hcds_sel_v9 as select from scarr as c
{
c.carrname as Carrier,
c.carrid as ID
}

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 87


Exercise 03: Define Views Using Core Data Services

In this exercise you will:


 Create a simple Core Data Services (CDS) view
 Use Data Preview tool to check the output of the CDS view
 Use alias names for the fields and use Where clause
 Write a simple ABAP program to consume the CDS view using Open SQL
 See Student Manual, Exercise 3 Tasks 1-6

Time: 15 min

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 88


Lesson 2 – Basic Syntax of CDS Views
Summary

You should now be able to:


• Describe the syntax structure of a simple CDS view
• Define a simple CDS view with Select and Where Clause
• Explain the Syntax Rules for CDS DDL
• Explain the life cycle of CDS

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 91


Unit 2 – Introduction to Core Data Services
Lesson 3 – Annotations
CDS: Common Basis for Domain-Specific Frameworks

 Reusable and unified view model for all use cases Business
Logic

 Annotations enabling flexible usage in different contexts


Planning Analytics

 Efficient development
CDS

BI-Tools OData

Search

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 94


Annotations

 Enrich CDS data models with additional metadata.

 Annotations begin with @

 ABAP Annotations:
 Evaluated by the ABAP Core Data Services framework, namely the ABAP runtime environment itself

 Component Annotations:

 Evaluated by frameworks of other SAP software components (e.g., ODATA, UI and Analytics)

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 95


Kinds of Annotations

• AbapCatalog Annotations • SearchIndex Annotations


• AccessControl Annotations • Semantics Annotations
• Analytics Annotations • UI Annotations
• AnalyticsDetails Annotations • VDM Annotations
• ClientDependent Annotations
• Consumption Annotations
• DataAging Annotations
• DefaultAggregation Annotations
• EndUserText Annotations
• EnterpriseSearch Annotations
• Environment Annotations
• Hierarchy Annotations
• MappingRole Annotations
• ObjectModel Annotations
• OData Annotations
• Search Annotations

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 96


AbapCatalog Annotations

Define technical settings of CDS entities in the ABAP dictionary.


• AbapCatalog.sqlViewName: Database view in ABAP dictionary that is generated at activation
• AbapCatalog.sqlViewAppendName: Database view for CDS extension
• AbapCatalog.buffering.numberofkeyFields:
Number of key elements for buffering generic areas (Default 000)
• AbapCatalog.buffering.status :
• #ACTIVE: SAP Buffering active
• #SWITCHED_OFF: SAP buffering allowed but not active (Default)
• #NOT_ALLOWED: SAP buffering not allowed.
• AbapCatalog.buffering.type:
• #SINGLE: Buffering type- single records
• #GENERIC: Buffering type- generic area
• #FULL: Buffering type- full
• #NONE: Buffering type- none (Default)

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 97


AbapCatalog Annotations

• AbapCatalog.compiler.compareFilter: (Default: true)


• true : the filter conditions of the path expressions of the view are compared. If the same
filter condition occurs, the associated join expression is only evaluated once.
• false : a separate join expression is created and evaluated for each filter condition.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 98


ClientDependent Annotation

Defines the client handling when Open SQL is used to access a CDS entity

• ClientDependent: (Default: true)


• true : The CDS view is client-specific. The view fields of the CDS entity do not cover a client
column, from the perspective of an ABAP program. When accessed using SELECT,
automatic client handling is performed.
• false : The CDS view is a cross-client view. No automatic client handling is performed.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 99


EndUserText Annotations

Enable an intuitive consumption of the data model in User Interfaces

EndUserText.label:
Defines a human-readable text that is displayed besides input fields or as column headers.

EndUserText.quickInfo:
Defines a human-readable text that provides additional information compared to the label text. The
quickInfo element is used for accessibility hints or the mouse over function.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 100
Example

@AbapCatalog.sqlViewName: ‘S4HCDS_CONN3ANN‘

@AbapCatalog.compiler.compareFilter: true

@AbapCatalog.Buffering.type: #GENERIC

@AbapCatalog.Buffering.numberOfKeyFields: 1

@AbapCatalog.Buffering.status: #ACTIVE

@EndUserText.label: 'Flight Connection with ABAP Annotations‘

@ClientDependent: true

define view s4hcds_Connection3_Annotations as select from spfli


{
// Projection list
}

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 101
Take Away Annotations

• Separation of metadata and core data model Annotation allows


independency from Core Data Model
• Allow applications to add their specific view
properties to the Data Model And can be defined at many view
parts!
• Annotations can be defined for view header,
columns and parameters

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 102
Exercise 04: Make the CDS view cross-client

In this exercise you will:


 Use ClientDependent Annotation to make your view client independent
 See Student Manual, Exercise 4 Tasks 1-3

Time: 15 min

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 103
Unit 3 – Core Data Services: SQL Features
Unit 3 – Core Data Services: SQL Features
Lesson 1 : Expressions and Built-In Functions
CDS Built-in Function Overview

Generic SQL Conversion Arithmetic Date and Time


String Functions
Expressions Functions Functions Functions

• Simple- / • Unit-Conversion • Concat • Abs • Days between


Searched-Case • Currency- • Instr • Ceil • Add Days
• Coalesce Conversion • Left / Right • Div (Integer) • Add Month
• Cast • Length • Division (Dec) • Current Tmstp
• Hex2Bin • Lpad / Rpad • Floor • Date is Valid
• Bin2Hex • Ltrim / Rtrim • Mod • Tmstp is Valid
• Decimal Shift • Replace • Round • Seconds btw.
Tmstps
• Add seconds

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 109
Arithmetic Expressions

Supported operators
@AbapCatalog.sqlViewName: 'S4HCDS_SEL_VD12'
+, - , * and unary - define view s4hcds_sel_v12 as select from sbook
{
forcurkey,
Complex expressions forcuram as Amount,
bracketing of sub expressions possible cast( forcuram as abap.fltp )
+ ( cast ( -forcuram as abap.fltp ) * 0.03 ) as
reduced_amount,
cast( forcuram as abap.fltp )* 0.03 as savings
}

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 110
CASE Expressions
Simple CASE Expression

 The projection list can contain columns that are based on a case differentiation
 These columns can be named explicitly

 Example: The output is list of columns from table SBUSPART resulting TYPE as customer or Travel Agency
based on the TypeCode.
@AbapCatalog.sqlViewName: 'S4HCDS_SEL_VD10'
Supported expressions after define view s4hcds_sel_v10 as select from sbuspart
CASE: columns | built-in functions | {
arithm. expr. | path expr. | parameters buspartnum as ID,
contact,
WHEN: columns | literals | CASE | path expr.
contphono,
THEN: everything but built-in functions case buspatyp
ELSE: everything but built-in functions when 'FC' then 'Customer'
ELSE when 'TA' then 'Travel Agency'
else 'NA'
is optional
end as Type
Resulting column type }
derived from expressions after THEN and ELSE

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 111
CASE Expressions
Searched CASE Expression

 Operates like an if … elseif construct @AbapCatalog.sqlViewName: ‘S4HCDS_SCASE'


 Evaluates a series of boolean expressions and define view s4hcds_searched_case as select from spfli
returns the result of the first expression that {
evaluates to true key carrid,
key connid,
distance,
distid,
CASE WHEN cond_expr1 THEN result1 case
[WHEN cond_expr2 THENresult2] when distance >= 2000 then 'long-haul flight'
when distance >= 1000 and
[WHEN cond_expr3 THENresult3]
distance < 2000 then 'medium-haul flight'
... when distance < 1000 then 'short-haul flight'
[ELSE resultn] else 'error'
END ... end as flight_type
}

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 112
Nested CASE Expression

Example
@AbapCatalog.sqlViewName:‘S4HCDS_SEL_VD11'
 Based on the flight details give priority as follows: define view s4hcds_sel_v11 as select from spfli
{
 Carrid= AA => Priority 1
carrid,
 Carrid= LH and connid =400 => Priority 2 connid,
case carrid
 Carrid= LH and connid=except 400 => Priority 3 when 'AA' then 'Prio1'
when 'LH' then
 Carrid = others => Priority Unknown
case connid
when '0400' then 'Prio2'
else 'Prio3'
end
else 'Unknown'
end as Priority
}

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 113
CAST Expression

 Supported Operands: Literal, column, path


expression, build-in function, arithmetic expression @AbapCatalog.sqlViewName: 'S4HCDS_SEL_VD12'
define view s4hcds_sel_v12 as select from sbook
 Various data types in ABAP namespace supported {
 Result length determined at activation time forcurkey,
forcuram as Amount,
 No nesting of CAST expressions cast( forcuram as abap.fltp )
 Alias names required for resulting columns + ( cast ( -forcuram as abap.fltp ) * 0.03 )
as reduced_amount,
Example: cast( forcuram as abap.fltp )* 0.03
Cast foreign currency amount from sbook as reduced_amount as savings
and Savings. }

Supported types in ABAP namespace:


char( len ), clnt, cuky( len ), curr( len, decimals ), dats, dec(
len, decimals ), fltp, int1, int2, int4, lang, numc( len ), quan(
len, decimals ), tims, unit( len )

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 114
Predefined Functions
COALESCE Function

• COALESCE( arg1, arg2 ) - returns the value of AbapCatalog.sqlViewName: 'S4HCDS_SEL_VD13'


the argument arg1 (if this is not the null value); define view S4hcds_sel_v13 as select from scustom as c
otherwise it returns the value of the left outer join sbook as b on c.id = b.customid
argument arg2 {
c.name as Customer_Name,
• COALESCE can be used to set reasonable c.city as Customer_city,
coalesce( b.invoice , 'NULL') as invoice
default values for the NULL values
}
where b.bookid = '00002406'

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 115
Predefined Functions
SQL Functions

String functions:
@AbapCatalog.sqlViewName: 'S4HCDS_SEL_VD14'
• CONCAT(arg1, arg2)
define view s4hcds_sel_v14 as select from sbook
• LENGTH(arg) {
• LPAD/RPAD(arg, len, src) lpad ( connid, 13, '0' ) as conn_id, carrid,
ceil ( loccuram ) as amount_rounded_up
• REPLACE(arg1, arg2, arg3) }
• SUBSTRING(arg, pos, len)

Numeric functions:
• ABS(arg), CEIL(arg), FLOOR(arg)
• DIV(arg1, arg2), DIVISION(arg1, arg2, dec)
• MOD(arg1, arg2), ROUND(arg, pos)

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 116
Predefined Functions
Special Functions

 Delivered by SAP and not provided as native


@AbapCatalog.sqlViewName: 'S4HCDS_SEL_VD15'
functions on every database platform
define view s4hcds_sel_v15 as select from sbook
 Conversion functions {
 CURRENCY_CONVERSION( p1 => a1, … ) bookid,
unit_conversion (
 UNIT_CONVERSION( p1 => a1, ... )
quantity => luggweight,
 DECIMAL_SHIFT( p1 => a1, ... )
source_unit => wunit,
 Date functions target_unit => cast( 'G' as abap.unit ) ) as `
 DATS_IS_VALID
weight_in_grams
}
 DATS_DAYS_BETWEEN
 DATS_ADD_DAYS
 DATS_ADD_MONTH

 Time function: TIMS_IS_VALID


 Named Parameters
 An actual parameter a1 has to be bound via the “=>” operator
 Some parameters are optional
© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 117
Example

@AbapCatalog.sqlViewName: 'S4HCDS_FUNC_D1'
@ClientDependent: true
define view S4hcds_Func_Demo as select from sbook
{
CONCAT( carrid, connid ) as flightno,
fldate, bookid,
CONCAT( CONCAT( SUBSTRING(order_date,5,2), '-'),
SUBSTRING(order_date,1,4) ) as ordermonth,

case smoker
when 'X' then cast(loccuram as abap.fltp)* 1.03
else cast(loccuram as abap.fltp) * 0.98
end as adjusted_amount,

currency_conversion(
amount => loccuram,
source_currency => loccurkey,
target_currency => cast('EUR' as abap.cuky(5)),
exchange_rate_date => order_date ) as euro_amount
}

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 118
Exercise 05: Enhance the CDS view with Expressions

In this exercise you will:


 Use CASE expression to define the column more descriptive
 Use CAST expression in floating point calculation
 Use CONCAT function to combine 2 strings
 Use currency_conversion special function to convert the currency
 See Student Manual, Exercise 5 Tasks 1-5

Time: 15 min

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 120
Unit 3 – Core Data Services: SQL Features

Lesson 2 – Aggregate Expressions


Aggregate Expressions

 Aggregate Functions
 MAX
 MIN
 AVG
 SUM
 COUNT

 Can be used as elements with alternate name using AS in the projection list
 Require a GROUP BY clause when aggregate functions are used along with other elements in the projection
list

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 124
Aggregate Functions
COUNT

 You can calculate the number of rows in the result set @AbapCatalog.sqlViewName:'S4HCDS_SEL_VD16'
using COUNT . define view s4hcds_sel_v16 as
Rows containing only NULL values are included. select from sbook
{
 How many Records for booked flights with carrid: LH and count( * ) as booked_flights
}
connid : 0400
where carrid = 'LH' and connid = '0400'

 You can calculate the number of different NOT-NULL- ----


values of a certain column. {
 You can use only a single column as parameter for COUNT count( distinct planetype ) as planes
DISTINCT. }
----
NULL values are not included.

How many different entries of Plane Types?

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 125
Aggregate Functions
MIN, MAX, SUM

 You can calculate the minimum or maximum value @AbapCatalog.sqlViewName:'S4HCDS_SEL_VD17'


in a column. define view s4hcds_sel_v17 as select from sflight
{
 What is the price range of the flights? min( price ) as Min_Price,
max( price ) as Max_Price,
sum( price) as Total_Price
 You can calculate the number of values within a }
single column. where carrid = 'AA' and connid = '0017'
 NULL values are not included.

 You can only use a single column as parameter of


SUM.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 126
Aggregate Expressions
Group By Clause

 A table can be divided into (disjoint) groups of rows


@AbapCatalog.sqlViewName:'S4HCDS_SEL_VD18'
 A group is represented in the query result by a single row define view s4hcds_sel_v18 as select from sflight
 Aggregate expressions will be evaluated separately for {
each group planetype,
 Columns outside of aggregate functions must be listed in count( * ) as Count_flights
}
GROUP BY clause
where planetype = 'A340-600' or
planetype = 'A319-100'
 What is the number of flights per planetype? group by planetype

 The WHERE condition is evaluated before the rows are


combined using GROUP BY.

 What is the number of flights per plane type?


 Only plane type with number A340-600 or A319-100
included into the result set.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 127
Aggregate Expressions
Having Condition

 HAVING condition is evaluated after the group by


@AbapCatalog.sqlViewName: 'S4HCDS_SEL_VD19'
clause is evaluated define view s4hcds_sel_v19 as select from sflight
 HAVING condition can only be specified together {
with GROUP BY carrid,
fldate,
 Aggregate expressions can be specified in the count(*) as flight_count
HAVING condition }
group by carrid, fldate
having count(*) > 2

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 128
DEMO
Aggregation

@AbapCatalog.sqlViewName:‘S4HCDS_CUSTAGGR'
@ClientDependent: true
@EndUserText.label: 'Customer With Aggregation Of Miles'
define view s4hcds_Customer_Aggregation
as select from scustom as c
inner join sbook as b on c.id = b.customid
inner join s4hcds_Connection5_Functions as f on b.carrid = f.carrid
and b.connid = f.connid
{
key c.id as id,
c.name,
c.street,
c.city,
c.country,
sum(f.miles) as miles
}
group by c.id, c.name, c.street, c.city, c.country

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 129
Exercise 06: CDS view with Aggregate Expressions

In this exercise you will:


 Use COUNT aggregation function to find the total number of bookings
 Use MIN and MAX functions to find the minimum and maximum booking amount
 Use HAVING condition to restrict the result groups
 See Student Manual, Exercise 6 Tasks 1-4

Time: 15 min

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 130
Unit 3 – Core Data Services: SQL Features

Lesson 3 – Joins and Unions


Access to multiple tables

For read access to multiple database tables / views the following options are available:
 Combination of several tables (JOIN)
o INNER JOIN vs. OUTER JOIN
 Combination of results from several sub-queries (UNION)
o UNION ALL vs. UNION

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 134
INNER JOIN

One row of the left table and one row of the right table are always joined to a common result row - provided that
the JOIN condition is fulfilled.
 JOIN Condition: L.X = R.Y

L … X … … R … Y … …
… 1 … … … 3 … …
… 2 … … … 4 … …
… 3 … … … 5 … …
… 4 … … … 6 … …
… 5 … … … 7 … …

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 135
OUTER JOIN

The OUTER JOIN has three sub types:


 LEFT OUTER JOIN
 RIGHT OUTER JOIN
 FULL OUTER JOIN

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 136
LEFT OUTER JOIN

 One row of a table and one row of another table are always connected to a common result row - provided that
the JOIN condition is fulfilled.
 In addition, rows of the left table without matching row in the right table are copied to the query result. The
missing values ​(from the right table) are filled with NULL values.

L … X … … NULL NULL NULL NULL

… 1 … …
R … Y … …
… 2 … …
… 3 … …
… 3 … …
… 4 … …
… 4 … …
… 5 … …
… 5 … …
… 6 … …
… 7 … …

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 137
RIGHT OUTER JOIN

 One row of a table and one row of another table are always connected to a common result row - provided that
the JOIN condition is fulfilled.
 In addition, rows of the right table without matching row in the left table are copied to the query result. The
missing values ​(from the left table) are filled with NULL values.

L … X … …
… 1 … …
R … Y … …
… 2 … …
… 3 … …
… 3 … …
… 4 … …
… 4 … …
… 5 … …
… 5 … …
… 6 … …
NULL NULL NULL NULL … 7 … …

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 138
FULL OUTER JOIN

 One row of a table and one row of another table are always connected to a common result row - provided that
the JOIN condition is fulfilled.
 In addition, rows of both tables without matching records are copied to the query result. The missing
values ​(from the other table) are filled with NULL values.

L … X … … NULL NULL NULL NULL

… 1 … …
R … Y … …
… 2 … …
… 3 … …
… 3 … …
… 4 … …
… 4 … …
… 5 … …
… 5 … …
… 6 … …
NULL NULL NULL NULL … 7 … …

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 139
Supported joins in CDS views

Supported Join Types:


1. Inner Join
2. Left Outer Join
3. Right Outer Join
• Complex Join operations using ( … ) are supported
• Arbitrary On-Conditions: >, >=, <, <=, Like, between, and, or, not

Inner Join: Output list of customer and Left Outer Join: Output list of all customer
booking details for booking id = 2406 details with booking id = 2406.
@AbapCatalog.sqlViewName:'S4HCDS_JOIN_V01' @AbapCatalog.sqlViewName: ‘S4HCDS_LJOIN_01’
define view s4hcds_join_v1 as define view s4hcds_ljoin_demo1 as
select from sbook as b select from scustom as c
inner join spfli as p on p.carrid = b.carrid left outer join sbook as b on c.id = b.customid
and p.connid = b.connid {
inner join scustom as c on c.id = b.customid c.name as Customer_Name,
{ c.city as Customer_city
b.customid, c.name, }
b.fldate, p.cityfrom, p.cityto where b.bookid = '00002406'
}
where b.bookid = '00002406'
© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 140
Complex Joins – Example CDS view

@AbapCatalog.sqlViewName: 's4hcds_conn2join'
@ClientDependent: true
define view s4hcds_Connection2_Join
as select from spfli as c
inner join scarr as a on c.carrid = a.carrid
inner join sairport as af on c.airpfrom = af.id
inner join sairport as at on c.airpto = at.id
{
key c.carrid,
key c.connid,
a.carrname,
a.currcode as currency,
c.cityfrom, c.cityto, c.airpfrom,
af.name as airpfrom_name,
c.airpto,
at.name as airpto_name,
c.fltime, c.distance, c.distid
} where c.fltype <> 'X' //exclude charter flights

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 141
CDS Views
UNION [ALL] , UNION

• You can combine the result tables of multiple queries using UNION [ALL].
The individual results tables must have the same number of columns.
The corresponding result columns must have compatible data types.
 If no name list specified, the column names of the result sets must match

 UNION - Eliminate duplicates but it is slower


@AbapCatalog.sqlViewName: 'S4HCDS_UNION_01'
 UNION ALL – Includes duplicates define view s4hcds_union_demo1 as
select distinct from spfli
{
Example: carrid as CarrierID
 Select carrier ids of flights flying from } where cityfrom ='FRANKFURT'

city = Frankfurt and union all


have counter at Frankfurt airport select distinct from scounter
{
carrid as CarrierID
} where airport = 'FRA'

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 142
DEMO
Left Outer Join

@AbapCatalog.sqlViewName: 'S4HCDS_AGCYREV'
define view s4hcds_agency_with_Revenue as
select from stravelag as a
left outer join s4hcds_booking5_Functions as b on a.agencynum = b.agencynum
{
key a.agencynum as id,
a. name,
a. street,
a. city,
a. country,
sum(b.amount) as amount,
b.currency
}
group by a.agencynum, a.name, a.street, a.city, a.country, b.currency

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 143
Exercise 07: CDS view with Inner Join

In this exercise you will:


 Use INNER Join to display the flight booking information with the customer details.
 See Student Manual, Exercise 7 Tasks 1-2

Time: 10 min

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 144
Exercise 08: CDS view with Left Outer Join

In this exercise you will:


 Use LEFT OUTER Join to display the all the customer information with their total booking
amount.
 See Student Manual, Exercise 8 Tasks 1-2

Time: 10 min

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 145
Unit 4 – Advanced Concepts in CDS
Unit 4 – Advanced Concepts in CDS

Lesson 1 – Associations
CDS Associations – The Concept

Associations define relationships between entities in @AbapCatalog.sqlViewName: 'S4HCDS_ASSOC_D1'


the data model define view s4hcds_assoc_demo1
as select from spfli
Association definition contains association [1..1] to scarr as _scarr
 Target entity with optional alias (Recommended to start on spfli.carrid = _scarr.carrid
with _)
{
 Cardinality[min .. max] (optional) key spfli.carrid as id,
 ON condition represents JOIN condition
 easy to refactor // Path expression
Consumption of Association key _scarr.carrname as carrier,
 From
 Projection list key spfli.connid as flight,
 Aggregations spfli.cityfrom as departure,
spfli.cityto as destination
 WHERE, GROUP BY and HAVING clauses
}
Path Expressions Support
 Simplified consumption both in CDS view and Open SQL
Filter Expressions Support

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 151
Association Types

Ad Hoc Associations @AbapCatalog.sqlViewName: 'S4HCDS_ASSOC_D2'


define view S4hcds_Assoc_Demo2 as
 Association defined and used in the same CDS select from spfli
view  Association consumption constitutes a association [1..1] to scarr as _scarr
JOIN (Left Outer Join) on $projection.carrid = _scarr.carrid
{
Exposed Association key _scarr.carrname,
key spfli.connid,
 Association can be defined and exposed as part
spfli.cityfrom,
of the public signature of the view. spfli.cityto,
 Prerequisite: All columns of the view used in the
Join-Condition have to be exposed as well, in this // ad hoc association
example carrid _scarr.currcode,
 Consumption: From another CDS view or from // field used in the ON condition
Open SQL // Prerequisite for exposed association:
 Exposure does not automatically lead to a spfli.carrid,
JOIN // exposed association
“JOINs on demand” _scarr
}

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 152
Using Exposed Associations In CDS Views

Use exposed associations In data preview

In other CDS views


 Use fields of associated entity as needed using define view S4hcds_Assoc_Demo2b as
path expression select from S4hcds_Assoc_Demo2
 Leads to “JOIN on demand” {
_scarr.carrid
 CDS views can be defined for re-use }

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 153
Consuming Associations In Open SQL

Support for path expressions introduced in Open define view S4hcds_Assoc_Demo2 as select from spfli
SQL with ABAP 7.5 association[1..1] to scarr as _scarr
on $projection.carrid = _scarr.carrid
 To allow consuming associations in CDS entities
{
 Simple path expressions supported, cityfrom, cityto,
without filter expressions spfli.carrid,
 Association name prefixed with backslash \ // Exposed association:
_scarr
 Supported in all clauses, e.g. field list, }
where, order by, grouping, having …
SELECT FROM S4hcds_Assoc_Demo2
FIELDS cityfrom, cityto,
\_scarr-carrid as carrid,
\_scarr-carrname as carrname,
\_scarr-currcode as currcode
WHERE \_scarr-currcode IN ( ‘USD', ‘EUR' )
ORDER BY \_scarr-currcode INTO TABLE
@data(lt_customer).

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 154
Filtered Associations

Filtered Association define view S4hcds_Para_Demo2 as


select from scustom as customer
Associations can be enhanced by adding a association[0..*] to sbook as _bookings
supplementary filter on customer.id = _bookings.customid
{ customer.id,
 Define association of cardinality “to-N”
customer.name,
// Exposed Association with filter
 Use filter expressions in square brackets _bookings[ class = 'C' ] as _business_flights,
// Exposed Association without filter
_bookings }

define view S4hcds_Para_Demo3 as


select from S4hcds_Para_Demo2
{ id,
name,
// Path expressions with filter condition and 1:
 Usage of attribute 1:
_bookings[1: fldate = '20150101'].carrid
(Declaration of monovalency) as ny_booking_carrid,
_bookings[1: fldate = '20150101'].connid
as ny_booking_connid
}
© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 155
CDS Associations – Translation into Joins

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 156
CDS Associations: Advantages

Why would you use associations?


 Easy model consumption
– Path expressions
– Filter expressions
 Small(er) re-use views
 “JOINs on demand”:
JOINs are only generated if the
corresponding association is consumed

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 157
Exercise 9: CDS View with Association

In this exercise you will:


 Use association to define relationship with two tables
 Perform aggregations on the fields from the association target table
 Expose an association to consume from outside
 Consume the exposed association using path expression in Open SQL
 See Student Manual, Exercise 9 Tasks 1-5

Time: 10 min

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 158
Lesson 1: Associations
Summary

You should now be able to:


• Use Associations in CDS views
• Consume CDS associations in Open SQL using path expressions

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 159
Unit 4 – Advanced Concepts in CDS

Lesson 2 – Input Parameters


CDS Views with Input Parameters

CDS Views with Input Parameters @AbapCatalog.sqlViewName: 'S4HCDS_PARA_D1'


define view S4hcds_Para_Demo
 Comma-separated list of scalar input with parameters p_distance_l:S_DISTANCE,
parameters with type p_distance_o:S_DISTANCE,
 Parameter types: predefined or data element p_unit:S_DISTID
as select from spfli
 Parameter can be used in {
– Projection list as element key carrid,
key connid,
– ON conditions of JOINs
cityfrom,
– Expressions in WHERE or HAVING clauses cityto,
– Operand directly after CASE distance,
distid
– Operand of an arithmetic expressions
}
 Parameters can be accessed by where distid = :p_unit
:<param_name> or and distance between :p_distance_l
$parameters.<param_name> and :p_distance_o

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 162
Environment Annotation

Used in CDS views to associate input @AbapCatalog.sqlViewName: 'S4HCDS_PARA_D5'


parameters with ABAP system fields @ClientDependent: false
define view S4hcds_Para_Demo5
 Environment.systemField: Annotation as system with parameters
fields for pass by parameter using SELECT in @Environment.systemField : #CLIENT
Open SQL. p_mandt : syst_mandt,
Paramater annoted with defaults to value of p_carrid : S_CARR_ID
as select from sflight {
#CLIENT sy-mandt *
#SYSTEM_DATE sy-datum } where mandt = :p_mandt and carrid =
#SYSTEM_TIME sy-uzeit $parameters.p_carrid

#SYSTEM_LANGUAGE sy-langu
#USER sy-uname

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 163
Consumption of CDS view with Parameter in Open SQL

Open SQL
SELECT * from S4hcds_Para_Demo5( p_carrid = 'LH' ) into table @data(lt_flight).

NOTE
If the CDS entity is used as a data source of a SELECT statement in Open SQL, this assignment has the
following consequences:
– No explicit actual parameter can be assigned to an input parameter to which the system field sy-mandt was
assigned using #CLIENT. Open SQL always passes (implicitly) the value of sy-mandt
– An explicit actual parameter does not need to be be assigned to an input parameter assigned a different
system field using #SYSTEM_.... If no explicit actual parameter is specified, Open SQL passes the nominal
value of the assigned system field implicitly.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 164
Session Variables

• Global variables of the current database that @AbapCatalog.sqlViewName: 'S4HCDS_SVAR_D1'


contain information about the current context define view S4hcds_Session_Variables_Demo
as select from sbook
• Available Session Variables: {
$Session.SYSTEM_LANGUAGE, customid,
$Session.USER $session.user as system_user,
$Session.CLIENT $session.client as system_client,
• Global variables are set to values when the CDS $session.system_language as system_language
}
view is accessed using Open SQL
• Session variables can be used in the projection
list of the CDS view
• Session variables can also be passed as input
parameters to another CDS view

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 165
Exercise 10: CDS View with Input Parameters

In this exercise you will:


 Create a CDS view with Input parameters
 Assign the input parameter to System field using Environment Annotation
 Use the input parameter in the filter path expression
 Write an ABAP program to consume the CDS view with parameter using Open SQL
 See Student Manual, Exercise 10 Tasks 1-5

Time: 15 min

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 166
Unit 4 – Advanced Concepts in CDS

Lesson 3 – Extensibility
CDS Views - Extensions

Enhance CDS Views with @AbapCatalog.sqlViewAppendName: 'S4HCDS_EXT_V34'


• Additional fields extend view s4hcds_sel_sf33
with s4hcds_ext_sf34
• Arithmetic & CASE expressions {
• Literals concat ( airline, flightnumber) as flightno,
case reserved
when 'X' then 'Reserved'
Annotation else 'Booked'
AbapCatalog.sqlViewAppendName }
end as status

- Generated Append view in the dictionary

Extension is stored and transported in separate DDL source

The following CDS views cannot currently be enhanced


 Views with an explicit name list
 CDS view enhancements cannot themselves be enhanced

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 170
$extension – Include the base table extensions

The ABAP Dictionary enhancement concept is also supported @AbapCatalog.sqlViewName: 'S4HCDS_SEL_V37A'


in ABAP CDS entities. define view s4h_cds_sf37a as
select from spfli
{
By using $EXTENSION.* in the select list, all fields that are key carrid,
added as enhancements to the underlying database table or key connid,
classical DDIC view are automatically added to the CDS entity. cityfrom,
cityto,
Here the fields added to the database table spfli, will $extension.*
automatically be added to the view entity }

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 171
Core Data Services: View Definition
View-on-View Concept

View-on-View @AbapCatalog.sqlViewName: 'S4HCDS_SEL_V32'


 View can have other views as data source @AbapCatalog.buffering.status: '#ACTIVE'
@AbapCatalog.buffering.type: '#SINGLE'
 No restriction on the number of layers
@ClientDependent:'true' //default
@AbapCatalog.sqlViewName: 'S4HCDS_SEL_V33' define view s4hcds_sel_sf32 as
define view s4hcds_sel_sf33 as select from sbook
select from s4hcds_sel_sf32 as v {
inner join scustom as c carrid as airline,
on v.customer = c.id connid as flightnumber,
and v.customer = '00002406' fldate as flightdate,
{ bookid as id,
key v.airline, customid as customer,
key v.flightnumber, @Semantics.amount.currencyCode:‘LOCCURKEY'
c.name, loccuram as amount,
c.city @Semantics.currencyCode
} loccurkey as currency_code
}

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 172
Data modeling with views

View on View View on View View on View View on View


V1 V2 V3 V4

Association
Basic View Basic View
B1 B2

Tables Tables Tables


T1 T2 T3

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 173
Hierarchy of views and extension support

• Hierarchical view-on-view concept


Consumer Consumer Consumer Extensions
• Optimized result-sets with C1 C2 C3
minimum data transfer
• Append additional columns,
arithmetic expressions or literals to
result set View on View View on View &
V1 V2

Basic View
B1

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 174
Exercise 11: Extend CDS Views

In this exercise you will:


 Extend an existing CDS view to add additional fields to the projection list
 See Student Manual, Exercise 11 Tasks 1-2

Time: 10 min

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 175
Unit 4 – Advanced Concepts in CDS
Lesson 4: Data Control Language (DCL)
Do Authorization Checks Conflict With Code-to-Data?

Classic AUTHORITY-CHECKS on
SELECT FROM S4HCDS_FlightBooking_NoDCL
Instance Level FIELDS carrid, connid, SUM( loccuram ), currcode,
 Filter DB result using checks in ABAP? \_customer-postcode, \_customer-city,
 Benefit of Code-to-Data approach partly lost \_customer-street
 Each access to the data has to be checked WHERE custtype = 'B' AND \_customer-country = 'US'
explicitly GROUP BY carrid, connid, currcode, \customer-postcode, …
INTO TABLE @lt_customer.

LOOP AT lt_customer INTO ls_customer.


AUTHORITY-CHECK OBJECT 'S_CARRID'
ID 'CARRID' FIELD ls_customer-carrid
ID 'ACTVT' FIELD '03'. "Display
Code-to-Data
IF sy-subrc <> 0. "User not authorized to see current line
DELETE lt_customer INDEX sy-tabix.
ENDIF.
ENDLOOP.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 179
Data Control Language Overview

Classical approach DCL approach


• Declarative approach instead of coded

• Based on CDS modeling objects and PFCG PFCG


therefore part of the data-model <Code> <Code>
DCL
• Authorizations are also pushed down to DB
by extending the Open SQL SELECT
statement
SQL
& SQL

Authorization CDS
Check View

<Code> <Code>

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 180
Usage of Declarative DCL Authorizations – Example Scenario

Enable READ-access only to Flight bookings of airlines for which


Scenario the user is authorized (according to the PFCG authorization object)

define view S4HCDS_FlightBooking as select from sbook


{
carrid,
connid,
fldate,
bookid,
CDS-View ( to be authorized )
order_date,
loccuram,
loccurkey as currcode,
.. .
}

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 181
CDS DCL: Declare Authorizations And Push Checks To Database

Use CDS DCL to model authorizations @EndUserText.label:


based on CDS views 'Auto assigned mapping role for S4HCDS_FlightBooking'
@MappingRole: true
New type of ABAP Repository Object
define role S4HCDS_FlightBooking {
 Access Controls – DCL Source grant select
 Separate from related CDS view / DDL source on S4HCDS_FlightBooking

Based on Roles and Conditions where ( carrid ) =


 Each DCL source defines a role aspect pfcg_auth ( S_CARRID,
CARRID,
 Conditions = WHERE clause actvt = '03' );
}
 Declarative & Code-to-Data approach
SELECT FROM S4HCDS_FlightBooking
 Evaluated at run-time in database when Open SQL
FIELDS carrid, connid, …
/ SADL query accesses CDS entity
INTO TABLE @lt_customer.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 182
Literal And Aspect Conditions

Literal conditions
– Allows declaring completely new authorizations @EndUserText.label: 'Auto assigned mapping role for …'
define role <role name> {
– Can be combined with aspect conditions
grant select
on S4HCDS_FlightBooking
where
Aspect conditions – for aspect PFCG country = 'US'
 Allows reusing existing authorizations based on
or ( carrid ) = aspect pfcg_auth (
authorization objects and PFCG roles
S_CARRID, -- Authorization object
 Parameters: CARRID, -- Matched auth. object field
– LHS: list of view fields to be matched against ACTVT = '03' –- Fixed auth.object field
authorization object fields );
– RHS: classical authorization object and list of }
authorization object fields

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 183
Most Important Annotations For Access Control Objects

Annotations in DCL Sources @EndUserText.label: 'Auto assigned mapping role …'


 @EndUserText.label: Translatable short text of role @MappingRole: true
 @MappingRole:The role is assigned to all users
automatically regardless of the client. Only true supported define role <role name> { … }

Annotations in DDL Sources


 @AccessControl.authorizationCheck: Defines access
control when Open SQL is used to access the CDS view: …
– #CHECK: Perform access control, syntax check warning @AccessControl.authorizationCheck: #NOT_REQUIRED
if no role is assigned …
– #NOT_REQUIRED: Like #CHECK, but suppress syntax
check warning define view <view name> as …
– #NOT_ALLOWED: Perform no access control, syntax
check warning if DCL source if assigned

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 184
Runtime Behavior

During runtime the SELECT statement for a CDS view will automatically be enhanced with the authorization filter.

SELECT … FROM … INTO …


WHERE …
AND <Authorization Filter Condition>

DCL DDL
Authorization Object ABAP Data Base CDS View
Interface
View fields

User Profile

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 185
Important Notes About Access Controls

Access Controls vs. classic authorization checks


 Use classic authorization checks when application is started
 Use CDS Access Controls for instance-based authorization checks

Access Controls only considered on direct CDS view access


 When explicilty using CDS view in Open SQL statement or SADL
 Ignored when queried indirectly via other CDS views etc.

Access Controls evaluated on the Database


 ABAP layer cannot distinguish between non-existing data and data not
read due to lack of permissions

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 186
Naming Conventions and Guidelines for DCL Documents

Naming Conventions
 The DCL source name shall be identical to the CDS DDL source name.
 The DCL source description shall start with Auto assigned mapping role for
and continue with the name of the CDS view name (Camel Case).
 The name of the role inside the DCL source shall be identical to the
CDS view name (Camel Case).
 The EndUserText.label shall start with Auto assigned mapping role for
and continue with the name of the CDS view name (Camel Case).

Additional Guidelines
 The DCL document has to include the annotation @MappingRole: true.
 Only one mapping role definition per DCL source document is allowed.
 Other aspects than pfcg_auth shall not be used.
 Only one mapping role per CDS view is allowed.
 A DCL source document shall always include the mapping
for one CDS view exclusively.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 187
Avoiding Risk of Privilege Escalation

If a user could influence the value of an authorization relevant CDS View


attribute of a view with a user provided parameter value there
will be the risk of privilege escalation.

A user has only to execute the view Z_ViewWithParameter


with the value XYZ for the parameter p_param to get full
access to table besg.

 The where condition of the DCL mapping role for a CDS


view shall never contain a field of the view which directly
DCL document X
reflects a parameter or is calculated from a parameter.

 Delegation of instance based checks to an associated view


is only allowed via associations where the on condition of Users authorization
the association does not include any attribute of the
association target view which is directly or indirectly
depending from a parameter of the association target view.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 188
Testing for DCL
Transaction SACM

Select variant 16 for


test with open SQL

Test with your logged-


in user or execute
with different user.

Enter the name of the


CDS view.

Enter the name value


pairs for the
parameters used in
the view.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 189
Testing for DCL
Result in Transaction SACM

Used DCL role

Used authorizations
of the user

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 190
Demo
Access Control
using CDS DCL

© 2015 SAP SE or an SAP affiliate company. All rights reserved.


Unit 4 – Advanced Concepts in CDS
Lesson 5: Odata Consumption of CDS
What is the OData protocol?

The Open Data Protocol (OData) enables the creation and


consumption of REST APIs, which allow resources to be
published and edited by Web clients using simple HTTP
messages.

It is an open standard, by the OASIS consortium.

Detailed reference information at http://www.odata.org/

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 195
CDS OData Exposure - Architecture

 Generating service artifacts from CDS


View
Annotation: @OData.publish: true
 Activating OData service in the SAP
Gateway hub using transaction
 Prerequisites
 At lease one key element is
necessary in the CDS view
 CDS view entity name length should
not exceed 26 characters

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 196
SAP Gateway - OData
Consumption of ABAP Artifacts & Implementations

CDS View Consumption


 Direct mapping of CDS views to an entity set
in an OData service
 Completely modeled approach; no coding
needed for read operations

ABAP
 OData service can be easily bound to an
SAPUI5 control
Implementation using Open SQL and
AMDP in the generated Classes

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 197
OData
Demo example
@OData.publish: true @AbapCatalog.sqlViewName: 'CDS_VIEW_SAMPLE_EXP'
@OData.publish: true

This annotation is added to the CDS view definition in define view s4hcds_odata_demo as
order to generate all artifacts that are required for select from sbook
OData service exposure.
{ key sbook.carrid,

key sbook.connid,

sbook.fldate,

sbook.loccuram,

sbook.loccurkey

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 198
Lesson 5: OData Exposure
Summary

You should now be able to:


• Expose the CDS view as OData Service

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 199
Unit 5 – New Features in Open SQL

Lesson 1 – New Features in Open SQL


Open SQL Definition
What Is Open SQL?

Database SQL-like
abstraction layer syntax

Open SQL
Common NOT the subset of
semantics SQL, common to all
for SQL databases

Open SQL is the only DB abstraction layer that defines a common


semantic for all SAP-supported databases!

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 204
What is Open SQL? Why Enhance It?

Open SQL is the only DB abstraction layer that defines a common semantic for all SAP supported databases
Limitations in ABAP < 7.4 SP05 Minimize the limitations

SQL-92 Standard
Standardized Open SQL
(≥ ABAP 7.5)

Enhanced Open SQL


(ABAP 7.4)

Open SQL
(before ABAP 7.4)

Use of CDS associations

Support more standard SQL features in Open SQL – for SAP HANA and other database platforms

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 205
What‘s New in Open SQL in ABAP 7.4?

New Open SQL syntax SELECT carrid, connid, fldate,


 ABAP variables (host variables) escaped with “@” bookid, customid
 Comma-separated column list FROM sbook
INTO TABLE @lt_bookings
 Arithmetic expressions using +, - ,*, /, DIV, MOD, ABS,
WHERE customid = @lv_customer.
FLOOR,CEIL
 Common semantics SELECT
 String concatenation carrid, connid, fldate, bookid, customid,
 CAST CASE smoker
 SQL CASE, COALESCE WHEN 'X' THEN
FLOOR( loccuram * @lc_smoker_fee )
ELSE CEIL( loccuram * @lc_nonsm_disc )
Implication END AS adjusted_amount,
CAST( loccuram AS FLTP ) / CAST( 2 AS FLTP )
AS half,
 Strict mode: Nearly all former warnings
loccurkey
transform into syntax errors.
FROM sbook
INTO TABLE @lt_bookings2
WHERE customid = @lv_customer.
© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 206
Further Limitations Removed

 RIGHT OUTER JOIN now supported

 Use brackets in JOIN expressions


– To override implicit left-bracketing

 ON conditions extended:
– No field of the right table required in ON condition Table 1 Table 2 Table 3 Table 4
– No longer limited to Equi-Joins
– Fields of the right table usable in WHERE clause of LEFT OUTER JOIN
– Implicit client handling

 Maximum number of tables in JOINs increased


= 50
 Maximum number of sub queries increased
= 50

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 207
New in Open SQL in ABAP 7.5: FROM First, FIELD, INTO Last

INTO clause at the end SELECT carrid, connid, fldate, bookid, customid
 For consistency with UNION syntax FROM sbook
 Additions such as UP TO … ROWS after INTO WHERE customid = @lv_customer
INTO TABLE @lt_bookings UP TO 10 ROWS.

Key word FIELDS SELECT FROM sbook


 Exchange order of field list and FROM clause FIELDS carrid, connid, fldate,
 FROM clause first results in code-completion friendly bookid, customid
syntax WHERE customid = @lv_customer
INTO TABLE @lt_bookings UP TO 10 ROWS.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 208
New in Open SQL in ABAP 7.5: UNION / UNION ALL

Support for UNION and UNION ALL SELECT FROM sbook


 UNION – Distinct, no duplicates FIELDS carrid, connid, fldate, bookid, customid,
FLOOR( loccuram * @lc_smoker_fee )
 UNION ALL – Duplicates included CAST( loccuram AS FLTP ) /
 Only explicit field lists allowed – no SELECT * CAST( 2 AS FLTP ),
 Types of linked columns have to compatible („The loccurkey
larger type wins“) WHERE customid = @lv_customer
 INTO clause must be at the end of the statement AND smoker = 'X'
UNION ALL
SELECT FROM sbook
FIELDS carrid, connid, fldate, bookid, customid,
CEIL( loccuram * @lc_nonsm_disc )
CAST( loccuram AS FLTP ) /
CAST( 2 AS FLTP ),
loccurkey
WHERE customid = @lv_customer
AND smoker = ' '
INTO TABLE @lt_bookings2.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 209
Usage of CDS Association using Path Expressions

 Support of „simple“ path expressions (without SELECT FROM S4hcds_Assoc_Demo2


filter expressions) FIELDS cityfrom, cityto,
 An association has to be prefixed by a \_scarr-carrid AS carrid,
backslash \_scarr-carrname AS carrname,
(Better readabillity of the code) \_scarr-currcode AS currcode
 Associations can be used in all clauses, i.e. WHERE \_scarr-currcode
field list, where, order by , group by, having and IN ('USD' , 'EUR' )
from clauses ORDER BY \_scarr-currcode
INTO TABLE @data(lt_customer).

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 210
New Features in Open SQL
ABAP expressions
 ABAP expressions are set into @( )
SELECT FROM sbook
 ABAP expressions are allowed at all input FIELDS carrid, connid, fldate, bookid,
positions customid
 ABAP expressions are evaluated before the WHERE customid =
Open SQL statement is executed @( lo_helper->get_customer_id( 'SAP AG' ) )
INTO TABLE @DATA(lt_booking)
UP TO @( lo_helper->get_max_row_count( ) ) ROWS.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 211
New Features in Open SQL
(Partially) dynamic ON clauses
 Part conditions can be dynamic like in the
WHERE resp. HAVING clause SELECT s~carrid, s~carrname, p~connid
FROM scarr AS s LEFT OUTER JOIN spfli AS p ON
(dynamic_condition) AND p~cityfrom = p_cityfrom
INTO TABLE @data(lt_result).

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 212
Global Temporary Tables (GTT)

 Global Temporary Tables are defined in the


ABAP Dictionary (SE11)
 Contents is only valid inside a database
transaction, content deleted before COMMIT
 Implicit COMMITs (e.g. RFC calls) lead to short
dumps
 Behave like normal tables in Open SQL and CDS
 Can be used to store intermediate results for
subsequent database calls

SELECT FROM sbook_temp


FIELDS class, SUM( loccuram ) AS spend
GROUP BY class
INTO TABLE @DATA(lt_spend_by_class).

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 213
New Features in Open SQL
INSERT performed in Bulk on Database
 INSERT FROM SELECT copies the result set of a INSERT sbook_temp
SELECT statement into the target table FROM ( SELECT FROM sbook
 Result set is not transferred to the application FIELDS carrid, connid, fldate, bookid,
server customid, custtype, smoker,
 Execution is done completely in the database class, loccuram, loccurkey,
order_date
 Can be used to fill global temporary tables
WHERE ( cancelled <> 'X‘
OR cancelled IS NULL )
AND customid = @lv_customer
).

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 214
Further Information

• Open SQL Feature List (per Release)


https://wiki.wdf.sap.corp/wiki/pages/viewpage.action?pageId=1613868694

• Open SAP Course: ABAP Development for SAP HANA


https://open.sap.com/courses/a4h1

• ABAP Development Tools: http://adt.wdf.sap.corp:8080/

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 215
Exercise 12: New Features in Open SQL

In this exercise you will:


 Write an Open SQL query using the new Open SQL syntax
 Use a JOIN, the CASE expression and other expressions in Open SQL
 See Student Manual, Exercise 12 Tasks 1-2

Time: 15 min

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 216
Exercise 13: Global Temporary Tables

In this exercise you will:


 Use and extend the new INSERT …. FROM SELECT statement in Open SQL
 Analyze a Global Temporary Table and use it in Open SQL statements
 See Student Manual, Exercise 13 Tasks 1-3

Time: 15 min

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 217
Unit 6 – Virtual Data Model (VDM)
Lesson 1: VDM Motivation and Architecture
Unit 6 – Virtual Data Model (VDM)
Lesson 1: VDM Motivation and Architecture
What is the Virtual Data Model (VDM)?

VDM is a semantical model of the suite application data, technically expressed in the
language of ABAP CDS views. It is stable, extensible and available for reuse.

SalesOrder Customer
What is this??
VDM

CSK-KOSTL Virtual Data Model


VBAK-GBSTK SalesOrderItem Material • Understandable
• Semantically rich
• Comprehensive

80 000 Tables
(technical, cryptic, unrelated)

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 223
VDM Motivation and Architecture

Harmonized Consumption
 Analytics
 Fiori apps
 OData and openSQL interfaces

openSQL
Unique Semantic Model (VDM)
SalesOrder Customer
 Views and fields in business terminology
 Explicit relations
VDM

 Semantically enriched
SalesOrderItem Material  Ready to use

Application Data in Tables


 Cryptic table and field names
 Semantics and relations of tables feel
80 000 Tables like a secret science to the uninitiated

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 224
S/4HANA Runtime Architecture
Overview

VDM
Offers common data and
metadata access for
transactional, analytical,
search and other use
cases

Common data and metadata


access for transactional, analytical,
search and other use cases via
CDS based VDM

All analytics content of S4HANA


shall be based on CDS based VDM

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 225
CDS – The Technical Foundation of VDM

“Virtual”
– refers to the fact that the VDM semantic model
may deviate from the historically grown persistent model of
database tables to make it simpler and easier to
understand

CDS Characteristics
 SQL based
 Associations express view relations
 Annotations define additional metadata
 ABAP(any DB) & HANA natively

Semantically Rich Data Model


 Common, unified, harmonized meta model for all
frameworks
 Reusable by consumers and developers

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 226
CDS VDM Use Cases

The usage of ABAP CDS views following the VDM guidelines is mandatory for the following use cases:

• Any analytical content (e.g. queries, cubes etc. exposed via generic analytical tools like Lumira,
Design Studio)

• New transactional or analytical FIORI applications (following the S4HANA target architecture)

• Smart Business KPIs

• Fact sheets and object pages

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 227
Example: Virtual Data Model in OData and Fiori UI

Consistent, self-explanatory, business oriented


naming based on Global Term Catalog

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 228
Unit 6 – Virtual Data Model (VDM)
Lesson 2: VDM Layering
S/4HANA CDS-based Virtual Data Model (VDM)
View Types and Layers

Domain specific views


Consumption View  Analytics
 Search
Private Consumption View  Transactional applications etc. Analytical Query
Instance authorizations via DCL (Data Control Language)
Standardized Terms (Global Field Names etc.)
R R

Auxiliary/technical helper views


Compensation for missing CDS functionality
Interface View Not part of the public/external interface

Public, stable and reusable interface for any consumer


Composite View
Modeling based on business semantics
Instance authorizations via DCL (Data Control Language) Analytical View,
Private Composite View
Execution via ABAP Open SQL interface Dimension View
Standardized Terms (Global Field Names etc.)
R
R R

Derived from basic views


Redundant data
Basic View R

Extension Include View


Private Basic View Anchor for key user defined extension fields

Definition of core entities


Simple projection of DB table
Exposure of all business data
Fact View, Dimension
Normalized with controlled data redundancy View, Text View,
Basis for Save Draft Hierarchy View
Database Table
Extension Include
Suite database tables

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 232
VDM Annotations

@VDM.viewType
Admissible Values: #BASIC, #COMPOSITE, #CONSUMPTION, #EXTENSION

All CDS views shall be annotated explicitly with a VDM view type.

//Example:
@VDM.viewType: #BASIC
define view I_BillOfMaterial as select...

@VDM.private
Admissible Values: #blank (=true), true or false

Only private interface and consumption views need to be annotated explicitly.

Public views do not need to be annotated as such. //Example:


//Private View
@VDM.private:true // = @VDM.private
define view P_BillOfMaterial1 as select...

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 233
Data Category Annotations
@Analytics.dataCategory and @ObjectModel.dataCategory

Annotate the data category as follows:

 Plain transaction data as @Analytics.dataCategory: #FACT,

 Transaction data containing all relevant fields for data aggregation as


@Analytics.dataCategory: #CUBE,

 Business documents, configuration and master data including keys and attributes as
@Analytics.dataCategory: #DIMENSION,

 Language-dependent texts as @ObjectModel.dataCategory: #TEXT,

 Hierarchies as @ObjectModel.dataCategory: #HIERARCHY.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 234
Annotations to Interface views
Basic views

Consumption views
 @VDM.viewType set to #CONSUMPTION

Interface views
Composite views

Composite views
 @VDM.viewType set to #COMPOSITE
 @Analytics.dataCategory with values #CUBE,
#DIMENSION, #FACT, #TEXT, #HIERARCHY
 @VDM.businessObject (to be decided)

Basic views

Core Entities / Text Views / Hierarchy Views


Distinguished by
 @VDM.viewType set to #BASIC
 @Analytics.dataCategory with values
#DIMENSION, #FACT, #TEXT, #HIERARCHY
 @VDM.businessObject (to be decided)

Database tables

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 235
Annotations to Interface views
Composite and Consumption views

Consumption views
 @VDM.viewType set to #CONSUMPTION

Interface views
Composite views

Composite views
 @VDM.viewType set to #COMPOSITE
 @Analytics.dataCategory with values #CUBE,
#DIMENSION, #FACT, #TEXT, #HIERARCHY
 @VDM.businessObject (to be decided)

Basic views

Core Entities / Text Views / Hierarchy Views


Distinguished by
 @VDM.viewType set to #BASIC
 @Analytics.dataCategory with values
#DIMENSION, #FACT, #TEXT, #HIERARCHY
 @VDM.businessObject (to be decided)

Database tables

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 236
VDM CDS View Layering
Naming Conventions

VDM View Type Private CDS Name Prefix SQL Name Prefix Global Field Name Checks
#CONSUMPTION C_ C X
#CONSUMPTION X P_ P
#COMPOSITE I_ I X
#COMPOSITE X P_ P
#BASIC I_ I X
#BASIC X P_ P
#EXTENSION E_ E X

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 237
Naming Rules for Fields

Field Label

• Contains the full semantic name of the field / column

• Derived from the underlying data element of the field

• In exceptional cases defined by the annotation @EndUserText.label

Field Name

• Is a name from the Global Field Name Catalog

• New fieldnames are created according to the Naming Rules for Fields following the described process.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 238
Exercise 14: Virtual Data Model

In this exercise you will:


 Create Basic and Consumption views
 Use the VDM annotations to classify the VDM views
 See Student Manual, Exercise 14 Tasks 1-2

Time: 10 min

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 239
Lesson 2: VDM Layering
Summary

You should now be able to:


• Explain the different layers in VDM
• User the VDM specific annotations
• Follow the correct naming conventions for VDM views

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 240
Unit 6 – Virtual Data Model (VDM)
Lesson 3: Authorization for VDM
Lesson 3: Authorization for VDM
Learning Objectives

After completing this unit, you should be able to:


• Use DCL to authorize the VDM CDS views
• Use the Transaction SACM to test the authorization

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 245
Basic Principles

Access to data via the Virtual Data Model (VDM) with Core Data Services (CDS) in Suite is always controlled by a combination
of:

• Start authorization check of the consumption domain (e.g. Analytics, ODATA etc.)

• Instance based authorization for the data source CDS view.

Instance based authorizations are derived dynamically during runtime from the user’s PFCG authorizations as single point of
truth.

A modeled approach for the developer

• Keep the mapping between CDS view attributes and ABAP authorization objects out of code in a DCL.

No additional authorization concept to be maintained in S/4 HANA.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 246
Start authorization (functional access restriction)

All consumption domains (analytical query, OData service, search, transactional) have to be protected by an explicit start
authorization:

• For generic consumption domains like analytics or OData service the start authorization will be provided by the particular
framework.

It shall never be possible for an end-user to access any CDS view or database table directly with a tool (e.g. a generic data
browser) bypassing the start authorization check.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 247
Instance based authorization – Generic Consumption

ALL CDS views which are allowed as data sources for generic consumption domains (Analytics, ODATA) have be to protected
by a CDS DCL:

• All non-private CDS views enabled as data source for consumption via Analytical Engine (annotation
@Analytics.DataCategory: #DIMENSION, #CUBE or #FACT)

• All non-private CDS views enabled for Odata 1-to-1 exposure (annotation @OData.publish: true).

A CDS view has to include all authorization relevant attributes for defining the DCL in its projection list or in an associated view.

In other words: If a view is not protected by a DCL the annotations @OData.publish: true or @Analytics.DataCategory:
#DIMENSION, #CUBE or #FACT shall not be used.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 248
Instance based authorization – Exceptions

DCLs shall not be used for:

• Hierarchy node views (@Analytics.dataCategory: #HIERARCHY), analytical queries (@Analytics.query: true) and extension
include views (@VDM.viewType: #EXTENSION)

DCLs are not required for:

• Private Views (@VDM.private:true)

• Text Views (@Analytics.dataCategory: #TEXT)

• Views for generic consumption where an instance based access differentiation per user in not required from business
constraints. Example are views defining a list of allowed code values (e.g. unites of measure or list of allowed status codes).

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 249
Annotation @AccessControl.authorizationCheck 1/2

• All VDM CDS views have to include the annotation @AccessControl.authorizationCheck.

• If the annotation is not used at all in the DDL document a warning will occur when activating the CDS view in ABAP
development tools if no DCL role exists.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 250
Annotation @AccessControl.authorizationCheck 2/2

All CDS views have to be ‘classified’ if a DCL is required in SAP delivery, addable by customer or not allowed at all with the
annotation @AccessControl.authorizationCheck

• @AccessControl.authorizationCheck: #CHECK shall be used for CDS views requiring protection by a DCL role according the
authorization guideline and text views delivered with a DCL role.

• @AccessControl.authorizationCheck: #NOT_REQUIRED shall be used for VDM private views, text views delivered without a
DCL role and generically consumable views which do not require an instance based differentiation per user.

• @AccessControl.authorizationCheck: #NOT_ALLOWED shall be used for hierarchy node views, analytical queries and
extension include views.

A warning message will be shown during activation of the CDS view for:
• CDS Views without the annotation @AccessControl.authorizationCheck if no DCL role exists.
• CDS Views with the annotation @AccessControl.authorizationCheck: #CHECK if no DCL role exits.
• CDS Views with an association to a dictionary view.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 251
Instance based authorization – Coded Consumption

A coded consumption of a CDS view includes any ABAP code with a SELECT statement on the CDS View or any OData Service
consumption besides 1-to-1 exposure.

Recommended: Consumption of a CDS view with a DCL will automatically use the modelled instance based authorization. 
Architecture Guideline S/4 HANA [OMP-IAM-8]

Break out: Consumption of a CDS view without a DCL requires to implement a sufficient instance based authorization check like
accessing a table or the SQL view of a CDS view directly.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 252
VDM Authorization Summary
Consumption views
Analytics Search Data retrieval for transactional Application-specific views
start authorization start authorization applications start authorization
start authorization
Instance based authorization check by modeled DCL mapping role for all CDS views*
besides Analytical Queries (annotation @Analytics.query: true)

Interface views
Composite views
Instance based authorization check by modeled DCL mapping role Private views
for all CDS views* besides the hierarchy node views (annotation
@Analytics.dataCategory: #HIERARCHY and text views No authorization check
@Analytics.dataCategory: #TEXT

Basic views
Instance based authorization check by modeled DCL mapping role Private views
for all CDS views* besides the hierarchy node views (annotation
No authorization check
@Analytics.dataCategory: #HIERARCHY and text views
@Analytics.dataCategory: #TEXT

Database tables No authorization check

*With the exception where an instance based access differentiation per user in not required from business constraints.
© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 253
Example: All Authorization Relevant Attributes Included in the
Projection List

V_VBAK_AAT I_SalesOrder V_VBAK_VKO


AUART SalesOrder SPART
ACTVT (with value 03) VKORG
SalesOrderType
VTWEG
SalesOrganization
ACTVT (with value 03)
DistributionChannel
OrganizationDivision

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 254
Example: Delegation of Instance Based Checks to Associated Views
Important: Don’t use DCL with path expression for
performance critical CDS views.

A required instance based authorization check can be delegated to an associated view by using in the constrain condition
attributes of the associated view via path notation if the view itself does not contain in the projection list all authorization relevant
attributes.
@MappingRole: true
define role I_SalesOrderItem {
grant select on I_SalesOrderItem
where (_SalesOrder.SalesOrderType) =
aspect pfcg_auth (v_vbak_aat,
auart,
actvt = '03' )
and (_SalesOrder.Division,
_SalesOrder.SalesOrganization,
_SalesOrder.DistributionChannel) =
aspect pfcg_auth ( v_vbak_vko,
spart,
vkorg,
vtweg,
actvt = '03' );
}

Typical use case is sub nodes of a BO sharing the instance based restriction defined for the root node
where the sub nodes themselves do not contain the authorization relevant attributes.

Important:
1. Only path expressions using an association of cardinality to 1 and a CDS View as target data source shall be used in the
conditions of a DCL mapping role.
2. A path expression in a DCL mapping role using an association with a dictionary table or dictionary view as target data source
is not allowed.
© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 255
Delegation of Instance Based Checks with Parameters

Delegation of instance based checks to associated views with parameters require to pass in the constrain condition with path
notation an actual value for the parameter.

The following can be used as actual value for the parameter:

• Literals

• Parameters of the view protected by the DCL mapping role

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 256
Delegation of Instance Based Checks with Parameters
Literal as Actual Value

@EndUserText.label: 'Mapping role for ZI_Item'


@MappingRole: true
define role Zi_Item {
grant select on Zi_Item
where ( _header(P_Language:'E').HeaderAttribute1 ) =
aspect pfcg_auth (ZTEST1,
variant,
actvt = '03' );

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 257
Delegation of Instance Based Checks with Parameters
Forwarding Parameters

@EndUserText.label: 'Mapping role for ZI_Item'


@MappingRole: true
define role Zi_Item {
grant select on Zi_Item
where (
_header(P_Language:$parameters.P_Language).HeaderAttribute1 ) =
aspect pfcg_auth (ZTEST1,
variant,
actvt = '03' );

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 258
Lesson 3: Authorization for VDM
Summary

You should now be able to:


• Use DCL to authorize the VDM CDS views
• Use the transaction SACM to test the authorization

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 259
Unit 6 – Virtual Data Model (VDM)
Lesson 4: VDM ATC Checks
VDM CDS Development Guideline

In order to ensure consistency and homogeneity of


VDM CDS views in S/4HANA a comprehensive set
of rules has been compiled which is verified by ATC
checks known as
VDM CDS Development Guideline

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 262
VDM CDS ATC Checks

 All VDM ATC checks are based on the metadata captured in the source file of the CDS views.
 They are restricted to the CDS views using the view annotations @VDM...
 Additionally CDS view names and DDLS file names beginning with the reserved VDM prefixes 'I_', 'E_', 'P_' or 'C_' are
included in the check scope.
 The ATC checks are executed on active CDS views only.

 ATC Check-ID: POC_ANNOTA

In order to reasonably execute the checks, the annotations @VDM.viewType and @VDM.private have to be set
More details can be found here:
https://wiki.wdf.sap.corp/wiki/display/SuiteCDS/VDM+CDS+ATC+Checks

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 263
Lesson 4: VDM ATC Checks
Summary

You should now be able to:


• Explain ATC checks in VDM

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 264
Unit 6 – Virtual Data Model (VDM)
Lesson 5: SFLIGHT VDM Example
Focus of this Example

Use of CDS views in analytics


 Dimension views
 Fact and text views
 Cube views
 Outlook: query views

Use of associations for model building


 Foreign key associations
 Text associations

Important annotations of CDS views

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 266
Example based on SFLIGHT

Flight by
Airport
Query

Flight by Flight
Airport
Airport Connection

AircraftType Flight Airline Airline Text

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 267
Example based on SFLIGHT

D. ZU##_C_AVAILFLIGHTSQ Available
C. ZU##_C_AvailFlightsQ Flights
S. ZU##_CAVFLIGHTQ Query D. ZU##_I_FLIGHTCONNECTION D. ZU##_I_AIRPORT
C. ZU##_I_FlightConnection C. ZU##_I_Airport
S. ZU##_IFCONN S. ZU##_IAIRPORT

D. ZU##_I_FLIGHTBYAIRPORT
Flight
Flight by 0..1 Airport
C. ZU##_I_FlightByAirport Connection carrid
Airport SAIRPORT
S. ZU##_IFLIGHTA SPFLI airpfrom
airpto

AircraftType 0..1 Flight 0..1 Airline 0..1 Airline Text


SAPLANE planetype SFLIGHT carrid SCARR carrid SCARR

D. ZU##_I_AIRCRAFTTYPE D. ZU##_I_FLIGHT D. ZU##_I_AIRLINE D. ZU##_I_AIRLINETEXT


C. ZU##_I_AircraftType C. ZU##_I_Flight C. ZU##_I_Airline C. ZU##_I_AirlineText
S. ZU##_IAIRCRFTT S. ZU##_IFLIGHT S. ZU##_IAIRLINE S. ZU##_IAIRLINET

DDL Source
CDS View Name
SQL View Name
© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 268
Step by Step Creation of #BASIC Views

 Step-by-step guide to create your first CDS views I_Airline and I_AirlineText.

 Create DDL source in ABAP development tools

 Naming conventions for source, CDS view name, SQL view name

 Use of Ctrl+SPACE for efficient work

 Use of global field name suggestions

 End user label for a view

 Analytics data category #DIMENSION and ObjectModel data category #TEXT

 Semantics annotations for currency code, url and text

Association
© 2016 between the views
SAP SE or an SAP affiliate company. All rights reserved. Internal 269
Airline
@AbapCatalog.sqlViewName: ' S4HCDS_IAIRLINE' -- S4HCDS_ + I + AIRLINE; uppercase
@AccessControl.authorizationCheck: #NOT_REQUIRED -- authorization check via DCL not required
@Analytics.dataCategory: #DIMENSION
-- view is available as dimension view for analytics with analytics engine
@Analytics.dataExtraction.enabled: true
-- this view is a good candidate for extraction of data for a data warehouse
@EndUserText.label: 'Airline' -- label of the view for an end user, can be translated
@ObjectModel.representativeKey: 'Airline'
-- the (most significant) key field, anchor of foreign key associations pointing here
@VDM.viewType: #BASIC -- basic interface view of VDM (virtual data model)
define view S4hcds_I_Airline -- S4hcds_+ I_ + Airline; private prefix + VDM prefix + global term for core entity
-- name should be kept identical with DDL name
as select from scarr -- data source, here a table
association [0..1] to S4hcds_I_Airlinetext as _Text on $projection.Airline = _Text.Airline
-- naming convention for associations: _xyz
-- $projection recommended: can use aliases, avoids name clashes
-- use cardinality [0..*] for language-dependent texts
{
@ObjectModel.text.association: '_Text'-- indicate association to view with (language-dependent) texts
key scarr.carrid as Airline, -- control-space proposes field name from global field name catalog
@Semantics.currencyCode: true -- column semantics: this is a currency code
scarr.currcode as AirlineLocalCurrency,
@Semantics.url -- column is a URL; enables consumers to render it properly
scarr.url as AirlineURI,
_Text -- expose the association to related text view, naming convention _Text

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 270
Airline Name

@AbapCatalog.sqlViewName: 'S4HCDS_IAIRLINET' -- S4HCDS_ + I + AIRLINE + T; uppercase


@AccessControl.authorizationCheck: #NOT_REQUIRED
@ObjectModel.dataCategory: #TEXT -- text view, usually language-dependent (but not in this example)
@Analytics.dataExtraction.enabled: true
@EndUserText.label: 'Airline Name'
@ObjectModel.representativeKey: 'Airline'
-- the (most significant) key field, anchor of text associations pointing here
@VDM.viewType: #BASIC

define view S4hcds_I_AirlineText -- S4HCDS_ + I_ + Airline + Text (naming convention)


as select from scarr

{
key carrid as Airline,
// @Semantics.language -- usually, texts are language dependent
// key spras as Language, -- with a language column as additional key field
@Semantics.text -- indicate the "text" field in the view; is used as text for representative key field
@EndUserText.label: 'Airline Name‘
-- choose a better enduser label for the column than in DDIC data element defined
carrname as AirlineName
}

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 271
Airport

@AbapCatalog.sqlViewName: 'S4HCDS_IAIRPORT'
@AccessControl.authorizationCheck: #NOT_REQUIRED
@Analytics.dataCategory: #DIMENSION
@Analytics.dataExtraction.enabled: true
@EndUserText.label: 'Airport'
@ObjectModel.representativeKey: 'Airport'
@VDM.viewType: #BASIC

define view S4hcds_I_Airport


as select from sairport

{
@ObjectModel.text.element: [ 'AirportName' ]
key sairport.id as Airport,
@Semantics.text
sairport.name as AirportName,
sairport.time_zone as AirportTimeZone
}

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 272
Aircraft Type

@AbapCatalog.sqlViewName: 'S4HCDS_IAIRCRFTT'
@AccessControl.authorizationCheck: #NOT_REQUIRED
@Analytics.dataCategory: #DIMENSION
@Analytics.dataExtraction.enabled: true
@EndUserText.label: 'Aircraft Type'
@ObjectModel.representativeKey: 'AircraftType'
@VDM.viewType: #BASIC

define view S4hcds_I_AircraftType


as select from saplane

{
key planetype as AircraftType,
producer as AircraftManufacturer
}

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 273
Master and Transactional Data as #BASIC Views

 Views I_FlightConnection and I_Flight as examples of #BASIC VDM views for master and
transactional data.

 Analytics data categories #DIMENSION and #FACT.

 Annotate a column as analytics measure with default aggregation

 Annotate a unit of measure and a quantity with a related unit of measure

 Annotate a currency and an amount with a related currency

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 274
Flight Connections (1)

@AbapCatalog.sqlViewName: 'S4HCDS_IFCONN'
@AccessControl.authorizationCheck: #NOT_REQUIRED
@Analytics.dataCategory: #DIMENSION
@Analytics.dataExtraction.enabled: true
@EndUserText.label: 'Flight Connection'
@ObjectModel.representativeKey: 'FlightConnection'
-- the (most significant) key field, anchor of foreign key associations pointing here
@VDM.viewType: #BASIC

define view S4hcds_I_FlightConnection


as select from spfli

association [0..1] to S4hcds_I_Airline as _Airline on $projection.Airline = _Airline.Airline


association [0..1] to S4hcds_I_Airport as _AirportFrom on $projection.AirportFrom = _AirportFrom.Airport
association [0..1] to S4hcds_I_Airport as _AirportTo on $projection.AirportTo = _AirportTo.Airport

[..]

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 275
Flight Connections (2)
[..]{
@ObjectModel.foreignKey.association: '_Airline'
key carrid as Airline,
key connid as FlightConnection,
countryfr as CountryFrom, -- here a foreign key association to the country view should be added
cityfrom as CityFrom,
@ObjectModel.foreignKey.association: '_AirportFrom'
airpfrom as AirportFrom,
countryto as CountryTo,
cityto as CityTo,
@ObjectModel.foreignKey.association: '_AirportTo'
airpto as AirportTo,
fltime as FlightDurationInMinutes, -- could be made into a measure as well
deptime as DepartureTime,
arrtime as ArrivalTime,
period as ArrivalDateShiftInDays,
@Semantics.quantity.unitOfMeasure: 'DistanceUnit'
@DefaultAggregation: #SUM -- declares column "Distance" as a measure for analytics
distance as Distance,
@Semantics.unitOfMeasure
distid as DistanceUnit,
_Airline,
_AirportFrom,
_AirportTo
}
© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 276
Flight (1)
@AbapCatalog.sqlViewName: 'S4HCDS_IFLIGHT'
@AccessControl.authorizationCheck: #CHECK
@Analytics.dataCategory: #CUBE -- conceptually this view has data category #FACT
-- but it can only be tested as a #CUBE in the analytics environment
@Analytics.dataExtraction.enabled: true
@EndUserText.label: 'Flight'
@VDM.viewType: #BASIC

define view S4hcds_I_Flight as select from sflight

association [0..1] to S4hcds_I_Airline as _Airline on $projection.Airline = _Airline.Airline


association [0..1] to S4hcds_I_FlightConnection as _FlightConnection
on $projection.Airline = _FlightConnection.Airline
and $projection.FlightConnection = _FlightConnection.FlightConnection
association [0..1] to S4hcds_I_AircraftType as _AircraftType
on $projection.AircraftType = _AircraftType.AircraftType

{
@ObjectModel.foreignKey.association: '_Airline'
key carrid as Airline,
@ObjectModel.foreignKey.association: '_FlightConnection'
key connid as FlightConnection,
key fldate as FlightDate,
[..]

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 277
Flight (2)

[..]

@Semantics.amount.currencyCode: 'Currency'
@DefaultAggregation: #MIN
price as FlightPrice,
@Semantics.currencyCode
currency as Currency,
@ObjectModel.foreignKey.association: '_AircraftType'
planetype as AircraftType,
@DefaultAggregation: #SUM
seatsmax as MaximumNumberOfSeats,
@DefaultAggregation: #SUM
seatsocc as NumberOfOccupiedSeats,
@Semantics.amount.currencyCode: 'Currency'
@DefaultAggregation: #SUM -- a measure is identified by a default aggregation different from #NONE
paymentsum as CurrentBookingsTotalAmount,
_Airline,
_FlightConnection,
_AircraftType
}

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 278
#COMPOSITE View

 View I_FlightByAirport as example of a #COMPOSITE VDM view that is used as basis for analytics

 Analytics data category #CUBE

 Combines columns of I_Flight and I_FlightConnection views via association

 Execute the view in the analytics test environment in SAP GUI

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 279
Flight (by Airport) (1)
@AbapCatalog.sqlViewName: 'S4HCDS_IFLIGHTA'
@AccessControl.authorizationCheck: #CHECK
@Analytics.dataCategory: #CUBE
@EndUserText.label: 'Flight (by Airport)'
@VDM.viewType: #COMPOSITE

define view S4hcds_I_FlightByAirport as select from S4hcds_I_Flight


{
@ObjectModel.foreignKey.association: '_Airline'
key Airline,
@ObjectModel.foreignKey.association: '_FlightConnection'
key FlightConnection,
key FlightDate,
@ObjectModel.foreignKey.association: '_AircraftType'
key AircraftType,
@EndUserText.label: 'Airport From'
@ObjectModel.foreignKey.association: '_AirportFrom'
key _FlightConnection.AirportFrom,
@EndUserText.label: 'Airport To'
@ObjectModel.foreignKey.association: '_AirportTo'
key _FlightConnection.AirportTo,
@Semantics.currencyCode
key Currency,
[..]

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 280
Flight (by Airport) (2)

[..]

@DefaultAggregation: #SUM
MaximumNumberOfSeats,
@DefaultAggregation: #SUM
NumberOfOccupiedSeats,
@Semantics.amount.currencyCode: 'Currency'
@DefaultAggregation: #MIN
FlightPrice,
@Semantics.amount.currencyCode: 'Currency'
@DefaultAggregation: #SUM
CurrentBookingsTotalAmount,
_Airline,
_FlightConnection,
_FlightConnection._AirportFrom, -- exposure of associations via an association avoids redefinition of the associations
_FlightConnection._AirportTo,
_AircraftType
}

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 281
Introduction: #CONSUMPTION View

 View I_FlightByAirportQuery as example of a #CONSUMPTION view which is an analytical query

 Annotations for #CONSUMPTION, Analytics.query and OData.publish

 Filter definition

 Assign fields to rows resp. columns for display

 Aggregation via FORMULA

 Execute the view in the analytics test environment in SAP GUI

 Execute the view in Analysis for Microsoft Excel

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 282
Query Available Flights (1)

@AbapCatalog.sqlViewName: 'S4HCDS_CFLIGHTAQ'
@Analytics.query: true
@EndUserText.label: 'Available Flights'
//@OData.publish: true
@VDM.viewType: #CONSUMPTION

define view S4hcds_C_FlightByAirportQuery as select from S4hcds_I_FlightByAirport


{
@Consumption.filter: { selectionType: #SINGLE, multipleSelections: false, mandatory: true }
@AnalyticsDetails.query.axis: #ROWS
@EndUserText.label: 'Departure Airport'
AirportFrom,
@Consumption.filter: { selectionType: #SINGLE, multipleSelections: false, mandatory: false }
@AnalyticsDetails.query.axis: #ROWS
@EndUserText.label: 'Destination Airport'
AirportTo,
@AnalyticsDetails.query.axis: #ROWS
// @Filter: { selectionType: #INTERVAL, multipleSelections: false, mandatory: true } -- too few test data
FlightDate,
@AnalyticsDetails.query.axis: #ROWS
Airline,

[..]

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 283
Query Available Flights (2)

[..]

@AnalyticsDetails.query.axis: #ROWS
FlightConnection,
AircraftType,
Currency,
MaximumNumberOfSeats,
NumberOfOccupiedSeats,
@EndUserText.label: 'Available Seats'
@DefaultAggregation: #FORMULA
@AnalyticsDetails.query.axis: #COLUMNS
MaximumNumberOfSeats - NumberOfOccupiedSeats as NumberOfAvailableSeats,
@AnalyticsDetails.query.axis: #COLUMNS
FlightPrice
}

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 284
Unit 7 – HANA Native Code Push Down
Unit 7 – HANA Native Code Push Down

Lesson 1 – ABAP-Managed Database Procedures


Lesson 1: ABAP-Managed Database Procedures
Learning Objectives

After completing this unit, you should be able to:


• Create ABAP-managed database procedures.
• Call ABAP-managed database procedures in ABAP
• Debug ABAP-managed database procedures

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 288
Stored Procedures – Recap

SAP HANA offers stored


procedures in SQLScript – an
extension to SQL - for expressing
data intensive application logic.
Writing clever stored procedures can
be key for significant performance
boosts.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 289
Using Stored Procedures in ABAP < 7.40

EXEC SQL ABAP Database Connectivity API


EXEC SQL. lr_stmt->set_param(
procedure

execute procedure dbproc ( REF #( im_src ) ).


Call

in p_in1, lr_stmt->execute_procedure(
inout p_inout1 ) `dbproc` ).
ENDEXEC.

EXEC SQL. l_ddl_command =


create procedure dbproc( |create procedure dbproc( |
Create procedure

in i_param1 integer, & | in i_param1 integer, |


inout ch_param3 nvarchar (20)) & | inout ch_param3 nvarchar (20) )|
language sqlscript & |language sqlscript |
sql security invoker as begin & |sql security invoker as begin |
select top :i_param1 * & | select top :i_param1 * |
from sys.dummy; & | from sys.dummy; |
ch_param3 := 'Success'; & | ch_param3 := 'Success'; end; |.
end;
ENDEXEC. im_sql_handle->execute_ddl( l_ddl_command ).

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 290
ABAP-Managed Database Procedures

Methods of global classes marked with tag interface, available since ABAP 7.4 SP05
 AMDP classes and AMDP methods “Top-Down” Lifecycle
 Easy to consume in ABAP – as simple method call

AS ABAP
lr_customer->classify( ABAP Standard
EXPORTING in_date = in_date
Managed DB ABAP
in_sel = in_sel
IMPORTING out_itms = out_itms ). Procedure Transport

deploy
 AMDP methods are fully managed on the ABAP server

SAP HANA
– Source code editing with ABAP Editor (in ADT)
– Static syntax check and syntax coloring for SQLScript code Stored
Procedure
– Procedure created on first AMDP call
– Detailed analysis of runtime errors in ST22
– Transport analog to regular ABAP classes ABAP Managed Database Procedures

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 291
AMDPs: Integration of Database Procedures Into ABAP

Standard ABAP class methods are used as containers for the implementation of AMDPs
CLASS CL_AMDP_SAMPLE DEFINITION.
PUBLIC SECTION.
INTERFACES IF_AMDP_MARKER_HDB.
...
PRIVATE SECTION.
METHODS execute IMPORTING VALUE(it_param) TYPE type1
EXPORTING VALUE(et_param) TYPE type2.
ENDCLASS.
CLASS CL_AMDP_SAMPLE IMPLEMENTATION.
...
METHOD execute BY DATABASE PROCEDURE …. Method container
-- SQLScript code for an AMDP
ENDMETHOD.
ENDCLASS.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 292
AMDPs: Prerequisites in Class Definition

CLASS CL_AMDP_SAMPLE DEFINITION.


PUBLIC SECTION. Classes with AMDPs must use
INTERFACES IF_AMDP_MARKER_HDB. interface F_AMDP_MARKER_HDB
* Only ABAP code possible:
METHODS process
IMPORTING it_param TYPE type1 Parameters must be
EXPORTING et_param TYPE type2. Tables with elementary components
* ABAP code or SQLScript possible: or Scalar types
METHODS execute
IMPORTING VALUE(it_param) TYPE type1
EXPORTING VALUE(et_param) TYPE type2.
All AMDP method parameters must
ENDCLASS. be passed by value

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 293
Implementation of AMDP Methods

CLASS CL_AMDP_SAMPLE IMPLEMENTATION.


AMDP methods have to be marked
METHOD execute
with BY DATABASE PROCEDURE
BY DATABASE PROCEDURE
FOR db_platform
LANGUAGE db_language Database platform (HDB) and
[OPTIONS READ-ONLY] language (SQLSCRIPT) to be
USING name1 name2 etc.. specified

-- Write SQLScript code here. ABAP Dictionary tables, views, and


select * from dummy; other AMDP methods to be
declared in USING clause
ENDMETHOD.
ENDCLASS.
Method body contains SQLSscript
code
-- marks comments

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 294
AMDP Method – SQLScript Example

METHOD classify_by_id
BY DATABASE PROCEDURE FOR HDB
LANGUAGE SQLSCRIPT OPTIONS READ-ONLY
USING SCUSTOM SBOOK.
-- declare local scalar variables
declare lc_upper_threshold constant int := 300;
declare lc_lower_threshold constant int := 10;
-- translate list of customer ids into id, name ,#of flights …
lt_customers = select c.id, c.name, count( s.bookid ) … from scustom …
where mandt = :iv_client
and c.id in ( select id from :it_customer_id )
group by c.id, c.name;
-- calculate return table
et_classification = select id, name,
case when flight_count > :lc_upper_threshold then 1 …
from :lt_customers …
ENDMETHOD.
© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 295
AMDP Methods – Syntax Error Handling

Icon indicates line with error

Detailed error description


(mouse over)

Summary of errors

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 296
Calling AMDP Methods

An AMDP method is called like any ABAP method.


 AMDP methods are executed like static methods, even if they are defined as instance methods

...
METHOD process.
me->execute(
EXPORTING it_param = it_param
IMPORTING et_param = et_param
).
ENDMETHOD.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 297
ABAP Managed Database Procedures
Exception Handling

Catchable Exceptions "definition


METHODS <method_name>
 Several AMDP runtime errors have a corresponding <method_interface>
(catchable) exception
 Naming convention: ...
!
RAISING cx_amdp_error.

<ERROR_NAME>  CX_<ERROR_NAME>
"consumption
TRY.
 To-Dos for AMDP Developers/Consumers: <method_call>
– Add RAISING clause to the AMDP method definition
– Enclose the AMDP call in a CATCH cx_amdp_execution_failed INTO DATA(lx).
TRY… CATCH block "do some meaningful error handling
ENDTRY.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 298
Debugging ABAP-managed Database Procedures (with ABAP 7.5)

With ABAP 7.5, AMDPs can be debugged using the ABAP perspective “as usual”, provided:
 The Debug perspective is installed properly
 The AMDP has been executed before - AMDPs are created on the DB on demand!

Set breakpoints in ABAP editor, on lines where statements begin

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 299
Debugging ABAP-managed Database Procedures (with ABAP 7.5)

Execute program calling the AMDP  Debug view opens – with limited features

Two Debugger Threads!

Input parameters and local


variables of the procedure

Source code – add breakpoints


as needed

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 300
Enhancements of AMDP Methods: AMDP BAdIs

Foresees extensibility: Enhances


Software Provider BAdI definition marked as BAdI
(modification-free): Customer
Implemen-
•Marked as AMDP BAdI BAdI impl. including
tation
•Requires Fallback Class AMDP

Calls AMDP BAdI Fallback Impl. Custom


AMDP
Extensible  Standard
AMDP Solution

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 301
AMDP BAdIs: Use In AMDP Code

Software Provider View


 Extensible AMDP method declares use of and calls BAdI like any other AMDP
METHOD classify_by_id BY DATABASE PROCEDURE FOR HDB
LANGUAGE SQLSCRIPT OPTIONS READ-ONLY
USING s4hcds_amdp_cstmrcl_extnsbl=>classify_customers ….
… Name of BAdI Definition
-- call BAdI like another AMDP & interface method
call "S4HCDS_AMDP_CSTMRCL_EXTNSBL=>CLASSIFY_CUSTOMERS“
(:lt_customers,:et_classification);

ENDMETHOD.
Customer View: Name of BAdI interface
 BAdI implementation is simply an AMDP method
METHOD if_s4hcds_cstmrcl_extnsbl~classify_customers
BY DATABASE PROCEDURE FOR HDB LANGUAGE SQLSCRIPT OPTIONS READ-ONLY.
-- Custom SQLScript code here.
ENDMETHOD.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 302
Exercise 15: Implement and Call An AMDP

In this exercise you will:


 Create an ABAP-managed Database Procedure
 Call an ABAP-managed database procedure.
 See Student Manual, Exercise 10 Tasks 1-2

Time: 20 min

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 303
Exercise 16: Debug An ABAP-Managed Database Procedure

In this exercise you will:


 Debug an ABAP-managed Database Procedure
 Call an ABAP-managed database procedure.
 See Student Manual, Exercise 11 Tasks 1-2

Time: 10 min

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 304
Lesson 1: ABAP-Managed Database Procedures
Summary

You should now be able to:


• Create ABAP-managed database procedures.
• Call ABAP-managed database procedures in ABAP
• Debug ABAP-managed database procedures

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 305
Unit 7 – HANA Native Code Push Down

Lesson 2 – CDS Table Functions


Why do we need Table Functions?

CDS is an open extension of classical DDIC views:


• Support for AnyDB
• Optimal integration into DDIC and ABAP
• Supports about 90 % of SQL features
• But: no access to specific HANA features

Required: Some scenarios require selective measure (“Breakout Scenario” for HANA-only applications)
• Highest performance requirements e.g. with complex calculations
• Use of database / analytical engine specific functions required
• Open SQL and CDS views do not yet offer functionality to solve the problem

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 308
What do CDS Table Functions do?

CDS Table Functions allow to use natively


implemented database-functions in SAP
HANA DB directly from CDS

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 309
Necessary parts for CDS Table Functions

Table function definition Runtime for table function


Parameter list Runs stored SQL-script procedure
Return Parameter generated from AMDP on database
tables
Reference to implementing method
ABAP
Managed
Database
SAP HANA
Procedure
DDL Database
Source
AMDP Implementation
Includes SQL-script
function body

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 310
CDS Table Functions Implemented via AMDP

ABAP/DDIC
ABAP CDS AMDP
Table functions as
„Plain“ CDS- „Breakout“
native HANA
View CDS-View
SQLScript

generates generates

HANA SQL

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 311
Key features of Table functions

• They are implemented in HANA SQLScript via AMDP methods

• Signature is defined in DDL source (importing parameters and return columns)

• They can be consumed by Open SQL and ABAP CDS like other DDIC artifacts (i.e. DB tables,
classical DDIC views, CDS views ...)

• The SQLScript implementation is handled by the AMDP framework (lifecycle, tool support,
extensibility etc.)

• DDL source can be activated before the implementing AMDP method exists

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 312
Definition of a Table Function

Stored in a DDL source


@ClientDependent: false
Name of table function define table function S4HCDS_FlightTableFunction
with parameters
List of input parameters (Optional)
P_FlightDate : AD_DATE
returns
{
List of return parameters (At least one) ConnectionID : abap.numc(4) ;
FlightDate : AD_DATE ;
}
Link to implementation
implemented by method
CL_S4HCDS_AMDP_FLIGHT_TAB_FUNC=>get_flights;

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 313
Implementation of a Table Function (1)

Stored in a global ABAP class


CLASS CL_S4HCDS_AMDP_FLIGHT_TAB_FUNC DEFINITION
PUBLIC FINAL CREATE PUBLIC.

PUBLIC SECTION.
Marker interface
INTERFACES:
if_amdp_marker_hdb.
Method name and link to CDS view
for signature inheritance CLASS-METHODS:
get_flights FOR TABLE FUNCTION
S4HCDS_FlightTableFunction.

PROTECTED SECTION.
PRIVATE SECTION.
ENDCLASS.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 314
Implementation of a Table Function (2)

Implementation is done
in a special tagged method
METHOD get_flights BY DATABASE FUNCTION
FOR HDB
Table functions are read-only LANGUAGE SQLSCRIPT
OPTIONS READ-ONLY
Used ABAP managed objects
USING sflights.

Implementation in SQLScript return select


connid as ConnectionID,
fldate as FlightDate
from sflights
where fldate <= :p_FlightDate;

ENDMETHOD.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 315
Usage of a Table Function

Table functions can be used SELECT * FROM S4HCDS_FLIGHTTABLEFUNCTION


in Open SQL
( p_FlightDate = ‘20160222’ )
INTO TABLE @DATA(flights)
##DB_FEATURE_MODE[AMDP_TABLE_FUNCTION].
Table functions work on SAP HANA DB only
Pragma confirms the successful
execution of a feature mode check
(See class cl_abap_dbfeatures)

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 316
Client Handling - Definition

Activate client handling (By default: true)


@ClientDependent: true
define table function S4HCDS_FlightTableFunc_clnt
Client input parameter with parameters
@Environment.systemField: #CLIENT
Optional
Filled automatically by OpenSQL
clnt_in : abap.clnt,
P_FlightDate : AD_DATE
returns
Client return parameter {
Mandatory clnt : abap.clnt;
Located in first column ConnectionID : abap.numc(4);
FlightDate : AD_DATE;
}
implemented by method
CL_S4HCDS_AMDP_FLIGHT_TAB_FUNC=>get_flights_clnt;

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 317
Client Handling - Implementation

METHOD get_flights_clnt BY DATABASE FUNCTION


FOR HDB
LANGUAGE SQLSCRIPT
OPTIONS READ-ONLY

USING sflights.
return select
mandt as clnt
Usage of client input parameter to select connid as ConnectionID,
the correct values from the database fldate as FlightDate
from sflights
where fldate <= :p_FlightDate and
; mandt = :clnt_in

ENDMETHOD.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 318
Lesson 2: CDS Table Functions
Summary

You should now be able to:


• Use natively implemented SAP HANA-DB functions from CDS

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 329
Exercise 17: Implement CDS Table Function

In this exercise you will:


 Create a DDL Source for HANA Table function
 Use ABAP Class to write the source code for the table function
 See Student Manual, Exercise 17 Tasks 1-2

Time: 20 min

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 330
Further References

ABAP Application Infrastructure


https://wiki.wdf.sap.corp/wiki/display/A4H/ABAP+Application+Infrastructure

HANA Core Data Services


https://wiki.wdf.sap.corp/wiki/display/ngdb/HANA+Core+Data+Services

Domain-specific Annotations in CDS


https://wiki.wdf.sap.corp/wiki/download/attachments/1153423523/Domain-specific%20Annotations.docx?version=1&modificationDate=1441273752000&api=v2

Fiori Architecture Blueprints


https://wiki.wdf.sap.corp/wiki/display/fioritech/Fiori+Tech+Programming+Model

Development Guidelines
https://wiki.wdf.sap.corp/wiki/display/fioritech/Development+Guideline+Portal

SAP UI5
http://scn.sap.com/community/developer-center/front-end

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 331
Further References

SAP Fiori and developing UIs using this technology


Fiori Curriculum Jam.
programming guide and an
"Build SAP Fiori UI - End-2-End-Sample"

Open Data protocol (short: OData)


https://wiki.wdf.sap.corp/wiki/display/NWA/OData+self-paced+training

Gateway
Customer course GW100.

HANA SQL(Script)
ZHA150 SQL Basics for HANA, Unit 10.

Connecting Customer systems using ABAP in Eclipse


https://wiki.wdf.sap.corp/wiki/display/aie/AiE+and+customer+systems+-+How+to

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 332
You made it! – Thank you!

Contact Information:

Panneer Selvam
SAP Development University
[email protected] or SAP Dev Uni

© 2015 SAP SE or an SAP affiliate company. All rights reserved.


Appendix

Appendix Lesson 1 – Additional ABAP Language


Enhancements
Helpful ABAP Language Improvements: Expressions in ABAP 7.4

Use of expressions in ABAP can simplify code


 Style becomes more similar to other programming languages
 Fewer local variables or field symbols,
focus more on What than How

Helpful in ABDC context


 String expressions
 Inline declarations
 Constructor expressions
 Table expressions

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 338
String Expressions and String Templates

DATA lo_sql TYPE REF TO cl_sql_statement.


DATA lo_res TYPE REF TO cl_sql_result_set.
DATA lv_carrid TYPE string VALUE 'LH'.

DATA lv_sql_stmt TYPE string.

CONCATENATE 'SELECT * FROM SFLIGHT' Classical ABAP


' WHERE mandt = ''' sy-mandt ''''
' AND carrid = ''' lv_carrid ''''
INTO lv_sql_stmt.
Using String
lo_res = lo_sql->execute_query( lv_sql_stmt ). Expressions

lo_res = lo_sql->execute_query( |SELECT * FROM SFLIGHT |


&& | WHERE mandt = '{ sy-mandt }' |
&& | AND carrid = '{ lv_carrid }' | ).

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 339
Inline Declarations and Constructor Expressions

DATA lo_sql TYPE REF TO cl_sql_statement.


DATA lo_res TYPE REF TO cl_sql_result_set.
DATA lr_flight TYPE REF TO data.
DATA lt_flight TYPE STANDARD TABLE OF sflight. Classical ABAP
CREATE OBJECT lo_sql EXPORTING ….
lo_res = lo_sql->execute_query( … ).

GET REFERENCE OF lt_flight INTO lr_flight. Using Expressions


lo_result->set_param_table( lr_flight ).

DATA lt_flight TYPE STANDARD TABLE OF sflight.

DATA(lo_sql) = NEW cl_sql_statement( … ).


DATA(lo_res) = lo_sql->execute_query( … ).

lo_res->set_param_table( REF #( lt_flight ) ).

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 340
Table Expressions

Basic syntax:
 READ TABLE <table> INDEX 1 Overview Table LT_OVERVIEW
 <table>[ 1 ] PARAM VALUE
 READ TABLE <table> WITH KEY … ET_TOP “SCHEMA"."ET_TOP_529…"
 <table>[ param = 'ET_TOP' ] ET_BOTTOM "SCHEMA"."ET_BOTTOM_529…"
 For more options see documentation

Read using table


expressions

lo_result = lo_sql->execute_query(
|SELECT * FROM { lt_overview[ param = 'ET_TOP' ]-value }
| ).

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 341
Exercise 18: Use Expressions and Inline Data Declarations

In this exercise you will:


 Use inline data declarations and string templates to simplify ADBC code
 Use table expressions to simplify ADBC code
 See Student Manual, Exercise 19 Tasks 1-4

Time: 25 min

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 342
Appendix
Appendix Lesson 2 – Introduction to SAP HANA Studio
SAP HANA Studio – An Eclipse-based Development Environment

Eclipse™ is SAP’s strategic platform for highly integrated


design-time and development tools.

 SAP HANA Studio is Eclipse-based; tools based on existing Eclipse frameworks


 Common development environment for SAP HANA and ABAP (ADT) going forward
© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 346
SAP HANA Studio – Perspectives and Views

SAP HANA Studio provides several Eclipse perspectives


 Administration Console
 Modeler
 SAP HANA Development
 …

SAP HANA Studio provides several Views


 Systems
 Properties
 Job Log
 …

Editors, Toolbars …

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 347
Most Relevant Perspective For ABAP Developers: Modeler

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 348
The Systems View

System

Schema

Table
Double-click to
open definition
Right-click to
see data
Information
Models

Users &
Roles

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 349
Connecting to an SAP HANA Database

Connect to SAP HANA database


 Using Systems view

Information you need


 Host Name
 Instance Number
 Description
 Database User
 Password

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 350
Table Definitions

Display SQL
CREATE TABLE
statement

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 351
SAP HANA Content – Packages, Models, Delivery Units

Content Packages Delivery Unit as transport vehicle


 Create packages for own information models  Name & Vendor
 Contains one or more packages

Create packages
under node Content

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 352
Exercise A2: Log on to the SAP HANA Studio

In this exercise you will:


 Open the SAP HANA Studio and connect to the SAP HANA Server
 Create a content package in SAP HANA
 Create a delivery unit and assign a package to it
Time: 15 min

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 353
Appendix
Appendix Lesson 3 – Guided Performance Analysis
Transition ABAP Code in ABAP for SAP HANA
Best Practice

1. Detect
Execute Performance measurements
Analyze and prioritize Detect

2. Optimize
Use new features to optimize existing code

3. Innovate Optimize
Use new features, resources and possibilities
to enhance your business
Innovate

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 357
Guided Performance Optimization – Detect

1 Static Code Check 3


 Identify location of known critical code Work list
constructs (e.g. SELECT *)
 Tool: ABAP Test Cockpit / Code Inspector Developer

2 Runtime information from the production


system 1 2
 Usage of Constructs
 Tool: SQL Monitor

3 Prioritized Worklist
 Combines the static and runtime check
results DEV QAS PRD
 Tool: SWLT

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 358
New ABAP SQL Monitor

What is the SQL profile of my system or transaction?


 Get aggregated performance information on database interactions

Full transparency about every executed SQL in production environment

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 359
The New ABAP SQL Monitor - Architecture

When SQL Monitor is switched on


 ABAP kernel logs information about DB accesses asynchronously via runtime monitor.
 Monitoring data is moved periodically via a batch job to specific database tables.
 SQL Monitor transaction reads data from these database tables.

Work Process
SQL Monitor Transaction

Runtime
Async.
Database Interface Monitor Batch
Data Job

Application SQLM
Tables Tables

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 360
Switching the SQL Monitor On and Viewing SQL Monitor Data

Set up SQL Monitor


 Use transaction SQLM
 See also:
http://scn.sap.com/docs/DOC-47444

Display SQL Monitor data


 Use transaction SQLMD or
 Navigate from transaction
SQLM

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 361
Exporting and Importing SQL Monitor Snapshots

Transaction SQLM offers a simple management


of SQL Monitor snapshots.

Snapshots can be:


 Created based on local data
 Imported from file (e.g., from other systems)
 Exported to file
 Removed

To reduce data volume, basic filter criteria can be


applied before snapshot creation.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 362
Demo
SQL Monitor

© 2015 SAP SE or an SAP affiliate company. All rights reserved.


SQL Performance Tuning Worklist – Motivation

SQL Monitor ABAP Test Cockpit


Analyzes the SQL profile of processes  Detects source code with optimization potential
! No information about the code execution flow ! No information about if and how often code is
actually executed
(stack trace)

Which business
What ABAP code could
processes should be
be optimized?
optimized?

The SQL Performance Worklist (SWLT) allows you to correlate SQL runtime
data with ABAP code analysis to plan optimizations.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 364
SQL Performance Tuning Worklist – Usage

Transaction SWLT provides a combined view with flexible navigation options


1
Ranked
worklist

SQLM Data ATC Results


Different request Detailed check
entry points results
2 3

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 365
Demo
SQL Performance Worklist

© 2015 SAP SE or an SAP affiliate company. All rights reserved.


Exercise A3: Combine Static Checks and Run-time Analysis

In this exercise you will:


 Use SWLT to analyze ABAP report HA400D_SWLT_OPEN_AMOUNT, combining the results
of a static code inspector check and a run-time data collected using SQLM.
 See Student Manual, Exercise 4 Task 1.

Time: 15 min

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 367
In-depth Analysis of Performance Issues

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 368
Exercise A4: Improve Performance Using Joins

In this exercise you will:


 Analyze ABAP report HA400_EPM_OPT_OSQL_S2 accessing mass data via Open SQL.
The report determines how old each business partner’s Sales Orders Invoices are (average, in
days).
 Analyze the report.
 Understand and analyze the performance-improved version.
 See Student Manual, Exercise 5 Tasks 1-3.

Time: 10 min

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 372
Lesson A3 – Guided Performance Analysis
Summary

You should now be able to:


• Use the SQL Monitor (SQLM) to identify most important database access
• Use the Performance Tuning Worklist (SWLT) to combine static and dynamic
performance analysis results
• Use SQL Trace (ST05) for in depth analysis of database accesses

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 373
Appendix
Appendix Lesson 4 – VDM Analytical Perspective
Lesson A4: VDM Analytical Perspective
Learning Objectives

After completing this unit, you should be able to:


• Explain the Analytical perspective of VDM
• Explain the important annotations used in Analytical context in VDM

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 375
SAP S/4HANA Analytics Architecture

Key-User/Business-User Defined
Fiori UIs SAP BI Tools (Design Studio …) 3rd Party UI/Client Content

3rd Party Components (Optional)


Interfaces: https | oData | InA

Provided by SAP (Out-of-the-


Customer & User-Specific Analytical Content Box)
(Queries, KPIs etc.)
Frameworks & Infrastructure
Analytical

Virtual Data Model (VDM)


oData Service Engine Consumption Customer-Specific
Ext. SAP Technology Components

Open CDS-based
Views Consumption Views

Gateway Custom-Built Development


Customer-Specific
Interface views Ext. Artefacts or Customer-defined
Interface Views
Extensions to SAP-provided
Application Objects
Customer-Specific Private
Server Private Views Ext.
Views
(ABAP)

Database Server Physical Tables


(SAP HANA)

1 defined by roadmap and depending on deployment option 2 CDS = Core Data Services

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 376
Analytics Vision for SAP S/4HANA
Hybrid, embedded Stand-alone
User Analytical and transactional scenarios using tightly Analytics use cases using BI-tools and analytical apps
Experience embedded Analytics controls for…
Operational/
Simple List Pixel-perfect … transactional
reporting Planning

Multi-
Simple Pixel-perfect KPIs/ In-place
dimensional
List / Chart reporting Dashboards MS Office Multi-
reporting KPIs/ Decision support
dimensional
Dashboards Apps
report

… Rule-based
MS Office Simulation decision
Planning
Application automation and
Application
exception
handling

Consistent Analytical
Personalization, Sharing/Collaboration, Pivoting, Filtering, Office integration, Insight-to-Action,
Features, independent of
Navigation, Role-based access, Printing, …
“embedded” or “stand-alone”

Virtual Data Specific Models (Analytical Queries, Search Models, …) Customer Extensions
Model Virtual Data Model
Customer
For Search, operational and analytical processing Extensions
SAP HANA Platform

Application Tables External Sources / IOT

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 377
Analytical View Model

@Analytics.dataCategory: #CUBE @ObjectModel.dataCategory: #TEXT


I_SalesOrderItemCube @ObjectModel.representativeKey: …
Measure / key figure I_SalesOrganizationText
@DefaultAggregation: #SUM
NetAmount key SalesOrganization
@ObjectModel.foreignKey.association:…
SalesOrganization @Semantics.text
SalesOrganizationName

@Analytics.dataCategory: #DIMENSION
@ObjectModel.representativeKey: …
I_SalesOrganization
@ObjectModel.text.association: …
Dimension / characteristic key SalesOrganization

„navigation attribute“ CompanyCode


Dimension text
„Display attribute“

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 378
Foreign Key and Text Associations, Representative Key

DIMENSION TEXT
I_Country I_CountryText
rk Country rk Country
@ CountryName
CUBE
I_BillingXYZ

Country
Region
DIMENSION TEXT
I_Region I_RegionText
Country Country
rk Region rk Region
@ RegionName

Foreign-key associations on field level Text associations on field level

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 379
Analytical CDS Views
Relationships

Query AGGREGATIONLEVEL Important Annotations


@Analytics.query: true
@Analytics.dataCategory
@ObjectModel.dataCategory
CUBE

DIMENSION TEXT FACT HIERARCHY

DB Table

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 380
Analytical Query
Schematic Model

Analytical Query:
Query View Hierarchy View
@Analytics.query
Hierarchy Directory Association

Hierarchy Node View

Hierarchy Node Text


Foreign Key Association
Association Association
Foreign Key Text
Dimension View Association Association
or Dimension View Text View
Cube View

Analytical Network:
Data Source: Foreign Key
@ObjectModel.foreignKey/text/hierarchy.association
Association
@Analytics.dataCategory: #CUBE/DIMENSION
@DefaultAggregation Any View
(optional)

Database Table

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 381
Important Annotations

@Analytics.query
Admissible Values: blank (=true), true, false

Only analytical query views shall be annotated. They all reside in the consumption layer.
Query views shall not carry an analytical data category.
//Example:
@Analytics.query:true
define view C_BillOfMaterialQuery as select...

@Analytics.dataCategory
Admissible Values: #FACT, #DIMENSION, #CUBE, #AGGREGATIONLEVEL

The VDM reuses the analytical data categories for distinguishing texts and hierarchies from core entities.
//Example:
@Analytics:{
dataCategory:#DIMENSION , dataExtraction.enabled:true }
define view C_BillOfMaterial as select...
@ObjectModel.dataCategory
Admissible Values: #TEXT, #HIERARCHY

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 382
Analytical CDS Views
Important Annotations

Consumption View View


@Analytics.query: true @Analytics.query:true
@VDM.viewType: #CONSUMPTION
VIEW I_SalesOrderValueTrackingQuery
@Analytics.dataCategory: #CUBE…
#SalesOrder #SalesOrderItem SalesOrderItem Fields SalesOrganization @ObjectModel.dataCategory: #TEXT…
@ObjectModel.representativeKey: ‘KeyField’

Interface View

@Analytics.dataCategory: #CUBE Field


@VDM.viewType: #COMPOSITE @ObjectModel.foreignKey.association: ‘_FK’
VIEW I_SalesOrderValueTrackingCube
#SalesOrder #SalesOrderItem SalesOrderItem Fields SalesOrganization Fields ... _SalesOrganization
@ObjectModel.text.association: ‘_Text’
@ObjectModel.text.element: [‘TextField’]
@DefaultAggregation: #SUM
@Analytics.dataCategory: #DIMENSION
<<Association>> @Semantics.text/unitOfMeasure/…
@VDM.viewType: #BASIC
VIEW I_SalesOrder
ASSOCIATION [0..1] TO I_SalesOrganization AS _SalesOrganization
@AnalyticsDetails: …
#SalesOrder ... _SalesOrganization #SalesOrganization ...

<<Association>>
VIEW I_SalesOrganization
<<Association>>
VIEW I_SalesOrderItem
#SalesOrder #SalesOrderItem SalesOrderItem Fields _SalesOrder

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 383
CDS Views and Relations
Example: Very simple SFLIGHT model

4 7 2 3

9 6 5

1
: View
: refers to (select from, join, or association)
to)All rights reserved.
© 2016 SAP SE or an SAP affiliate company. Internal 384
CDS Views and Relations
Analytical Perspective: Data Category, Query; Semantics

@Analytics.dataCategory, ~.query
@Semantics (e.g. amount ) 8

4 7 2 3

9 6 5

#DIMENSION (Master Data) #FACT (Transaction Data)


#TEXT (Text) 1 #CUBE (Analytical View)
#HIERARCHY (Hierarchy) query: true (Analytical Query)
© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 385
CDS Views and Relations
Analytical Perspective: Star Schema (virtual)

Center: @Analytics.dataCategory: #CUBE or #DIMENSION

4 7 2 3

Dimension: Key, Attributes


Dimension: Text 1 Analytical View (incl. Measures)
@DefaultAggregation <> #NONE
Dimension: Hierarchy
© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 386
CDS Views and Relations
Analytical Perspective: Star Schema with Master Data Hierarchy (virtual)

Hypothetical Extension of SFLIGHT Example: External Hierarchy of Airlines

4 7 2 3

Dimension: Key, Attributes


Dimension: Text 1 Analytical View (incl. Measures)
Dimension: Hierarchy @DefaultAggregation <> #NONE
© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 387
CDS Views and Relations
Analytical Perspective: Data Sources for Analysis (Design Studio)

@Analytics.query: true, or @Analytics.dataCategory: #CUBE (has default Query)

9 6

Analytical View
Analytical Query

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 388
CDS Metadata required to establish (transient) ODPs
Data Category

DataCategory on interface level

@ObjectModel.dataCategory: #TEXT, #HIERARCHY

@Analytics.dataCategory: #FACT, #CUBE, #DIMENSION

 DIMENSION: Master Data (or Business Documents) (incl. associations to attributes and texts)
 TEXT: Text View (containing 1 or more language-dependent texts)
 HIERARCHY: Hierarchy Nodes (contains the key of the hierarchy directory)
 FACT: Transaction Data (incl. at least one measure)
 CUBE: Transaction Data, incl. associations to all elements with master data
(“star schema”), and incl. all dimensions and all fields relevant for grouping (“navigation
attributes”).
(typically a CUBE is based on a single view of category FACT

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 389
Check Analytical Query
Query Monitor (Transaction RSRT) (1)

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 390
Check Analytical Query
Query Monitor (Transaction RSRT) (2)

Shall be used to test the correctness of query views (Annotation: @Analytics.query: true) and views used in these query views.
Can also be used to test Analytical Views (CUBE or FACT) via a default query.

Allows to test the complete query functionality in different UIs

For query enter the ID of your query: "2C" + <sql view name of the query>.
Example:
 CDS view name: ZTKC_FlightQuery
 SQL view name: ZTKCFLIGHTQUERY
 ID of (transient provider for) query: 2CZTKCFLIGHTQUERY

For Query Display choose: "HTML" to get an html-based UI for the query

As a result you get a view of your as specified in your CDS views You can now change the query execution like adding
additional fields, removing fields, choose display attributes, set filters,...

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 391
Check Analytical Query
Query Monitor (TA: RSRT) (3)

Hints:

If a query view is currently executed in rsrt but changed and activated in parallel the changes might not taken in the current rsrt
session. So, if you change a view which you are currently using in rsrt you need to restart the transaction

If a query view doesn't work but is correct (as checked by the check report mentioned below) this might be a caching issue. Try
to regenerate the query via Environment --> Generate Queries.

Some features (adding display attributes, choosing key or text for display) are hidden in the extended menu. Use the right
mouse-click at the name of the relevant field and choose "Extended Menu"

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 392
Lesson A4: VDM Analytical Perspective
Summary

You should now be able to:


• Explain the Analytical perspective of VDM
• Explain the important annotations used in Analytical context in VDM

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 393
Appendix
Appendix Lesson 5 – CDS Unit Testing
Why do we need Testing for “Code Pushdown”-Scenarios ?
Complexity of S/4 CDS Model (1)
Graph Representation of a Data Model using the Association as Edges

S/4Hana Development System[1]


Number of CDS Views: 6.590
Number of Associations 9.328
Lines of Code in CDS Views: 355.905

[1] on 2015-09-18
© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 397
Why do we need Testing for “Code Pushdown”-Scenarios ?
Complexity of S/4 CDS Model (2)
TOP Views (with most “basis objects”) TOP Views (with most tables)
Entity # Basis Objects Entity #Tables
VFCLM_BAM_DDL_BSM_MD5 5.114 VFCLM_BAM_DDL_BSM_MD5 4.598
C_PURORDREFPURCONITM 3.055 VFCLM_BAM_DDL_BSM_MD4 2.298
P_ASSOCPURORDITMPURCONITM 3.054 VFCLM_BAM_DDL_BSM_MD3 2.298
C_PURGINFORECORDFS 3.008 C_PURORDREFPURCONITM 1.619
VFCLM_BAM_DDL_BSM_MD4 2.555 P_ASSOCPURORDITMPURCONITM 1.619
VFCLM_BAM_DDL_BSM_MD3 2.553 C_PURGINFORECORDFS 1.600
C_PURCHASINGCATEGORYFS 1.603 C_PURCHASINGCATEGORYFS 838
C_PURORDBYSUPPLIERINVOICE 1.569 C_PURORDBYSUPPLIERINVOICE 827
C_CONTRACTITEMFS 1.534 C_CONTRACTITEMFS 813
C_PURREQUISITIONITEMFS 1.527 C_PURREQUISITIONITEMFS 811
C_PURREQUISITIONFS 1.519 I_SUPPLIERCONTACTCARD 807

 55 Views exceed “ANYDB limit” of 248 tables

Complete List: Complete List:

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 398
Why do we need Testing for “Code Pushdown”-Scenarios ?
Complexity of S/4 CDS Model (3)

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 399
Why do we need Testing for “Code Pushdown”-Scenarios ?
Here is the Answer…

Resulting Questions (based such complex CDS Models)


 How to ensure consistency across the different layers of the View stack ?
 How to avoid regressions ?
 How to provide supportability ?

Potential Answers
 Use Debugging
 SQL doesn’t offer debugging “by definition”
 Use (Unit) Testing
 the only “technically feasible” option to ensure the above qualities!

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 400
Unit Testing

Unit testing is a software methodology to test portions of code, to ensure they are fit for the intended
purpose. These portions of code can be described as smallest testable element of an application.

In Object Oriented programming a method or a class can be considered as unit. With code pushdown
a CDS view or a database procedure can be considered as unit.

 Test a single CDS view

 Test a single ABAP managed database procedure

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 401
Dependencies

The portion of code that shall be tested is also called Code Under Test (CUT). Typically the CUT
invokes other code or relies on data sources like a database table. Such dependencies are also called
Depended-on Component (DOC).

Unit test Code Under Depended On


Test Component

The dependency to database table content can prevent a successful unit test execution in case the
assumed content is not available however.

 In order to achieve stable unit tests it is required to isolate the CUT from any test hindering DOC.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 402
Test Doubles

A common practice is to replace a DOC with test unfriendly behavior by a substitute with test friendly
behavior. Such a substitute is also called Test Double.

(Original)
Unit test Code Under Depended On
Test Component

establishes
Test Double
no longer
required

 Unit testing requires to create test doubles


 Unit testing requires to manage dependencies in order to establish test doubles

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 403
Appendix
Appendix Lesson 6 – Fiori Programming Model
Fiori Technology

Search & Analytics


The challenge –
Search Engine Analytics
Engine Engine simplify and bring together what
Transactional Proc.
belongs together

HANA

Data Data
Replication Replication

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 406
Fiori Programming Model – Open, flexible and standardized

SAPUI5 Common UI Technology for Enterprise Applications

FioriBuildingBlocks UX Consistency and Development Efficiency


Based on Metadata
UI Tier
UI Integration Tier
UI Integration Tier • Reuse of UI technologies (e.g. SAPUI5 and FioriBuildingBlocks)
and design investments and innovations for all Application Tiers
• Integration Services, like Cross-System-Navigation, Mobile
S/4 Service/Application Tier Application Infrastructure
• Service API Definition and Processing
• Key enabler for Fiori Programming Model
• Allows step-wise transition to S/4 HANA
HANA
Core Data Services
• Data models
Database Tier • Metadata describing Business Semantics
© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 407
Getting started – Get the Idea
Simple Example of a Fiori Programming Model

SAP WebIDE UI5 Sources

Generate user interface


UI developer

ABAP in Eclipse Gateway Service

Expose OData service

ABAP in Eclipse CDS / DDL Source


Backend
developer
Define
Data data model
modeling

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 408
Simple list reporting
ALV-like applications
Fiori User Interface UI runtime
Find:
GET ../SalesOrder?
$filter=
R $select=
$orderby=
search=
$top= 50
HTTP / OData

OData Service OData dispatcher


SQL
select
from SalesOrder
R
CDS (DB Views) where and contains( , )
order by
limit 50
SalesOrder
HANA
Annotations

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 409
Fiori Building Blocks: Smart Controls and Smart Templates
Annotation Driven Fiori UIs

What means  Annotations describe semantics related to data (examples see next slide).
? Smart?  Smartness of Controls and Templates is based on the understanding of
these semantics. Annotations are evaluated in the Client Controller logic.

Development steps
Choose Template Select annotated Run fully functional
OData Service. standard Fiori Application
Templates incorporate Annotations are derived from No front end coding required.
latest Fiori design and CDS for reuse, productivity Extension via additional
UX. and consistency. Annotations or own Templates.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 410
Demo
Fiori & OData

© 2015 SAP SE or an SAP affiliate company. All rights reserved.


Fiori Programming Model
Summary

You should now be able to:


• Explain the Fiori Programming Model

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 412
Appendix
Appendix Lesson 7 – Miscellaneous
Open SQL Vs ABAP CDS

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 414
Core Data Services: HANA & ABAP

Two Ways of Database Integration


Even so the Core Data Services Specification is
language and platform agnostic, the CDS
implementations are not.
HANA CDS HANA DB
ABAP

?
• Same Semantic on all DBs • HANA only (HANA specific features
• Initial Focus on View building available)

• Integration into ABAP Data • Initial Focus on Building Models


Dictionary from Scratch

CDS Associations: CDS Associations:


• Unmanaged Associations • Managed and Unmanaged
ABAP CDS only Associations

Due to the different requirements and platforms, the two CDS


implementations have different feature sets and release
cycles.
A technical compatibility is not guaranteed.

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 415
ABAP CDS vs HANA CDS

© 2016 SAP SE or an SAP affiliate company. All rights reserved. Internal 416

You might also like