S4D430 Building Views in Core Data Services ABAP (CDS ABAP) . . PARTICIPANT HANDBOOK INSTRUCTOR-LED TRAINING . Course Version: 10 Course Duration: 3 Day(s) e-book Duration: 24 Hours Material Number: 50142171 SAP Copyrights and Trademarks © 2017 SAP SE or an SAP affiliate company. All rights reserved. No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP SE or an SAP affiliate company. SAP and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of SAP SE (or an SAP affiliate company) in Germany and other countries. Please see http://global12.sap.com/corporate-en/legal/copyright/index.epx for additional trademark information and notices. Some software products marketed by SAP SE and its distributors contain proprietary software components of other software vendors. National product specifications may vary. These materials are provided by SAP SE or an SAP affiliate company for informational purposes only, without representation or warranty of any kind, and SAP SE or its affiliated companies shall not be liable for errors or omissions with respect to the materials. The only warranties for SAP SE or SAP affiliate company products and services are those that are set forth in the express warranty statements accompanying such products and services, if any. Nothing herein should be construed as constituting an additional warranty. In particular, SAP SE or its affiliated companies have no obligation to pursue any course of business outlined in this document or any related presentation, or to develop or release any functionality mentioned therein. This document, or any related presentation, and SAP SE’s or its affiliated companies’ strategy and possible future developments, products, and/or platform directions and functionality are all subject to change and may be changed by SAP SE or its affiliated companies at any time for any reason without notice. The information in this document is not a commitment, promise, or legal obligation to deliver any material, code, or functionality. All forward-looking statements are subject to various risks and uncertainties that could cause actual results to differ materially from expectations. Readers are cautioned not to place undue reliance on these forward-looking statements, which speak only as of their dates, and they should not be relied upon in making purchasing decisions. © Copyright. All rights reserved. iii Typographic Conventions American English is the standard used in this handbook. The following typographic conventions are also used. This information is displayed in the instructor’s presentation Demonstration Iii a Procedure Warning or Caution Hint Related or Additional Information A 0 » Facilitated Discussion iv User interface control Example text Window title Example text © Copyright. All rights reserved. Contents vii Course Overview 1 Unit 1: 2 14 19 23 35 43 Lesson: Motivating CDS Views and Understanding the Background Lesson: Working with ABAP Development Tools (ADT) Exercise 1: Create a Project, a Package and a Program in ADT Lesson: Analyzing and Using A CDS View Exercise 2: Analyze a CDS View and Use It in Open SQL Unit 2: 44 51 56 Unit 3: 80 87 93 101 107 109 116 121 126 137 143 145 153 161 169 181 188 197 203 213 Basic SQL Features in CDS Views Lesson: Define a Simple CDS View Exercise 3: Define a Simple CDS View Lesson: Creating a CDS View with Inner Join, Projection, and Selection Exercise 4: Define a CDS View That Reflects a Database View Lesson: Using ABAP Annotations in CDS Views Exercise 5: Use Annotations in DDL Sources 61 67 73 79 Introduction More SQL Features in CDS Views Lesson: Using SQL Expressions in CDS Views Exercise 6: Use Expressions in a CDS View Lesson: Using Built-in SQL Functions in CDS Views Exercise 7: Use Built-in Functions in a CDS View Lesson: Understanding Nested Views Exercise 8: Define a CDS View based on other CDS Views Lesson: Using Aggregations in CDS Views Exercise 9: Define a CDS View with Aggregation Lesson: Using Additional Join Types and UNION (ALL) Exercise 10: Define a CDS View with a UNION statement Unit 4: Advanced Concepts Lesson: Defining CDS Views with Input Parameters Exercise 11: Define and Use a CDS View with Input Parameter Lesson: Building CDS Views with Associations Exercise 12: Define a CDS View with Associations Exercise 13: Use a CDS View with Associations Lesson: Enhancing a CDS View Exercise 14: Enhance a CDS View Lesson: Linking a CDS View with Authorization Rules Exercise 15: Create and Use a DCL Source © Copyright. All rights reserved. v 219 Unit 5: 220 231 241 242 249 253 260 264 269 vi Database-Specific Features of ABAP CDS Lesson: Understanding CDS Table Functions Exercise 16: Define and Use a CDS Table Function Unit 6: Consumption of CDS Views (Outlook) Lesson: Using a CDS View as Data Source for ALV IDA Lesson: Using CDS Views as Replacement Objects Lesson: Generating OData Services from CDS Views Lesson: Understanding the Consumption of CDS Views in SAP Fiori Lesson: Understanding Analytics Based on CDS Views Lesson: Understanding Virtual Data Models with CDS Views © Copyright. All rights reserved. Course Overview TARGET AUDIENCE This course is intended for the following audiences: © Copyright. All rights reserved. vii viii © Copyright. All rights reserved. UNIT 1 Introduction Lesson 1 Motivating CDS Views and Understanding the Background 2 Lesson 2 Working with ABAP Development Tools (ADT) Exercise 1: Create a Project, a Package and a Program in ADT 14 19 Lesson 3 Analyzing and Using A CDS View Exercise 2: Analyze a CDS View and Use It in Open SQL 23 35 UNIT OBJECTIVES ● Know the Background for Core Data Services ● Understand the Basics of CDS ● Work with ABAP Development Tools ● Read a Data Definition ● Use CDS-related Tools in ADT ● Use Open SQL to Read From a CDS View © Copyright. All rights reserved. 1 Unit 1 Lesson 1 Motivating CDS Views and Understanding the Background LESSON OBJECTIVES After completing this lesson, you will be able to: ● Know the Background for Core Data Services ● Understand the Basics of CDS SQL Basics and ABAP's Classical Approach When it comes to accessing a Database Management System (DBMS) from within an application programming, the Structured Query Language (SQL) has established itself as a kind of first choice. SQL is largely standardized as ANSI SQL, but each vendor adds its own features. Structured Query Language {SQL) - Access to database management systems (DBMS) - Largely standardized (SQL-92) - Three sublanguages: DML, DDL, DCL 1 • Data Mani,pulatlon Language (D ML) - Read and change data in DB tables - Statements SELECT, INSERT, UPDATE, DELETE ... • Cata Definition Language (DDL) - Create and ma.intain DB tables and views - Statements CREATE, ALTER, DROP, ... Data ,control Language (DCL) - Define authorizations and transaction control - StatementsGRANT, REVOKE, ... ] Figure 1: Reminder: SQL Overview SQL as a whole covers all kinds of tasks that might be relevant for an application program. There are three sublanguages of SQL: Data Manipulation Language (DML) Provides statements for reading and changing the content of database tables and comprises statements like SELECT, INSERT, UPDATE, and DELETE. Data Definition Language (DDL) 2 © Copyright. All rights reserved. Lesson: Motivating CDS Views and Understanding the Background Provides statements for creating database objects like tables and views and to maintain their properties. Statements like CREATE TABLE, CREATE VIEW, ALTER TABLE, DROP TABLE belong to the DDL part of SQL. Data Control Language (DCL) Covers the aspects of data integrity and security. DCL allows the application to define authorization rules and to bundle DML statements into transactions (better known to the ABAP developer as Logical Units of Work (LUW). DCL statements are, for example, GRANT and REVOKE. ABAP had always had a very special approach to SQL. ABAP's Classical Approach to SQL OML inABAP - Open SOL, integrated in programming language - DB-independent syntax - DB-independent behavior - Reduced feature set compared to SQL-92 • DDL inABAP - ABAP Dictionary - DB-independent tool - Form-based editing of table definitions and views DCL inABAP - Not needed in ABAP - Authorization and transaction control never on DB level - Always done in application (AUTHORITY-CH ECK, COMM IT WORK, ... ) ] Figure 2: ABAP's Classical Approach to SQL In principle, only the DML part of SQL is available to an ABAP program at runtime. Open SQL, SQL the SQL variant that is built-in into the ABAP language, only covers DML aspects. When ABAP developers want to define database tables and views, they are not supposed to issue DDL statements at runtime. They have to use the ABAP Dictionary tool, which provides form-based editors for table and view definitions (for example, repository objects Transparent Table and Database View). During activation of these definitions, the system creates database-specifc DDL statements and sends them to the database. The DCL part of standard SQL is not needed in ABAP. In the classical approach of ABAP, all tasks covered by this sublanguage are kept away from the database. The ABAP application logic is supposed to take care of authorization checks, locks, and transactions (LUWs). The Limitations of Classical Open SQL Open SQL not only restricts itself to the DML part of SQL. When we look at standard SQL, for example, the SQL-92 Standard, many DML features described there are missing from Open SQL. © Copyright. All rights reserved. 3 Unit 1: Introduction Limirtations in .ABAP < 7 .4 SP05 SQL-92 Standard .,. AMitio�al restrictwl'\S Open SQL (before ABAP 7.4) Figure 3: Limitations of Open SQL Before Release 7.40 Among the many limitations of conventional Open SQL, the missing support for expressions, either in the field list or in the WHERE clause, was the most obvious and most dearly missed by application programmers. • General Restrictions - No fixed values - No computed values No CASE expressions - No SQL tu notions 1 limited Support for J o·i ns - Only inner joins and left outer joins - Only Equi.Joins fjoin condition with operator "=" ) - In left outer join: No fields of right table in WHERE clause More limitations - No UNION or UNION ALL I Figure 4: Some Limitations of Open SQL Before Release 7.40 SP05 Two important reasons exist for these limitations: Open SQL wants to be database-independent, not only regarding syntax but — much more important — regarding the results. Open SQL has to be guaranteed that an Open SQL statement provides the same result on all databases. The easiest way to do this is to avoid those features of standard SQL where the database vendors have different opinions about what the result should look like. One example are arithmetic expressions where rounding rules are not the same on all databases. A basic performance rule of ABAP Programming has always been: Keep unnecessary load away from the database. The general assumption had been, that an application programmer, by following this rule, would not make too much use of more sophisticated SQL features, even when they were available in Open SQL. The Limitations of ABAP Dictionary Views When it comes to the definition of Views in the ABAP Dictionary, the gap between ABAP and standard SQL used to be even bigger. 4 © Copyright. All rights reserved. Lesson: Motivating CDS Views and Understanding the Background • DB-indepe,ndent Definition of Database View - Defined in ABAP Dictionary (form based tool) - Created on database (CREATE VIEW statement) Very limited support o,f SQL features Only inner joins with Equi-join Only simple projections (no calculated fields, no conversions, functions, ... ) - Only simple selections (using literal values) - Only DB tables as source (View-on-View not supported) Some ABAP specialities - Buffering - Labels (through data elements) - Search helps and foreign key relations (inherited from underlying tables) Figure 5: ABAP Dictionary Views ABAP Dictionary Views Support on all DBMSs Join/Union. Projection. Selection inner join & simple selection only x Calculation expressions, aggregation, grouping not supported ��Wfrr1.1 Nested views ( on views) x not supported I I I Figure 6: Limitations of ABAP Dictionary Views Again, the main reasons were the common ground for all supported databases and the general “Keep load away from the database” approach. SAP HANA and the Need for Code-to-Data This all changed when, starting with Release 7.4, SAP HANA was fully supported by ABAP systems. © Copyright. All rights reserved. 5 Unit 1: Introduction SAP HANA takes advantage of the latest technology developments 100''/o In-Memory computing OLTP II OLA� In rt!a�llm!! Column and rCNv storage And changed the way of developing and executing applications No Less Aggregates OD-the-fly data models v.illoutdupk-ilt� Indices Fleiwle aml fut relrievel ofthe dalasel Compression �1L [ Text Milllg 83�� on c:olurnn !il<lrag� I 10-10,000x Acceleration Mas...;.e parallemlion Less Parti- tioning Code lines L�!:c:ornplt!.'d.y In data mod@k and code Mass data analysis Ana�/ Tra�ction Figure 7: The SAP HANA platform - More than just another database With SAP HANA, SAP combines the latest developments in hardware and software technology to provide a state-of-the-art in-memory database. However, SAP HANA is much more than a database. Several data analysis engines and a builtin application platform allow the execution of detailed data analyses and even application logic on the database layer itself. To benefit the most from SAP HANA's capabilities, it is necessary to change the programming paradigm as well as the traditional application design. • ApplicaUon Programming Models Database Figure 8: Paradigm Changes in Application Programming The basic approach of classic ABAP programming was: 6 ● Keep load from the database ● Get all the data you need on the application server, and ● Do your processing in ABAP © Copyright. All rights reserved. Lesson: Motivating CDS Views and Understanding the Background But to benefit the most from SAP HANA's capabilities, especially from its use of parallelism and optimized data structures and transfer, it is better to do expensive calculations and aggregations on the database itself rather than transferring huge amounts of data onto the ABAP application server. This is a fundamental change to the ABAP programming paradigm. Now it becomes "logic to data", or "code-to-data" as it is frequently coined, rather than "data to logic". Classic Applications UI Rendering Data-Centric Applications Presentation Server UI & Client Side Application Logic U I Application Logic Service Logic Application Server Data-Centric Logic Database Relallonal D SAP HANA Database *Service Layer on Application Server or on SAP HANA itself (SAP HANA XS) Figure 9: Transformation of Application Design The classical design of ABAP applications combined a powerful application server with a relatively dumb relational database and a similarly simple presentation layer. All the logic was located on the application server. The new application design, inspired by SAP HANA's improved capabilities, transfers part of the logic (called Data-Centric Logic in the figure above) onto the database. On the other end, big parts of the logic (called UI Application Logic in the figure) move from the application server into smart clients. Only a middle part of the overall logic (Service Logic) remains on an application server. Note: It is even possible to implement this remaining service layer on SAP HANA itself. This approach is used by SAP HANA XS. © Copyright. All rights reserved. 7 Unit 1: Introduction SAP HANA Core Data Services UI Rendering UI & Client Side Application Logic UI Application Logic Service Logic Data-Centric Logic Database SAP HANA platform Figure 10: SAP HANA Native Applications and the Need for CDS With the dawn of SAP HANA and the possibility to develop applications directly on the database, not using an application server any more, the need arose to create a meta model repository directly on the database. As with the ABAP Dictionary on the application server, there should be more in the box for you than using native SQL's CREATE TABLE or CREATE VIEW. Especially regarding the need of enriching pure technical definitions with semantics. And that's one of the main reasons for SAP's Core Data Services. The Core Data Services (CDS)' are a collection of domain-specific languages and services for defining and consuming semanticallly rich data models. DDL Data Definition Language Model and retrieve data on a semantic level higher than SQL QL Query Language Consume CDS entities Fully transparent SQL extensions Extends native SQL means for increased productivity DCL Data Control Language Define authorizations for CDS views Modelled and declarative approach Integrates with classic authorization concepts Figure 11: Concept of Core Data Services (CDS) There are many technologies that introduce higher-level models on top of SQL to add semantics and ease consumption – for example, OData EDM models, the Semantic Layer in the BI platform, JPA and enterprise objects in Java, or the business objects frameworks in ABAP. Those higher-level models share many commonalities, but are usually specific to their technology. This prevents their reuse across stacks and increases effort for application developers. 8 © Copyright. All rights reserved. Lesson: Motivating CDS Views and Understanding the Background To address this, SAP HANA introduced a set of domain-specific languages (DSL) and services – called Core Data Services – for defining and consuming semantically rich data models. Among these languages is an enhanced Data Definition Language (DDL) for defining semantically rich database tables/views (CDS entities) and user-defined types in the database. Some of the enhancements are: Expressions Used for calculations and queries in the data model Associations On a conceptual level, replacing joins with simple path expressions in queries Annotations To enrich the data models with additional (domain specific) metadata ABAP Core Data Services UI Rendering, UI & Client Side Application Logic U I Application Logic Application Server ABAP Service Logic Application Logic (ABAP) Data-Centric Logic Database Database Schema (Any) Database Figure 12: Core Data Services on ABAP From the beginning, CDS was not designed for SAP HANA alone. Also the ABAP application server should be able to benefit from the enhanced capabilities that are offered by the DDL of CDS compared to the form-based ABAP Dictionary tool. Since the ABAP Dictionary with its capability of defining tables, views, and data types was already there, the natural way of introducing CDS on the ABAP application server was to add it to the ABAP Dictionary. An ADT-based source code editor allows you to create DDL sources. On activation, the CDS entities defined in such a DDL source become full citizen ABAP Dictionary objects. They work as ABAP types that can be named after a TYPE addition and they can be accessed in Open SQL. © Copyright. All rights reserved. 9 Unit 1: Introduction Database Independent - Use CDS ABAP with any database supported by SAP Advanced View Bui I ding - CDS Views provide m uoh more SOL features than classical Dictionary Views Annotations to add Semantic: Information - Add end user texts, currency keys, buffer settings, ... - Add semantic information for consumers (ana.lytics, OData, SAP Ul5, ... ) • Implicit.Authorization Checks - Define authorization rules for CDS Objects • Associations instead of Joins - Define relations between CDS Objects that will be transleted into joins • CDS Table Functions - Views based on scripted coding [Currently only supported for SAP HANA) I Figure 13: Some Basic Features of ABAP CDS As a first step, the advanced view building capabilities of CDS have been implemented in ABAP CDS. With many, many tables already defined in the ABAP Dictionary, the DEFINE VIEW statement of ABAP CDS makes the full wealth of the CDS universe readily available to existing ABAP data models. You can either define sophisticated new views or simply wrap an existing table in a CDS view in order to enrich it semantically. For example, ABAP CDS offers a new authorization concept based on roles defined with DEFINE ROLE in a DCL source code. In order to let an existing table participate in the new authorization concept, you can simply create a CDS view for that table that is connected to a role. Other examples are advanced joining of tables with associations or using specific annotations in order to connect existing tables to new technologies like OData or UI5. 10 © Copyright. All rights reserved. Lesson: Motivating CDS Views and Understanding the Background ABAP Diictionary Vi:ews ABAP' cos Views Support on all DBMSs Join/Union, Projection, Selection 111? I 1::c:--1111 inner join & simple selection only x 1 inner join. outer Join, union Calculation expressions, aggregation, grouping not supported Nested views (on views) x not supported Figure 14: Advanced View Building with CDS ABAP On a purely technical level, ABAP CDS Views provide the following additional capabilities compared to ABAP Dictionary Views: • ● Enhanced support for combining queries, such as UNION and OUTER joins ● Support for calculations that use expressions in the column list and for selection ● Aggregation and grouping in the data model ● Nested views (View-on-View) Two Ways of Database Integration Even so the Core Data Services SpecificatiOn is language and platform agnostic, the CDS implementations are not. BAP • D Same Semantic on alll DBs • Initial Focus on View building • Integration into ABAP Dictionary NA • O IHAINA only (HANA specific features available) • Initial Focus on Building Models from Scratch Figure 15: ABAP CDS versus HANA CDS With HANA CDS and ABAP CDS we have two implementations based on the same specification. They are very similar but not 100% equal. This is mainly because the two implementations pursue different goals: © Copyright. All rights reserved. 11 Unit 1: Introduction HANA CDS is located on the SAP HANA database directly and is meant to support the development of SAP HANA native applications (SAP HANA XS). It makes liberate use of features which are unique to SAP HANA. ABAP CDS is located on the Application Server ABAP, where it is fully integrated in the ABAP Dictionary and thus in the ABAP transport system, lifecycle management, etc. The goal of ABAP CDS is to support the implementation of ABAP applications – independent of the database system. Therefore its initial focus is on view building, and not on building models from scratch – although this might become possible in the future. Conclusion: Due to the different requirements and platforms, the two CDS implementations have different feature sets and release cycles. A technical compatibility is not guaranteed. CDSelated Repository Objects Ill Data. Definition (DDL Source) - Defines a COS View or CDS Table Function - Display-only in ABAPWorkbench (as olf Rel. 7.51) - Editing requires the use of ABAP Development Tools (ABAP in Eclipse) • Access Control (DCL Souree) - Defines authorization rules that are automatically checked when a program reads certain data - Display-only in ABAPWorkbench (as off Rel. 7.50) - Editing requires the use of ABAP Development Tools (ABAP in Eclipse) Figure 16: CDS-related Repository Objects With ABAP CDS, the following new repository object types were introduced: Data Definition ● ● Also referred to as DDL Source (for Data Definition Language, named after the DDL part of SQL) Contains the definition of either a CDS View or a CDS Table function Access Control ● ● 12 Also referred to as DCL Source (for Data Control Language, named after the DCL part of SQL) Contains the definition of authorization rules that are automatically checked when a program accesses a certain CDS View or CDS table function © Copyright. All rights reserved. Lesson: Motivating CDS Views and Understanding the Background Note: Depending on the system release, you can display the source code of the new CDS-related repository objects in the classical ABAP workbench. However, to create or change the new repository objects, you have to use the respective editors in ABAP Development Tools (also known as ABAP in Eclipse). LESSON SUMMARY You should now be able to: ● Know the Background for Core Data Services ● Understand the Basics of CDS © Copyright. All rights reserved. 13 Unit 1 Lesson 2 Working with ABAP Development Tools (ADT) LESSON OBJECTIVES After completing this lesson, you will be able to: ● Work with ABAP Development Tools Eclipse-Based ABAP Development ABAP Development Tools (ADT) is an alternative to the ABAP Workbench. ADT provides the following features: ● A complete new ABAP development experience on top of the Eclipse platform ● An open platform for developing new ABAP-related tools ● A set of open, language-independent, and platform-independent APIs that developers can use to build new custom tools for the ABAP environment SAP GU I Cliient Ec'lipse Client ABAP Development I Tools (ADT) NWASABAP (7.31 SP4 or higher) .--��-.aL���-, ABAP Workbench -���---��-.... Repository Figure 17: ABAP Development Tools — Eclipse Based ABAP Development Benefits of Developing in Eclipse With ABAP Development Tools in Eclipse, you benefit from the usability, speed, and flexibility of Eclipse, while also benefitting from proven ABAP Workbench features. ABAP Development Tools improves developer productivity by offering better refactoring functionality, code completion, auto-insertion, and code templates. It also includes an invaluable Quick Fix feature and is highly navigable. 14 © Copyright. All rights reserved. Lesson: Working with ABAP Development Tools (ADT) ABAP Development Tools allows you to connect to multiple ABAP systems and provides session failover, reducing the impact of lost connections. It also enables cross-platform development by integrating ABAP and non-ABAP development tools in a single, powerful integrated development environment (IDE). The architecture of ABAP Development Tools for SAP NetWeaver is designed to allow developers to use a single Eclipse client, installed locally, that connects to several ABAP backend systems of different releases. This allows developers to control all activities in a central location and helps avoid time-consuming context switches. The client provides a set of standard Eclipse development tools, such as the project explorer for system browsing and search views. Getting Started with ADT • l!fl • Eclipse is a framework • Too.lls for different languages as plugins • Each "Perspective" defines a set of tools .,,,,Gil:,�001E•� l);wa(d!!fd) �maflf"""°' .� 1:1 Jo<o Tn,c ttor.1«hy ,¢>�� 4':.R......-.o i;;1:1,...... � Xm. --+ Choose Perspective 11ABAP11 for ABAP Development Figure 18: Selecting the Perspective Eclipse allows development in many different programming languages. To support this, Eclipse contains different combinations of tools, called Perspectives. If you have ADT installed, you can switch to the ABAP perspective. Choose Window→ Open Perspective→ Other...→ ABAP in the menu bar or choose the Open Perspective button. © Copyright. All rights reserved. 15 Unit 1: Introduction • ARIAP • E chpse -IN'i>rf�,. • AIIAPl'l'09flll'n a.kN Oful!I •• • ABAP Project: Logon to one ABAP System (System ID, Client, User and Password) 1 Favorite Pac kages per ABAP Proj,ect 1 Multip,le ABAP Projects i n one Eclipse Figure 19: Creating a Project When you use ADT, you log on to an SAP back-end system and work directly with its repository objects. In this sense, the development process is exactly the same as when you use the ABAP Workbench, there is no manual check-out and check-in of the objects. An ABAP project serves as a container for the development objects that are stored in a particular ABAP back-end system, and contains the logon parameters for the system logon — System, Client, User, and language. You must be logged on to the system to edit an object. Within the ABAP project, you can access any development object in the repository. In addition, to make it easier to manage objects you can set up favorite packages for each project. Editing Repository Objects in ADT Syntax Check Test (in SAPGUI window) I fi·i·IEY. ,;,, fll, �· Edi �4.1&fHi fE&IF;i•i•F&EH:i•if .JW&lJltiil>�rc1i11:4i -llWIAWl!B:!l· !l•iiiiiiiiiim H=iiH•F,i•Fii!, 5'!oor<h ""'IO<t Ftun "'•·- • - �!'..,j«IE,,plo..,,l::. • � Holp Ji!. "'(i]I v '-' � B � ZME_800_b<�OO-OO_en [2ME, 000, 9C400-00, EN) r:;J'(:c-Ps><k<l9e> • $T.-.P • B\:•oo.GO s a:i ?eC�oo_oo 9 s Activate Fi [ZMEIZBC400_00_HELlO . �---- ----------- --------- ----- ------ S,,,,,.,Hitw� PJ..IU!.HE.TERS: Y!RITE 11\FI TE, pa_ .. ..,,,., TYPE sr.,: ing. H�lJo 110.:-Jd.! •. 1 'Ii llc>', pi,,_�- - ss Sy>lemlh"'Y T abstrirp to quickly navigate 'between editors I objects Double-Click to open in editor -----=========�======-� � Figure 20: Editing Repository Objects 16 © Copyright. All rights reserved. Lesson: Working with ABAP Development Tools (ADT) The Project Explorer provides a hierarchical view of the repository, similar to the navigation area of the ABAP workbench. Under each project, you can maintain a list of favorite packages. By expanding the node System Library, you see a list of all packages. To open a specific repository object in its respective editor, double-click it. The editor is shown on the right side of the ABAP perspective. For each new object, a new tab is added. This simplifies the navigation between editors and objects. • Different Types of Editors Native Eclips,e Editors '9 IZMEJZIIC@III_IL ti Q. [ZMEJ2ilCIIOII_D_ [�EJ2.J:IC4.0t_.- r IZMU:!il'Fll c:1 C] • ,_ --- ---- --- ------------------ ------- -------------- ------- ------------. '..J • Eclipse features :: i;i,e:�rii: llt:'100_�:!J_HZ:t.l.O •••••••••-•••• •••••• ····--··-••••••••••• • Available for some Repository Objects (e.g. Pmgrams, Classes Web Dynpro, etc. ) 'Wi!:IT'!l":tlll!IJ.i.illQll"lllll'. tZ:!IJ•LDr!:. ;wJ!Jff: • Eclipse-like look & feel ·n,uo·. :J;llll!li_illllllol. .!.I Integrated SAP GUI Ediitors O,JVq,_......_.,mo �IZlo'EJ-.M.�I\LQ 11 � 6' • <l eee ,, C 1.IIIM t'lt'ld.Hl D/1pJ�y R.#Port Tr!IIIHai.fi!n • SAP GUI Look & Feel � .. '$''!3 /11,l!!I� .l'l.!100 �oi;JJ1Ul.Q ll!i;.tOiO_O(I -... -. r ..,,, • No new features l!I " ------i tst"«-D (l{J_�J.'l.O r,..., • Used where no native editor is available (e.g. Transactions, Dicti,onary Objects, screens, etc. Figure 21: Native Editors or Integrated SAP GUI Editors There are two kinds of editors in ADT – there is a native Eclipse implementation and an SAP GUI based implementation. In the figure, Native Editors and Integrated SAP GUI Editors, you can see an example of each of the following types: There are two types of editors in the ABAP development tools: ● Editors for which there is a native Eclipse implementation For example, ABAP Editor ● Editors that are displayed in an in-place SAP graphical user interface (GUI) For example, ABAP transaction editor with the classic SAP GUI visualization appearing within the Eclipse environment There is no requirement to use ADT for ABAP Development, and each developer is free to choose whether to use ADT or the classic ABAP Workbench. The functions and features of Eclipse and ADT lend themselves particularly well to object-oriented programming, among these features are various built-in refactoring functions and support for unit testing. There are other tasks to which the ABAP Workbench is better suited — in particular working with module pools and screens. © Copyright. All rights reserved. 17 Unit 1: Introduction Documentation, Installation and Support for ABAP Development Tools GetABAP Development Tools from: SAP Software Downl,oad Center • http:1/service.s.ap.com/swdc SAP Devellopment Tools for Eclipse � SAP OevelopmeAt lools lor EclQl5e HOME ABAP TOOLS CLOUD TOOLS GATEWAY TOOLS This slte allows )'CU to lnslallvarious SIIP CfeVelopme11ttools pacltaoes lor Ed,pse. Note tlll3t some ttols are only avauat,le tor Edjpse Juno but not ret1or Edlpse Kepler. somvare Sit&s • http:1/tools.hana.ondemarid.com Also see SAP Community Network • htt�:l/scn.sap.com/comm11.111ity/abap/ eclipse To install som� or au ol1Mtoo1s 11s�e<1 i:,erow. g�tS'iP HAN1, Stud o oran Edlpse Ins /lllitailNewsom,·.rte �I'll: For S::P HWASlill1iP and E!dlips11Jun� (<l.2). add lil11 URLWlil�ll!l!li!.I.Lil1!.ll..llj • for Eclipse Kepler(4.3). add lile URL.tl.!!IIU!l!�.billi.gj]IW!lill.l!m!DW!i.lil Figure 22: Further Information If you are looking for a local installation of ADT, you can choose from the following sources: ● ● ● 18 SAP Software Download Center (http://service.sap.com/swdc), a part of the SAP Service Marketplace. SAP Development Tools for Eclipse Web site (http://tools.hana.ondemand.com). You can also find other products, such as the SAP HANA studio or the tools for SAP UI5 development on this site. SAP Community Network pages (http://scn.sap.com/community/abap/eclipse and http://scn.sap.com/community/abap/hana). They provide documentation and support on how to install the SAP Development Tools for Eclipse. © Copyright. All rights reserved. Unit 1 Exercise 1 Create a Project, a Package and a Program in ADT Business Example Template: S4D430_INTRO_T1 (Executable Program) Solution: S4D430_INTRO_S1 (Executable Program) Create a new ABAP Project in ADT Open ABAP Development Tools. Create a project for application server S4D and add package DEVS4D430_EXERCISE as a favorite package under this project. 1. Open ABAP Development Tools, that is start Eclipse and open the ABAP perspective. 2. Create a project connected to system S4D. Use client, user ID and password provided by your instructor. 3. Add package HA400_PRIMDB_EXERCISE to the favorites of this project. Create a Package with ADT In your project, create a new development package Z4D430_## (where ## stands for your group number) and add it to the favorite packages in your project. 1. In ADT, create a new development package Z4D430_## (where ## stands for your group number). 2. Add your package Z4D430_## to the favorite packages under your project. Create and Test a Program with ADT In ADT, create a copy of executable program S4D430_INTRO_T1 and place it in your package. De-comment the source code in the program. Perform a syntax check, then activate and execute the program. 1. Create a copy of executable program S4D430_INTRO_T1 (suggested name for the copy: Z##_INTRO, where ## stands for your group number) and place the new program in your package Z4D430_##. 2. In your new program, de-comment the entire commented source code. 3. Perform a syntax check for your program. 4. Activate the program. 5. Perform a test of the program as ABAP application (SAP GUI application) from within ADT. © Copyright. All rights reserved. 19 Unit 1 Solution 1 Create a Project, a Package and a Program in ADT Business Example Template: S4D430_INTRO_T1 (Executable Program) Solution: S4D430_INTRO_S1 (Executable Program) Create a new ABAP Project in ADT Open ABAP Development Tools. Create a project for application server S4D and add package DEVS4D430_EXERCISE as a favorite package under this project. 1. Open ABAP Development Tools, that is start Eclipse and open the ABAP perspective. a) Choose Start→ All Programs→ Eclipse from the Microsoft Windows Start Menu. b) If the Welcome page is open, close it or choose the Workbench link. c) Change to the ABAP perspective using the push button in the upper right-hand corner. 2. Create a project connected to system S4D. Use client, user ID and password provided by your instructor. a) Right-click anywhere in the Project Explorer window on the left and choose New→ ABAP Project. b) Click the Browse button and choose system connection S4D. Press OK followed by Next >. c) Enter client, user and password given to you by your instructor. Choose Finish . 3. Add package HA400_PRIMDB_EXERCISE to the favorites of this project. a) In the Project Explorer, expand the project. Right click Favorite Packages under your project and choose Add a Package.... b) Enter package name DEVS4D430_EXERCISE and press OK. Create a Package with ADT In your project, create a new development package Z4D430_## (where ## stands for your group number) and add it to the favorite packages in your project. 1. In ADT, create a new development package Z4D430_## (where ## stands for your group number). a) In the Project Explorer on the left, right-click your project and choose New→ ABAP Repository Object .... 20 © Copyright. All rights reserved. Lesson: Working with ABAP Development Tools (ADT) b) In the dialog window New ABAP Repository Object expand node Package, choose entry Package and click Next. c) On the next dialog window, enter Z4D430_## (where ## stand for your group number) and choose Next. d) On the next dialog window, enter a Short Description for your package and choose button Continue (Enter). e) On the next dialog window, choose Own Requests to select the prepared transport request. f) Choose Continue (Enter). 2. Add your package Z4D430_## to the favorite packages under your project. a) In the Project Explorer, right click Favorite Packages under your project and choose Add a Package.... b) Enter the name of your package and press OK. Create and Test a Program with ADT In ADT, create a copy of executable program S4D430_INTRO_T1 and place it in your package. De-comment the source code in the program. Perform a syntax check, then activate and execute the program. 1. Create a copy of executable program S4D430_INTRO_T1 (suggested name for the copy: Z##_INTRO, where ## stands for your group number) and place the new program in your package Z4D430_##. a) In the Project Explorer, Expand your favorite package DEVS4D430_EXERCISE. You find the executable program under Source Code Library→ Programs b) Right-click on the template program and choose Duplicate.... c) Enter the name of your package (Z4D430_##) and the name for the new program (Z##INTRO) and choose Next>. 2. In your new program, de-comment the entire commented source code. a) Left-click anywhere in the source code. b) Hit keys Ctrl+a to mark the entire source code. c) Hit keys Ctrl+> to de-comment the entire source code. 3. Perform a syntax check for your program. a) Choose push button Check ABAP Development Object or hit keys Ctrl+F2. 4. Activate the program. a) Choose push button Activate or hit keys Ctrl+F3. 5. Perform a test of the program as ABAP application (SAP GUI application) from within ADT. a) From the menu, choose Run→ Run As→ ABAP Application or hit key F8. © Copyright. All rights reserved. 21 Unit 1: Introduction LESSON SUMMARY You should now be able to: ● 22 Work with ABAP Development Tools © Copyright. All rights reserved. Unit 1 Lesson 3 Analyzing and Using A CDS View LESSON OBJECTIVES After completing this lesson, you will be able to: ● Read a Data Definition ● Use CDS-related Tools in ADT ● Use Open SQL to Read From a CDS View DDL Source SQL View and CDS View DDLSource Dictionary object, contains definition of SOL View and CDS View /:nerated upon tivation I' \. SQLView Dictionary Object, Represents Database Object r .... CDS View Entity Neither in Dictionary nor on Database, Carries more semantic, Figure 23: One DDL Source – Defines Two Objects A CDS View is defined in a DDL Source, which is a new type of repository object. There is no editor for DDL sources in the classical ABAP workbench. This new type of repository object has to be analyzed and developed in ABAP Development Tools in Eclipse. Upon activation of a DDL Source, two objects are created: the SQL View and the CDS View. Neither of them can be edited directly. The SQL View is visible as an object in the ABAP Dictionary where it cannot be edited and only reveals a fraction of the information available in the DDL source. It serves as a representative of the database object. The CDS View carries more semantics than its SQL view. It is not created on the Database and it is not visible in the ABAP Dictionary. It can, however, be consumed via open SQL. The new Open SQL syntax introduced with NW 7.40 SP5 is required to access CDS Views. © Copyright. All rights reserved. 23 Unit 1: Introduction Annotation: @AbapCatalog.sqlViewName: 'S4D430_CARR' define view S4D430,_Carrier as select carrid1 carrname, currcode, url from sear-r Name of �he SQL View Fielld list {comma separated) Name of the CDS View FROM cllause Figure 24: SQL View and CDS View in DDL Source As with conventional database views, the simplest form of a CDS view is a projection – that is, a selection of fields from a single table. The language used is SQL Data Definition Language (DDL), but in an Open SQL form so that the view can be deployed on any database platform. As CDS views are part of Open SQL, notice also that there is no explicit client handling. l l DDL Source -, ./ [ SQL View J SQL View ... , CDSVlew .. CDS View ... Repository Object (Dictionary} • Not found in repository Represents "real" database object • Not known to database Is an ABAP data type • Is an ABAP data type (structure, with client field) , No additional semantics I [ (structure, without a client field) • Additional semantics (Annotations) Figure 25: Difference Between SQL View and CDS View The name of the CDS entity is specified after the DEFINE VIEW statement. It is recommended, though not technically necessary, that the name of the DDL source and the name of the CDS view are identical. The name of the SQL View is specified after the Annotation @ABAPCatalog.sqlViewName. It has to be different from the name of the CDS entity. Like for any Dictionary view, the maximum length is 16 characters. 24 © Copyright. All rights reserved. Lesson: Analyzing and Using A CDS View Annotations @AbapCatalog.sqlViewName: 'S4D430_CARR' @Abapcatalog.compiler.compareF·lter: tr�e @Accesscontrol.authorizat·oncheck: #CHECK @EndUserText.label: 'Demo: Simple Projection' View Annotations Element Annotation before the element define view S40438_cairrier a,s select carrid, carrname; @EndUserText. label: 'Currency Code' currcode� Element Annotation after the element url @<EndUserText. label: 'Homepage' from scarr Enri:ch a definition with metadata Start with character"@" May be related to the complete view (view annotations) or to individual parts (element annotations, parameter annotations. etc.) Are mostly optional (exception: @AbapCatalog. sql.ViewName) Figure 26: Annotations – Some Basic Facts A CDS annotation (or annotation for short) enriches a definition in the ABAP CDS with metadata. An annotation is identified by a simple or structured name after leading character "@" or "@<". Depending on its scope, an annotation can be found in different locations within the CDS Source. View annotations Relate to the view itself and are placed before the define view statement. Element annotations Relate to elements in the field list and can be found before or after the element. [o Hint: Element annotations after the element begin with leading characters "@<" . SAP uses a set of predefined SAP annotations. Most of them are optional. But there is one exception: @AbapCatalog.sqlViewName is mandatory in every CDS View definition. © Copyright. All rights reserved. 25 Unit 1: Introduction CDS-Related Tools in ADT • Navigation from SQL View to DDl Source • Display of SQL CREATE Statement • Active Annotations View • Graphical Editor • Dependency Analyzer • Data Preview I Figure 27: CDS-Related Tools in ADT ABAP Development Tools offers a variety of tools to analyze an existing DDL Source. These tools help to understand a CDS view definition – even when you do not yet know how to read the DDL Source itself. You find most of these tools if you right click the view name (either in the Project Explorer or in the DDL Source text) and go to submenu Open With. Navigation from SQL View to DDL Source " i:I v OEVSAO,:l30(pnty 1 ... dod) S 0E.VS41)4lO_DEMO Care D .ta Suvic!:!li Right-Click the SOL View Choose Open With -> Definition D,�ione,y v. .... ��o· "JI! SdD4lO.,AGC\'� "61 Sr�� DEJ!�::::-EM j� New1Dl�on1eyV.ew > ffl > IEI: H'A4(i(I ) 19 • Op•n I-IA400_(0l�_DE C'bl+5hilt•G i. .. g;,0u1r !::I An <Mli�i<.,ot ov•if_.br,. I Shor·•Linl<.. A<ti,,,a•:c: II, Che119eP•d:.,geAi;:ignment Ron A< Ocbu,gA, Poofir.ecA< _. U..lo<k Ct.t•U Synducn;,ow,th HANA R.opo,;;ta,y Add llookmaoJ:. .• Figure 28: Navigation from SQL View to CDS View If you have located an SQL View and want to know how it is defined, right-click the SQL View in the Project Explorer and choose Open With→ Definition. 26 © Copyright. All rights reserved. Lesson: Analyzing and Using A CDS View Display SQL Create Statement ,1..tiapC.. �alo<,.aql\'.i.e·�I""'"' •stD!!O Cil:RJ.• @.tJJepCat:alc:io .c:o- :t..lc:: .c:ciccpa::er11t::;;::: t:'u.� ��<;:<1:lll!Con1ao1.01,1i:;J.o�hai:; o:iel.c<:i<': tCl'l:!!CK 4 SEndU�.,,.r.,xe .lab.,l: • llieo,o, S!.J<pl" Pro;tec:cton • <ll!lf!M V"l"W S!<H30_C'a"'"'-'""' ·Revell Filo S.ve Q ��%;.�::\.{��. smcr ===:=�=: ·='IR·,·c;,_gJUD", -�<\?:- '"b"RL •sa,n,,• "SC:Ai,ii;" !'!!;OM ) Figure 29: Display SQL Create Statement When you activate a DDL Source, the development environment sends an SQL statement to the database to create the SQL View. You can display this SQL CREATE statement as follows: 1. Right-click anywhere in the DDL Source. 2. Choose Show SQL CREATE Statement. The SQL Create Statement is displayed in a dialog window (popup). Like with any native SQL statement, details of the CREATE statement will depend on the type of database used by the system. © Copyright. All rights reserved. 27 Unit 1: Introduction Active Annotations View ..., "It OEVS:O,l:IOl..-•r'!l)·lo. 111•d �S!�.CEMO Right-Click the '" o ..,s....... v i.OmOtM....,., ii)�N('l... r�vr,,uE t, mwm • .,. !�;'" mw :.. ,,"Iii--r1@r?.CAPMR o.... s.. ,1,+ - 1 Vit.WS r,ll�_A(l(YltEY �SIIM.30.BOOl::,IGO' r,IISIIM:!O_C_ > ill �,....,,;t,ot.11111_.;ii...lliili'l.l!i!!!l.!.ii-__ � v..-o��� :i> �� 0.p<nde"')' ""'I)," > Ot<�i<lon;i D Gr�Killl&il:or > II! ,,-oecos.E>ttc1SE > itlflrir:0..t:A�t-5 >ll�ml1b,a� ).,,,,., !3 .. �,:, :., v'!ll<ol«• > Oh"' ) =g sdtdlm o.,,w....io,. Choose Open With -> Active Annotations .. I Or,c,, ) ll!lll'IS'OOO. v N'... lkl;plkm.. >lll>WIJC � :;:�;. DDL Source r... x � . � .,. "-�·' lltl ... Oll<t• wtW1\ere-idl-dllri.,,N Opens in Tab below the editor �, Clrl.+itiafh(i. l@ . ..... -......,tll ..,, -=-,, .... s.__ I • i''!, i\ A<tir.rt" °""JoPiC"'9"AA'9""'"" � 430_ca,,;,.,, .. ---�·Prcfilc:ilt5, c,a.11 Cbl,/dt,C > Annottte:d[lan.fflts Anno'lil'lioniYllue T"""'t<dT«t Si:4,l;W,Cimn ..,w)�iru'l�ici11i Figure 30: Active Annotations View (1) The Active Annotations view summarizes the semantic information of the CDS View and of its view fields. This is not restricted to annotations alone. It also lists semantic information that is taken (inherited) from other CDS Views or from DB table definitions and data elements. Open the Active Annotations view as follows: 1. Right-click DDL Source. (Either in the editor window or in the Project Explorer.) 2. Choose Open With→ Active Annotations. The Active Annotations view is displayed in a dedicated tab in the tabstrip below the editor window. 28 © Copyright. All rights reserved. Lesson: Analyzing and Using A CDS View Cl P11>p.. b •.., . ., •:. Pr<lbL 11w1o. 'OJ ,...i. ... @ ,..m,. t3 � ...i. ... Cl ftt<L. . ,,.,_ II MAP.. ,, s.. rch ::a P""J... A.&AI'•• .,,. Active Annotaaons for Entity S4d4SO_Garrier • 5..t«tion l s, Annot,icd IEl<m<nt, S4.i4JO_,.rri., > � En.� umot•tiom .... (,trrid qui< me Ai,t ... (od• Aid .... ID labfl hl!ad,ng l;EndUfOrloot qui<ldmc Aid ..� Ai,t ... label lw,ad,r,g v II, 5CAiAA 5C.AllR ,CARR !IRR Mfflt '>/RR Ai�IIIW! tunmdi!! l;EndU<erl..i 1.cc,1, q....:klmc label Ai11I� Label for view field CARRIO is inherited from DB table SCARR Label for view field CARRIO originates from data element Figure 31: Active Annotations View (2) In the example above, you can see that field carrid of CDS View S4d430_Carrier has a label “Airline” that is not defined in the corresponding DDL source. This label is taken (=inherited) from the source field in SCARR and originates from data element S_CARRID with which this source field is typed. Graphical Editor 0£\!S40t30 (p.artly looch:dJ .., $ [)EVS,l.D4JO.mMO CorcC 1,eScfvicff Data,Di!linitions €J S4l)430_AGENCV_wiiM_Rf'l[NUE Oemo: Trov�i Ag,nry w,:h TOIDI Rev,nu� (!l �0430.BOO](JNCJ_AND.A.GENCI' Dicti::;30_CARR!EII m � Sa!D4JO_ACJC'l'REV o� ... 'J!,l S41)4lO_BOO(_AGI Cld+AII+�) Op,en,nProj«I lllill,r,1,1inn Copy Ctrl•C ,C Odeh! D,ltt• £::. GttWlm•·u.odl.ill!. .. Act...,ti,;n Leg @ Aet:M! Annot&tion.s 1',!..,,0rttOefimtion Dupli<•te. .. llitwl $h1rclinli;. .. 1 _...._ ,, Sold430_Carrlc,r • Cffl1cl III . .... III ClrfNJ:'JII cvrroooe, _ n "'""'" ... Figure 32: Graphical Editor for CDS Views The Graphical Editor for CDS Views is another useful tool that supports you in analyzing complicated DDL Sources. It not only shows how the given CDS View depends on other © Copyright. All rights reserved. 29 Unit 1: Introduction repository objects, it also provides a graphical representation of the projection list and displays details about aggregations, filters, etc. Open a given DDL Source in the Graphical Editor as follows: 1. Right-click DDL Source. (Either in the editor window or in the Project Explorer). 2. Choose Open With→ Graphical Editor. The Graphical Editor opens in a new tab in the editor window. Dependency Analyzer OEVS40430 (p,1utty IQ<lded) " it 0EV541)430J)EMO C�llott�;<,i,: D1tit Odinltiom (!J s,l[143(1.,AGENC'l'_Y.IITl-l_ll!MNU! O.ma Tn,.�IAg•nty .. �n Toi..,rR..,.nu• (iJ s.lDA30.BOOKING_AND.)IG[NCY • S.:D43IOCAMIE!I: Dictieo,ny o.-e:-i.-- - (B Now o.i� 0. ,nition Vi� llupli<�te. .. �$11)43(1.}l,GC:Vl!EV � S-![143(1_800)(.AOC' O?m 0 ..,,nP<Q- I '111 s.lDA.W_CAR!I o..tl!'Prarii!W O?mWith A<t;...;,1ion Log Copy @ AflrJ� Anr.o ..ation.s lloli!b! - Annot.tion Propo�otion , (!J S.:IMJO.CIJ,TOMER "" Sh�•� !int<. .. t.'I (A.l"I...IIM t""r1ei"nul!':!Q, (l) 11:QGJ S.:D430_C.A . ER Jo IKQGI S40l30.Cil.!tRll:R ll SQL Depemlem:y Tree SQL Relation Objro l)'P• Entify·N,m•· lnt,ba« ObjKI Figure 33: Dependency Analyzer For more sophisticated DDL Sources, it can be quite difficult to find the actual source of the data. This becomes particularly true if a CDS View reads from several other objects and if these other objects are not just database tables but CDS Views that again depend on other objects. The Dependency Analyzer offers a simplified view by focusing on the dependancy tree and disregarding the rest. Open a given DDL Source in the Dependency Analyzer as follows: 1. Right-click DDL Source. (Either in the editor window or in the Project Explorer.) 2. Choose Open With→ Dependency Analyzer. The Dependency Analyzer opens in a new tab in the editor window. 30 © Copyright. All rights reserved. Lesson: Analyzing and Using A CDS View Data Preview 'It v DEV'.11)4:JO p.,rtf,load...tJ " $ DEvS-ID430_0lMO Doti Oolin�iorn, @ 54D430.).GEJNC'(l'l'lTH..JREVENLIE Demo: T,a....r A;tnr:y » th Taal�"""' • S4D430_900�1111G_ANO_AG!;NC, I 54D430 (.e.JIRIER � (D N!WD•t• O..tinition Oicii,i>ntty o.p1ic-itt. .. Vi� 111', SilD430_AGCYlt!' "jl\ 54D430_800K,,A QpSI �pminProjc<t OpSIWith CoP'.I' llttm Amnot,lions C!lete Annotation Prop1gation ,. llopend�An,1per D FS Gr•phi><,I Edhor Figure 34: Data Preview for CDS Views (1) The Data Preview tool allows you to analyze the data returned by a CDS View without the need to implement a SELECT statement yourself. In that sense, it is very similar to the Data Browser tool of the classical ABAP workbench (transaction code SE16). Open the Data Preview for a given DDL Source as follows: 1. Right-click DDL Source. (Either in the editor window or in the Project Explorer.) 2. Choose Open With→ Data Preview. The Data Preview opens in a new tab in the editor window. • IKQGJ So1D430_CARR.IER � [KQGI 540430_CAll:RIER t-l � fJj �30.CAll:RIER t cu«coele AA AB Amtii,.an Airlin-. us£I AirB•rlin EUR AC ,r,,;,c,n�, AF IJ.hfrillKC Alit1IL• CAO EUR EUE!: Gl!P Al. BA co B,;wh A;rw,,.. Co•tinlt'LtJIAi, ... i"lll ...- .. .,.:..1....,... hlipo,lfwhdpO//whllp://w._ htlp,lfw.� hdpO//Whttpo//W,- �ttp:llw... USE) 11f!, Jllton � JI S11l'!�C)_CAAIIH:'.R-CARII.ID, 34 ll4 30_CARRI E:EI-CARHlliO!E1 S41l451)_CAJl.1Uc:ll;<UP;RCOOE, S4 lli 3Cl_CARRI !:R�URL FIIOH I"' 34 ll4 30_CARRH'.R I x Nuon ,,.. of Entri� N\Irnl!or oi �lies thM m .. 1 lh• soloction <rimi.., 13 OK Figure 35: Data Preview for CDS Views (2) The Data Preview lists the first n entries of the specified view or table. N is set to 100 by default but can you can increase or decrease this value manually (setting Max.Rows). © Copyright. All rights reserved. 31 Unit 1: Introduction The toolbar on the Raw Data tab offers additional functions: Add filter Opens a dialog to enter selection criteria Number of Entries Displays the total number of rows in the table/view that match the selection criteria SQL Console Opens a new editor window with a SELECT statement for this view/table. You can edit this statement, execute it, and display the result to run a more sophisticated ad-hoc analysis of the data. A New Syntax for Open SQL Classical Syntax (Before NW 7 .40 SP05) SELECT carrid connid fl.date SUM( payment.sum I currency FROM sflight INTO TABLE gt_flights WHERE fldate > sy-datum GROUP BY carrid co.nnid f'ldate currency ORDER BY carrid connid. New Syntax Rules in NW 7.40 SELE.C'T c:arrid, c:onnid, fl.date, SUM( paymentsum ) , c:u.rrenc:y FROM sflight INTO TABLE @gt_flights WHERE fldate > @sy-datum Variables must be escaped with the @symbol GROUP BY carrid, connid, fl.date, cu.rrency ORDER BY carrid, connid. Column lists are now commaseparated I Figure 36: New Open SQL Syntax in NW 7.40 As off AS ABAP 7.40 SP05, ABAP Open SQL offers a large variety of new features. In order to make this possible, it was necessary to re-design the Syntax of Open SQL. The new Syntax Rules as off NW 7.40 are as follows: ● ● Comma-separated column lists — to allow for sophisticated expressions Mandatory escape character @ for ABAP data objects — to ensure a clear distinction between database objects (tables and table columns) and objects of the ABAP program (variables and constants). Regarding the usage of old syntax and new syntax, the following rules apply: ● ● ● 32 If an SQL statement uses the new syntax, it has to use it consequently. An SQL statement may use the old syntax as long as it contains only features that were already available before NW 7.40 SP05 (compatibility mode). As soon as an SQL statement contains a single feature that was introduced in or after NW 7.40 SP05, it has to follow the new syntax rules (strict mode). © Copyright. All rights reserved. Lesson: Analyzing and Using A CDS View I» Note: CDS Views were introduced in NW 7.40 SP05. The new syntax is mandatory when using a CDS View in a SELECT statement. Classical Sequence of Clauses SELECT carrid connid f1date SUM( paymentsum) eurrency FROM sflight INTO TABL,E gt_flights WHERE fldate > sy-datwn GROUP BY carrid connid f1date currency ORDER. SY carrid connid. Nlew Syntax Rules in NIW 7. 50 SELECT FROM clause before field list Keyword FIELDS to introduce Field list FROM sfligh t FIEWS carrid, connid, fldate, SUN( paymentsum ), currency WHERE fldate > @sy-datum GROUP a:y carrid, connid, fldate, c.urrency ORDER iB.'f carrid, connid INTO at the IN'FO TABLE @gt_flights. very end (> NW 7.40) Figure 37: New Open SQL Syntax in NW 7.50 AS ABAP 7.50 brought more new features to Open SQL and, along with those, additional changes to the syntax. Most important, the sequence of clauses was changed as follows: ● ● Field list after FROM clause, introduced by new key word FIELDS — to allow for autocompletion when editing the field list INTO clause at the very end of the statement — to support the UNION of several SELECT statements with one INTO clause Regarding the usage of this new syntax, the following rules apply: ● ● An SQL statement may use the old sequence of clauses as long as it contains only features that were available before NW 7.50. As soon as an SQL statement contains a single feature that was introduced in or after NW 7.50, it has to use the new sequence of clauses (strict mode for NW 7.50). Note: Some features of CDS were first introduced in NW 7.50. If the definition of a CDS View contains such a feature, any SELECT statement reading from this CDS View has to use the new sequence of clauses. © Copyright. All rights reserved. 33 Unit 1: Introduction One DDL Source – Two Objects to Read from DDL Source SQLView SELECT ... FROM <SQL View name> CDS View Entity OR ? SELECT .... FROM <CDS View name> Use of SOL View is ... Use of CDS View is ... • Not recomrnendedl • Recommended! • Supported with classical and new syntax • Only possible with new syntax • Obsolete since NW 7 .50 • Not fully supported before Rel. NW 7.50 (e.g.in joins with DB tables) Figure 38: One DDL Source – Two Objects to Read From To use CDS in ABAP Open SQL, you can read either from the SQL View or from the CDS View. This might be a bit surprising because only the SQL View exists physically on the database. But if you read from the CDS View, the database interface will replace the name of the CDS View with the name of the corresponding SQL View when translating your Open SQL statement into a native SQL statement. This is the recommended way to access CDS views in ABAP. Alternatively, it is also possible to read from the SQL View directly. This was never recommended and became obsolete with NW 7.50. Note: In systems with release NW 7.40, CDS Views are not yet fully supported in Open SQL. Reading from the SQL View is then needed as a workaround. One example is the join of a CDS View with a database table. This is possible in NW 7.50 or higher. The workaround in NW 7.40 is a join of the corresponding SQL View with the database table. 34 © Copyright. All rights reserved. Unit 1 Exercise 2 Analyze a CDS View and Use It in Open SQL Business Example Template: S4D430_INTRO_S1 (Executable Program) Solution: S4D430_INTRO_S2 (Executable Program) Search for a DDL SQL View and Navigate to the Definition In ABAP Development Tools, search for SQL View S4D430_CUSTREV. Open the SQL View. Then navigate to the corresponding data definition (DDL Source). 1. In ABAP Development Tools, start a search for the ABAP repository object with name S4D430_CUSTREV. 2. Open the corresponding package in the project explorer on the left. 3. Open the corresponding data definition (DDL Source). Hint: Use the context menu in the project explorer to navigate to the view’s definition. What is the name of the DDL Source? What is the name of the CDS View? Analyze the CDS View with Different ADT Tools 1. Open the DDL Source with the Dependency Analyzer. © Copyright. All rights reserved. 35 Unit 1: Introduction Which database tables do the data come from? 2. Open the DDL Source in the Graphical Editor. 3. Open the Active Annotations view for the DDL Source. Open Data Preview for the CDS View 1. Use the Data Preview tool to display the raw data for this view. 2. Set a filter to display only flight customers located in Germany. Implement a SELECT Statement That Reads Data from the SQL View Use the SQL View as ABAP data type and as source for a SELECT statement. Note: The use of SQL Views in ABAP programs is obsolete as of AS ABAP 7.50. We do it here only for didactical reasons. SAP recommends to access the CDS Views only (see next part of this exercise). 1. Create a copy of your solution of the previous exercise in your package (suggested name: Z##_OPEN_SQL, where ## is your group number). Alternatively, you can copy program S4D430_INTRO_S1. 2. Change the definition of local data type ty_t_customers. Replace line type SCUSTOM with SQL View S4D430_CUSTREV. 3. Change the SELECT statement. In the FROM clause, replace transparent table SCUSTOM with SQL View S4D430_CUSTREV. 4. Activate and test your program. Implement a SELECT Statement That Reads Data From the CDS View Use the CDS Viewas View ABAP data type and as source for a SELECT statement. 1. Change the definition of local data type ty_t_customers again. This time, replace SQL View name S4D430_CUSTREV with the corresponding CDS View S4D430_Customer_With_Revenue. 2. Check for possible syntax errors. Why are SQL View and CDS View not compatible? 3. Adjust the SELECT statement to make it read data from the CDS View. 36 © Copyright. All rights reserved. Lesson: Analyzing and Using A CDS View Why do you get syntax errors that requests a “@” before data object gt_customers? 4. Adjust the SELECT statement according to the new syntax rules as of Release 7.40: Add colons between column names and place character “@” in front of all ABAP data objects. 5. Activate and test your program. © Copyright. All rights reserved. 37 Unit 1 Solution 2 Analyze a CDS View and Use It in Open SQL Business Example Template: S4D430_INTRO_S1 (Executable Program) Solution: S4D430_INTRO_S2 (Executable Program) Search for a DDL SQL View and Navigate to the Definition In ABAP Development Tools, search for SQL View S4D430_CUSTREV. Open the SQL View. Then navigate to the corresponding data definition (DDL Source). 1. In ABAP Development Tools, start a search for the ABAP repository object with name S4D430_CUSTREV. a) Choose Search from the menu or hit keys Ctrl+H. b) On the ABAP Object Search tab, enter S4D430_CUSTREV in field Object name and choose Search. 2. Open the corresponding package in the project explorer on the left. a) On the Search tab below the editor window, double-click the found repository object. This will open the SQL View in the ABAP Dictionary tool and will expand package DEVS4D430_EXERCISE in the Project Exporer. 3. Open the corresponding data definition (DDL Source). Hint: Use the context menu in the project explorer to navigate to the view’s definition. a) In the Project Explorer, right-click the SQL View and choose Open With→ Definition. What is the name of the DDL Source? S40430_CUSTOMER_WITH REVENUE (all upper case) What is the name of the CDS View? S4d430 Customer With Revenue (mixture of upper and lower case) Analyze the CDS View with Different ADT Tools 38 © Copyright. All rights reserved. Lesson: Analyzing and Using A CDS View 1. Open the DDL Source with the Dependency Analyzer. a) Right-click anywhere in the source code of the DDL Source and choose Open With→ Dependency Analyzer. Which database tables do the data come from? SCUSTOM and SBOOK 2. Open the DDL Source in the Graphical Editor. a) Right-click anywhere in the source code of the DDL Source and choose Open With→ Graphical Editor. 3. Open the Active Annotations view for the DDL Source. a) Right-click anywhere in the source code of the DDL Source and choose Open With→ Active Annotations. Open Data Preview for the CDS View 1. Use the Data Preview tool to display the raw data for this view. a) Right-click anywhere in the source code of the DDL Source and choose Open With→ Data Preview. 2. Set a filter to display only flight customers located in Germany. a) From the toolbar within Data Preview, choose Add Filter. b) From the dropdow list, choose field Country c) Enter filter value DE and choose Enter. Implement a SELECT Statement That Reads Data from the SQL View Use the SQL View as ABAP data type and as source for a SELECT statement. Note: The use of SQL Views in ABAP programs is obsolete as of AS ABAP 7.50. We do it here only for didactical reasons. SAP recommends to access the CDS Views only (see next part of this exercise). 1. Create a copy of your solution of the previous exercise in your package (suggested name: Z##_OPEN_SQL, where ## is your group number). Alternatively, you can copy program S4D430_INTRO_S1. a) See the corresponding step in the previous exercise. 2. Change the definition of local data type ty_t_customers. Replace line type SCUSTOM with SQL ViewS4D430_CUSTREV. View a) See source code extract from the model solution. 3. Change the SELECT statement. In the FROM clause, replace transparent table SCUSTOM with SQL View S4D430_CUSTREV. a) See source code extract from the model solution. 4. Activate and test your program. a) See the corresponding step in the previous exercise. © Copyright. All rights reserved. 39 Unit 1: Introduction Implement a SELECT Statement That Reads Data From the CDS View Use the CDS Viewas View ABAP data type and as source for a SELECT statement. 1. Change the definition of local data type ty_t_customers again. This time, replace SQL View name S4D430_CUSTREV with the corresponding CDS View S4D430_Customer_With_Revenue. a) See source code extract from the model solution. 2. Check for possible syntax errors. a) Open the Problems tab on the tabstrip below the editor. Why are SQL View and CDS View not compatible? The SQL View has a client field (MANDT) which is missing from the CDS View. 3. Adjust the SELECT statement to make it read data from the CDS View. a) See source code extract from the model solution. Why do you get syntax errors that requests a “@” before data object gt_customers? The new syntax for Open SQL is mandatory when you use a CDS View in the FROM clause. 4. Adjust the SELECT statement according to the new syntax rules as of Release 7.40: Add colons between column names and place character “@” in front of all ABAP data objects. a) See source code extract from the model solution. 5. Activate and test your program. a) Perform this step as you did in the previous exercise. Program S4D430_INTRO_S2 REPORT s4d430_intro_s2. *TYPES ty_t_customers TYPE STANDARD TABLE OF scustom * WITH NON-UNIQUE KEY id. *TYPES ty_t_customers TYPE STANDARD TABLE OF S4D430_CUSTREV * WITH NON-UNIQUE KEY id. TYPES ty_t_customers TYPE STANDARD TABLE OF s4d430_customer_with_revenue WITH NON-UNIQUE KEY id. DATA gt_customers TYPE ty_t_customers. * ALV Processing DATA go_salv TYPE REF TO cl_salv_table. DATA gx_excp TYPE REF TO cx_salv_error. * Selection Screen PARAMETERS pa_city TYPE s_city DEFAULT 'New York' LOWER CASE. START-OF-SELECTION. 40 © Copyright. All rights reserved. Lesson: Analyzing and Using A CDS View * Data Retrieval **************************************************************** * * * * SELECT * FROM scustom INTO TABLE gt_customers WHERE city = pa_city order by city name. * Option 1: Read from the SQL View (Obsolete as off Rel. 7.50) *************************************************************** * SELECT * FROM s4d430_custrev * INTO TABLE gt_customers * WHERE city = pa_city * order by city name. * Option 2: Read from the CDS View (Recommended) **************************************************************** SELECT * FROM s4d430_customer_with_revenue INTO TABLE @gt_customers WHERE city = @pa_city ORDER BY city, name. * output **************************************************************** TRY. cl_salv_table=>factory( IMPORTING r_salv_table = go_salv CHANGING t_table = gt_customers ). go_salv->display( ). CATCH cx_salv_error INTO gx_excp. " MESSAGE gx_excp TYPE 'I'. ENDTRY. © Copyright. All rights reserved. 41 Unit 1: Introduction LESSON SUMMARY You should now be able to: 42 ● Read a Data Definition ● Use CDS-related Tools in ADT ● Use Open SQL to Read From a CDS View © Copyright. All rights reserved. UNIT 2 Basic SQL Features in CDS Views Lesson 1 Define a Simple CDS View Exercise 3: Define a Simple CDS View 44 51 Lesson 2 Creating a CDS View with Inner Join, Projection, and Selection Exercise 4: Define a CDS View That Reflects a Database View 56 61 Lesson 3 Using ABAP Annotations in CDS Views Exercise 5: Use Annotations in DDL Sources 67 73 UNIT OBJECTIVES ● Create a DDL Source ● Understand the DDL Syntax Rules ● Define a CDS View That Reflects a Database View ● Use ABAP Annotations in CDS Views ● Work with Translatable Texts in CDS © Copyright. All rights reserved. 43 Unit 2 Lesson 1 Define a Simple CDS View LESSON OBJECTIVES After completing this lesson, you will be able to: ● Create a DDL Source ● Understand the DDL Syntax Rules Create a new DDL Source Right-Click the Project l(QG_800_ni-,.n?,c. Ar > r � 1,�_ . _ N " '__,������������___. IJ.\pl,cal•.- SIMP • MANNE&\'I' BCAOO !B 8C41ll > BC41l.2 > !B 01so.r,,w Go Into x Ri!!move from Contm !B=l!).130(p111J,I::. lmpOJlt... HAAOO_COLOO_DE &;pon •• ) �'IO:::cos_ou,i Rel""" ) Iii,, Co<c c,1 , ! Clo•• Unrelated Prajem > E6 10m1 ) > IB > Di<tion,1ry WDlCOS_E.x!:R. �lete Otlet� rs � , i!l:o. ... ____ .... _,,: P,oj«t. .. 1 ABAl:'ll�oi:yl•tt-- L.! rn. ,Foldu (tfl.,..AJt,. Shrft.., Dolhn c1o�l'rojo<1 (!) ABAPClm • rs ABAF' Funai on Gro ;p G ABAP Function Modul� 0 Cl AB.Al'lnt.erf0<e ABI\P Pro�r•m v,tid•t• c.. ,.0..1.s.. ... ) .i. Systo,nl rory 575_1)01.mann•ct.en [57S. C<>mp1>r•W"rth Y13J)OO_rn•nn..t_,n IY13. q; SQL ccn..,I• flatort from �.:,,;ii Hi>t<>ry•. O:thu•. CUl+N Figure 39: Create New DDL Source (1) To create a new DDL Source, proceed as follows: 1. Right-click on your project in the Project Explorer. 2. Choose New→ ABAP Repository Object … 44 © Copyright. All rights reserved. Lesson: Define a Simple CDS View r"' Now ABAP R.op<><�'OJ)' Objttt D x 1 ASAP· R�jHi$ito;y Object c, ..tt ,n ASAP 11:tpof ory Objed froject: ! KQG.800.m• nut.on d,1�del Cl Oato Oefinilio,r, Crc•I• • D,11 Ddiniti,m E,ojoct: • ----------------------t Ptcbge; · "'-----------' ' Add 10 1¥••1• pa.,k.og., ll_6Cription:• --------------------1 rm:: .., Oliginal�nguago: .... Figure 40: Create New DDL Source (2) 3. From the list, choose Core Data Services→ Data Definitions [o Hint: You can use the input field below Project to type a search term, e.g. "data". 4. Choose Next. 5. Enter the name of an (existing) package, and a name and description for the new DDL Source. © Copyright. All rights reserved. 45 Unit 2: Basic SQL Features in CDS Views OEVS40!.0 (p1rtt,, l�d«ll " $ DEVS4D430.DEMO .c WD IM 1 S i x (J Ntw Dal• Ddinition Oll!a DBfinition I CrieateaiDi!lllDefini1ion Right-Click Data Definitions under package Br-e... t,me:a• jlH<riplion:• Orfqin' 1/jngutgc: L.E_II ___. Figure 41: Shortcut (If Package Already Contains a DDL Source) If your package already contains a DDL Source, you can use the following shortcut: 1. In the Project Explorer, expand subnode Core Data Services→ Data Definitions of the favorite package. 2. Right-click Data Definitions and choose New Data Definition. DDL Source Templates Ill o x Templi!.te ... klt<t ene of the .w;il;blc lempl,ld. ll'U:Vit'w' (JjD•lin•ViowYoithJoin m Deline View will, A$...,<ililrM Dd'ioe View ..ill, P•rjl!'l<l,n BJEximdVi"" (!I Define Tal>I• Function wilh Pa,•metm iAba,i:,C t.o.lcv.:,<1lVi.,,..N="; "S(o<1l """"' c.�ef' @Al>o.l'Co.u,ioo. ecrepu .... ec,tpo.re!'1l;er: ;'.-ue 8,Acee,:s:sCocti'C-rol. auit.horl.%.aoel.onChect:: @,E::LdUs�rTe:x.ic.. h.bl!l: ICHE.CK • S �ddl_s:eiu:rce:_dll!:sc�1.p:t.1cn) • <hot:1.m, vi."" Sl<lcll ,.:. .. .-o:., nm.i: "cl1t.a1>hl Hc1:1r,,orJ - - - 4:,; -l!ele,;:, :...,,. S[<l11n. oc,i..-o:" nL"<"I - - I c.n�,I Figure 42: DDL Source Templates During DDL Source Creation When you create a new DDL, you can create a blank editor page. Alternatively, you can use one of several available templates as a starting point. 46 © Copyright. All rights reserved. Lesson: Define a Simple CDS View Usually, a respective dialog appears after you assigned the new DDL Source to your ABAP workbench request. But you can always return to the template selection later in the editing process. "IK i.AballCa"GailaQI. aql V.1.ewHame. � 9Accc.o.oCc,nercl 11ue:,or1:t4Ue>nCbcck tCl!tC!( 1 Deom:i. Tz-avel AQ�nc:y' tlne; V1ev S.1Jl'.M30_.AQ�nc:,i· n.a Sil!i1.ect :rrcs C1a&a_;5.ourcl!_naJDI!:' f 8LndU.sezTex,:. .la.be1 • s 6 07 ' aql v .iew name• ,eAb<lpCa ,•1011. """"'l.lo:r comp,oro:P'11,cr- true - - If Nome DataOefiilitiOII " 'll Dota Oelinition [croaoon) Bi delineT1bl�un�ionl'l�hli'1r1met� t dd"m!Viow L m def"meVi��(>(iltion D..tinoView �imt Vitw wi�h A:$.$O�i:ttion1 i,i dd"m!ViowWithlcin D..tino \li.wwith loir, Bi define'l"ow €J•••tondVt..., (>�;·� V.ow w�h p E>und\C,-, ol'IP�l"'elffl fJMe.«f$ Figure 43: DDL Source Templates During Editing To choose a template later, go to the Templates tab in the tabstrip below the editor window. I» Note: You may define your own templates in the editor preferences. Go to Window→ Preferences and search for “Data Definition Templates”. © Copyright. All rights reserved. 47 Unit 2: Basic SQL Features in CDS Views Syntax Rules • Keywords: All uppercase, alll lowercase, or lowercase with uppercase iniitiial lette.r. No mixed uppercase and lowercase Allowed: SELECT, select, Select Not alllowed: Select, seleCT. • Names: Not case-sensitive. Max. 30 characters. Literals: Numeric literals always in full, with decimal point if necessary. Allowed: 1, 2.0, or 0.5. Not allowed: .5, 1,3 Character !literals enclosed in single quotations marks I'), 'LH', '00001' Comments: Explicit end: enclosed by /" and --1 Rest of line: two forward slashes (II) • Separators: Statements can be closed usiing a semicolon (;). This is optional. • Prntected Words: Certain keywords cannot be used as self-defined names J Figure 44: General DDL Syntax Rules The general syntax rules inside DDL Sources are as follows: 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 because, for the moment, one piece of CDS source code can currently only contain a single statement. Protected Words Certain keywords are protected and cannot be used as self-defined names. 48 © Copyright. All rights reserved. Lesson: Define a Simple CDS View Standard SOL ( After keyword SELECT ) @AbapCatalog.sqlViewName: '54D430_CARR' define view S4D430_Carrier as select carrid, carr-nama, curr-eeda, url from scarr CDS DDL Style,( After FROM-Clause, enclosed in,,{" and ,.}" ) @AbapCatalog.sqlViewName: 'S4D430_CARR' define view S4D4:30_:Carrier as select from scarr car rid, carrname., cur re ode, url } I Figure 45: Variants for Specifying the Element List When you define a CDS View, you have two options to specify the element list (that is the field list in the simplest case): 1. After keyword SELECT, before keyword FROM. This corresponds to SQL standard syntax. 2. Enclosed in characters "{" and "}", after the FROM clause of the SELECT statement This is a speciality of to CDS Syntax and allows for improved auto-completion support. It is recommended to use second, CDS-specific syntax. Note: Regarding auto-completion support, the CDS-specific syntax corresponds to addition FIELDS in Open SQL. Naming Rules and Recommendations Regarding the names of DDL Source, CDS Entity, and SQL View, there are some hard rules enforced by the development tools, and mere recommendations that are intended to increase clearness and readability. © Copyright. All rights reserved. 49 Unit 2: Basic SQL Features in CDS Views DDL Source name: • Max. 30 Characters • Unique throughout the system (Customer narnespacel) Always Upper-Case CDS View name: • • • • • Max 30 Characters Unique throughout the system (Customer namespace!) Unique within AB.AP Dictionary (global ABAP data type) Not Case-sensitive Can be different from DDL Source name (not rscommendedl) SQL View name: • Max 16 Characters (Standard Diictionary Object) • Unique throughout the system (Customer narnespacel) Unique within .ABAP Dictionary (global ABAP data type) • Not Case-sensitive (will be translated to Upper Case) Different from CDS View name J 50 Figure 46: Naming Rules and Recommendations © Copyright. All rights reserved. Unit 2 Exercise 3 Define a Simple CDS View Business Example Template: none Solution: S4D430_SIMPLE (DDL Source) Create a new DDL Source 1. In your own Package, create a new DDL Source (suggested name: Z##_SIMPLE, where ## stands for your group number). Choose template defineView to generate the definition statement and some standard annotations. 2. If the tool did not ask for the template, go to the templates tab on the tabstrip below the editor and choose the template there. 3. In the respective Annotation, enter a name for the SQL View that is to be generated (suggested name: Z##SIMPLE). 4. Would it be possible to specify the same name for CDS View and SQL View? 5. What is the maximum length for the name of the SQL View? Implement the DDL Source 1. In the FROM clause of the SELECT statement, specify database table SBOOK. 2. Edit the field list of the SELECT Statement. Start with the complete key of table SBOOK, except for the client field. Add the fields for flight class, booking price in foreign currency (with the corresponding currency key), weight of luggage (with corresponding weight unit), booking date, travel agency number, counter number and customer number. Hint: To enter the field names, make use of the editor’s auto-completion capabilities! © Copyright. All rights reserved. 51 Unit 2: Basic SQL Features in CDS Views Activate the DDL Source and Test the Result 1. Perform a syntax check. Then activate the DDL Source. 2. In the Project Explorer window, refresh the object list for your package and locate the DB view that has been created. 3. Open the Data Preview for your CDS View. 52 © Copyright. All rights reserved. Unit 2 Solution 3 Define a Simple CDS View Business Example Template: none Solution: S4D430_SIMPLE (DDL Source) Create a new DDL Source 1. In your own Package, create a new DDL Source (suggested name: Z##_SIMPLE, where ## stands for your group number). Choose template defineView to generate the definition statement and some standard annotations. a) In the ABAP perspective of Eclipse, right-click on your project and choose New → Other ABAP Repository Object. b) On the next window, choose Core Data Services→ Data Definition. c) Enter the name of your package, a name, and a short description for the new object, and choose Next. d) If the tool asks for a template, select defineView and choose Next. e) Assign the object to your transport request and choose Finish. 2. If the tool did not ask for the template, go to the templates tab on the tabstrip below the editor and choose the template there. a) Go to tab templates on the tabstrip below the editor. b) Select template defineView. 3. In the respective Annotation, enter a name for the SQL View that is to be generated (suggested name: Z##SIMPLE). a) See source code extract from the model solution. 4. Would it be possible to specify the same name for CDS View and SQL View? No. They need to be distinguishable when they are used. e.g., in ABAP coding. 5. What is the maximum length for the name of the SQL View? 16 Characters Implement the DDL Source © Copyright. All rights reserved. 53 Unit 2: Basic SQL Features in CDS Views 1. In the FROM clause of the SELECT statement, specify database table SBOOK. a) See source code extract from the model solution. 2. Edit the field list of the SELECT Statement. Start with the complete key of table SBOOK, except for the client field. Add the fields for flight class, booking price in foreign currency (with the corresponding currency key), weight of luggage (with corresponding weight unit), booking date, travel agency number, counter number and customer number. Hint: To enter the field names, make use of the editor’s auto-completion capabilities! a) For auto-completion, press keys Ctrl and Space at the same time. b) See source code extract from the model solution. Activate the DDL Source and Test the Result 1. Perform a syntax check. Then activate the DDL Source. a) Choose Check ABAP Development Object or hit Ctrl + F2. b) Choose Activate or hit Ctrl + F3. 2. In the Project Explorer window, refresh the object list for your package and locate the DB view that has been created. a) Place the cursor on your package. b) Choose Refresh from the context menu or hit F5. c) Open subnode Dictionary→ Views. 3. Open the Data Preview for your CDS View. a) In the Project Explorer, right-click on your DDL Source and choose Open With→ Data Preview. DDL Source S4D430_SIMPLE @AbapCatalog.sqlViewName: 'S4D430_SIMP' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'Solution: Simple CDS View Definition' define view S4D430_Simple as select from sbook { carrid, connid, fldate, bookid, class, forcuram, forcurkey, luggweight, wunit, order_date, agencynum, counter, customid } 54 © Copyright. All rights reserved. Lesson: Define a Simple CDS View LESSON SUMMARY You should now be able to: ● Create a DDL Source ● Understand the DDL Syntax Rules © Copyright. All rights reserved. 55 Unit 2 Lesson 2 Creating a CDS View with Inner Join, Projection, and Selection LESSON OBJECTIVES After completing this lesson, you will be able to: ● Define a CDS View That Reflects a Database View Inner Join in DDL Source define view 540430 Connectionl Jloin a1s select from spfli inner join scarr on spfli.carrid = scarr.carrid spfl!.i. car.rid, spflli.connid, soarr.carrname, scarr.currcode, sp:fli.cityfrom, spflli.cityto, airpfrom, airpto Use Separator is,,." not,,-" (SQIL standard, not Open SQL Syntax) Table name mandatory where field name alone is ambiguous Figure 47: Inner Join in DDL View Definition 56 © Copyright. All rights reserved. Lesson: Creating a CDS View with Inner Join, Projection, and Selection Aliases for Tables and Fields define view S4D430_Connection2_Alias as select from inner join ,.s_c_a_r on a.carri _ �..-,-11 1 1C---...-- { lcarrid, connid, carrname, curr_ code as ,currency, __ cityfrom, cityto, airpfrom, airpto Alias for tabie name Alias for element (mandatory for certain expressions) Figure 48: Aliases for Tables And Fields In the element list, addition AS defines an alternative element name. The alternative element name replaces the actual name of the element from the data source data_source. The view field is created under the alternative element name in the CDS database view. Accordingly, the alternative element name must comply with the rules for names of view fields of database views, as well as the general naming rules for names, which means that it must also meet the naming conventions for component names of structures in ABAP Dictionary and cannot be a reserved component name. The reserved names that cannot be used are maintained in database table TRESE. Alternative element names can be used in the current CDS view to grant unique names for identically named elements from different entities of the data source. When the current CDS view is accessed, the alternative element names must be used instead of the actual name. Note: Alternative element names cannot be used within the CDS view, with one exception: alternative element names can be specified directly or after $projection in the ON condition of anassociation. © Copyright. All rights reserved. 57 Unit 2: Basic SQL Features in CDS Views Key Definition l@AbapCatalog.preserveKey: true define view S4.D43.0_Connect101n3_Keys as select Define these elements as key elements from spf.!i as c inner join scarr as a on c. carrid = a. carrid { {ke;l c _. car rid, �c.connid, a.carrname, Create database objcect with the specified key Need to be start elements of list (without gaps) a. currcod.e as currency, c.cityfrom, c.cityto, airpfrom, airpto ] Figure 49: Key Definition KEY is used to define the current element as a key element of the current CDS entity. Any elements of a SELECT list can be defined as key elements that are placed without gaps at the start of the list. The key elements of the CDS entity are evaluated as follows if they are used as a data source of a SELECT statement in Open SQL: ● ● By the addition ORDER BY PRIMARY KEY. In this case, the key elements must be defined at the start of the SELECT list without any gaps. In implicit access control. By default, the key elements of the CDS entity are used to document the semantics of the data model. The addition KEY is then ignored when the CDS view is activated and when other accesses are performed in program executions. The default setting can be overridden using the view annotation AbapCatalog.preserveKey: ● ● 58 If the value true is specified for this annotation, the key elements defined using KEY are also used as keys of the CDS database view. If this annotation is not specified or specified with the value false, the key elements defined using KEY are ignored by the key of the CDS database view. Like in classic views, the key fields of the database view are derived implicitly from the key fields of the basis tables and the join conditions. If this is not possible, all fields of the database view are key fields. © Copyright. All rights reserved. Lesson: Creating a CDS View with Inner Join, Projection, and Selection Selections de-fine view S4:0430_Connection4_Selection as select from spfli as c inner join scarr as a on c.carrid a.carrid key c.carri.d, key c.conni.d, a.carrname, a.currcod.e as currency, c.cityfrom, Add WHERE clause to define a pre-selecti:on c.cityto, ai.rpfrom, ai.rpto lwhere c. f1type <> 'X' ! I/exclude charter f1ights Figure 50: Selections Addition WHERE defines a condition for the results set of a CDS view. When the CDS view is accessed, the results set contains only the data from the data source data_source that meets the condition cond_expr specified after WHERE. Note: The fields evaluated in the condition do not need to be defined as elements of the CDS view in the SELECT list. © Copyright. All rights reserved. 59 Unit 2: Basic SQL Features in CDS Views 60 © Copyright. All rights reserved. Unit 2 Exercise 4 Define a CDS View That Reflects a Database View Business Example Template: S4D430_SIMPLE (DDL Source) Solution: S4D430_JOIN_AND_SELECTION (DDL Source) Create a new DDL Source 1. In your own Package, create a new DDL Source (suggested name: Z##_JOIN_AND_SELECTION, where ## stands for your group number). Choose template defineViewWithJoin to generate the definition statement and some standard annotations. 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##JOIN). Implement an inner join of tables SBOOK and SCUSTOM 1. In the definition of the CDS View, implement an inner join of tables SBOOK and SCUSTOM. Refer to the foreign key relations of table SBOOK to find the appropriate fields for the join condition. Make sure you specify aliases for the two tables. 2. Open your DDL Source Z##_SIMPLE (or the corresponding model solution S4D430_SIMPLE) and copy the entire field list to your new DDL Source. Optionally, add the alias for table SBOOK in front of the field names. 3. At the end of the list, add fields for name and address of the customer (Name, Street, Postcode, City, Country) . Hint: Make use of the editor’s auto-completion capabilities to enter the field names. Specify the key and provide aliases for some fields 1. Use prefix key to make sure all key fields of table SBOOK are also key fields of your view. 2. Provide an alias for fields FORCURRAM and FORCURRKEY (suggested alias names: AMOUNT and CURRENCY). Make sure that cancelled bookings are excluded from this view © Copyright. All rights reserved. 61 Unit 2: Basic SQL Features in CDS Views 1. Add a WHERE clause to read only bookings that are not cancelled. Activate and Test 1. Activate the DDL Source. 2. Open the Data Preview for the CDS View and ensure that the displayed data is correct. 62 © Copyright. All rights reserved. Unit 2 Solution 4 Define a CDS View That Reflects a Database View Business Example Template: S4D430_SIMPLE (DDL Source) Solution: S4D430_JOIN_AND_SELECTION (DDL Source) Create a new DDL Source 1. In your own Package, create a new DDL Source (suggested name: Z##_JOIN_AND_SELECTION, where ## stands for your group number). Choose template defineViewWithJoin to generate the definition statement and some standard annotations. a) See the corresponding step in the previous exercise. 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##JOIN). a) See source code extract from the model solution. Implement an inner join of tables SBOOK and SCUSTOM 1. In the definition of the CDS View, implement an inner join of tables SBOOK and SCUSTOM. Refer to the foreign key relations of table SBOOK to find the appropriate fields for the join condition. Make sure you specify aliases for the two tables. a) See source code extract from the model solution. 2. Open your DDL Source Z##_SIMPLE (or the corresponding model solution S4D430_SIMPLE) and copy the entire field list to your new DDL Source. Optionally, add the alias for table SBOOK in front of the field names. a) Open the DDL Source in the editor window by double-clicking on it. b) Select the entire field list. c) Hit Ctrl + C to copy the source code to the clipboard. d) Open the new DDL Source in the editor window. e) Place the cursor between character “{” and “}” and hit Ctrl + V. f) See source code extract from the model solution. 3. At the end of the list, add fields for name and address of the customer (Name, Street, Postcode, City, Country) . © Copyright. All rights reserved. 63 Unit 2: Basic SQL Features in CDS Views Hint: Make use of the editor’s auto-completion capabilities to enter the field names. a) See source code extract from the model solution. For the use of auto-completion, see the corresponding step in the previous exercise. Specify the key and provide aliases for some fields 1. Use prefix key to make sure all key fields of table SBOOK are also key fields of your view. a) See source code extract from the model solution. 2. Provide an alias for fields FORCURRAM and FORCURRKEY (suggested alias names: AMOUNT and CURRENCY). a) See source code extract from the model solution. Make sure that cancelled bookings are excluded from this view 1. Add a WHERE clause to read only bookings that are not cancelled. a) See source code extract from the model solution. Activate and Test 1. Activate the DDL Source. a) See the corresponding step in the previous exercise. 2. Open the Data Preview for the CDS View and ensure that the displayed data is correct. a) See the corresponding step in the previous exercise. DDL Source S4D430_JOIN_AND_SELECTION @AbapCatalog.sqlViewName: 'S4D430_JOIN' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'Solution: Inner Join and Selection' define view S4D430_Join_And_Selection as select from sbook as b inner join scustom as c on b.customid = c.id { key b.carrid, key b.connid, key b.fldate, key b.bookid, b.class, b.forcuram as amount, b.forcurkey as currency, b.luggweight, b.wunit, b.order_date, b.agencynum, b.counter, b.customid, c.name, c.street, c.postcode, c.city, c.country } 64 © Copyright. All rights reserved. Lesson: Creating a CDS View with Inner Join, Projection, and Selection where cancelled <> 'X' © Copyright. All rights reserved. 65 Unit 2: Basic SQL Features in CDS Views LESSON SUMMARY You should now be able to: ● 66 Define a CDS View That Reflects a Database View © Copyright. All rights reserved. Unit 2 Lesson 3 Using ABAP Annotations in CDS Views LESSON OBJECTIVES After completing this lesson, you will be able to: ● Use ABAP Annotations in CDS Views ● Work with Translatable Texts in CDS ABAP Annotations for Views I View Annotations @Aba Catalog.sqlViewName @ClientDependent @EndUserText.label Element An notations @Semantics.unitOfMeasure @EndUserText.label Parameter Annotations .. @Environment.systemField @EndUserText.label Extension Annotations .. @AbapCatalog.sg1ViewAppend.Name Function Annotations .. @ClientDependent @EndUserText.label FrameWOni·5pet: ific (Evaluated by Framework like OData. VDM, UI, Analytics .. ,.) ""' * See details the respective lessons See the short outlook on those in the last unit Figure 51: Classification of SAP Annotations Dependent on the Evaluation, we distinguish two groups of annotations: ABAP Annotations and Framework-specific annotations. ABAP annotations ABAP annotations define technical and semantic attributes of a CDS object. They are usually evaluated for every CDS object when activated by the ABAP runtime environment. ABAP annotations can modify the behavior of Open SQL statements that access a CDS entity. One important example is how the client dependency of a CDS entity is defined using the associated ABAP annotation. FrameworkFramework-specific annotations In most cases, the framework-specific annotations must be evaluated by the frameworks of the corresponding software components using a suitable API and are not relevant for © Copyright. All rights reserved. 67 Unit 2: Basic SQL Features in CDS Views activations and the ABAP runtime environment. Here, the names and values of these framework-specific annotations must follow the rules of the relevant framework. For SAP components, these can be taken from the tables of the Framework-Specific Annotations document. Dependent on the Scope, we distinguish 5 groups of annotations: View Annotations Annotations for a CDS view. Placed in front of the DEFINE VIEW statement. Element annotations Annotations for an element of the SELECT list of a CDS view. Placed in front of or after the element. Parameter annotations Annotations for a parameter of a CDS view. Placed In front of or after the parameter. Extension annotations Annotations for a CDS view extension. Placed in front of the EXTEND VIEW statement. Function annotations Annotations for a CDS table function. Placed in front of the DEFINE TABLE FUNCTION statement. l@AbapCatalog.sqlViewName: 'S4D430CONN5ANN0' l@ClientDependent, true Swfldh on/off client handling in Open SQL 1 @AccessControl.authorizationCheck: #CHECK @AbapCatalog.compiler.CompareFilter: true Switch on/off implicit access control in Open SOL l Control evaluation of filtered associations @AbapCatalog.Buffering.type: #GENERIC @AbapCatalog.Buffering.numberOfKeyFields: @AbapCatalog.Buffering.status: #ACTIVE I Switch on/off buffering of SQL View in Open SOL define view S4d430 Connection5 Annotations I· .. - - Figure 52: Important ABAP View Annotations For CDS Views, the following important ABAP annotations exist: AbapCatalog.sqlViewName Specifies the name of the CDS database view in the CDS view ClientDependent Defines client handling when Open SQL is used to access the CDS view. Is optional and default value is "true". AccessControl.authorizationCheck Defines the implicit access control when Open SQL is used to access the CDS view. 68 © Copyright. All rights reserved. Lesson: Using ABAP Annotations in CDS Views AbapCatalog.compiler.compareFilter Defines the evaluation of filter conditions in path expressions of the CDS view. AbapCatalog.buffering.<...> Define the buffering of the CDS view in SAP buffering. ABAP Annotations for View Elements Semantics for Amount I Currency Code � - ... @Semantics.amount.currencyCode:'CURRENCY' price, @Semantics.currencyCode: true currency, Before or after the el:ement ... Semantics for Quantity I UnitOfMeasure ... distance @<Semantics.quantity.unitOfMeasure: @<Semantics.unitOfMeasure: true dist id .... l I DISTID'' Before or after the element Figure 53: Important ABAP Annotations for View Elements The Semantics annotations are used to define the currency fields and quantity fields of CDS views and CDS table functions. Like all element annotations they can be located either before or after the element they refer to. [o Hint: Compare this to the Currency/Quantity Fields tab that is available when editing transparent tables or structure types in the ABAP Dictionary tool. © Copyright. All rights reserved. 69 Unit 2: Basic SQL Features in CDS Views ABAP Annotations for Translatable Texts View Annotation Maximum of 60 Characters .. . @EndUserText.label: 'Demo: Simple View Definition' ... Element Annotations � " - + -� @EndUserText.label: 'Discount' @EndUserText.quickinfo: 'Customer Specific Discount' c.discount, � " t 1 Maximum of 60 Characters I Before or after the element Note: Element text annotations are required if no text is inherited from data source (i.e. table definition or other view) J Figure 54: ABAP Annotations for Translatable Texts ABAP annotations starting with EndUserText are used to define translatable semantic texts for a CDS object. EndUserText.label is available as view annotation or as element annotation. The value is limited to a length of 60 characters. EndUserText .quickinfo is only available as element annotation. The value is stored as a string and can have arbitrary length. Translation of Annotations ln/0.I Saeen: Trilnsl8tion Editor Transaction SE63 Other Te:«s ell IISl'l J3SP Te""" L4\'0'1t- (C:rnao-clie,,s I DISi>2 J3SP Te"'-" r..,ou" (CHem,•Speci!icJ CA1 to,er:!'ace itena (� r-o"l'l@rtace T"Ullli;!!I (FU(;S) ['Dto!-:r"ti!lce il"i!-.!CIC;;!I (ru©f:) to,er!ace ite.x•• (PRO::;) ta,er:!'ace iten• (i!\AJiJ [ot@rt!!lce Ue..xic.!I (LlmA.) ccrr Cont>m1 Co:,pe•J. c.e ite.••• C'!ilDC n..n .. 1 t-100• to� C1>a11;e llo Obj ct Object Hime 1 p Trarnsl.11:i:in soor,ee IAl\guag� e�JJS0 Engi!h U'> T;,rg�t �mgwge � Gl'llNnDE Figure 55: Translation of CDS Views 70 © Copyright. All rights reserved. Lesson: Using ABAP Annotations in CDS Views The values of text annotations are stored in special tables that have a language key and that are translatable. The value specified in the source code should consist of text in the original language of the CDS source code and is translated into the required languages. Translation of CDS Views is done as usual in the Translation Editor (Transaction Code SE63). A new object type CDS View has been added to object group User Interface Texts. To translate the texts defined in a given DDL Source, proceed as follows: 1. Start Transaction SE63. 2. Choose Short Texts from the toolbar. 3. On the next dialog window, expand node User Interface Texts. 4. Choose subelement DDLS CDS Views. 5. On the next dialog window, enter the name of the DDL Source, the source language, and the target language 6. Choose Edit. Dynamic Access to Annotation Texts REPORT s4d430d_dynamio_acoess_to_text. DATA gv_txt TYPE string. PARAMETERS: pa eds TYPE ddstrucobjname DEFAULT 'S4D430_ANNOTATIONS', pa_;elem TYPE ddfieldname_l DEFAULT 'CARRIO', pa_lang TYPE sy-langu DEFAULT 1EN1 • = gv txt c::l_dd_ddl_annotation_service=>get_label_4_element( EXPORTING entityname pa_ods elem.entname pa_elem � pa_lang language = ) . .. I Figure 56: Dynamic Access to Text The methods of global class CL_DD_DDL_ANNOTATION_SERVICE read the texts as specified by an input parameter for the language. If no language is passed to the input parameter, the logon language is used as the default. I» Note: If no text is found for the language, the secondary language in AS ABAP is used. © Copyright. All rights reserved. 71 Unit 2: Basic SQL Features in CDS Views 72 © Copyright. All rights reserved. Unit 2 Exercise 5 Use Annotations in DDL Sources Business Example Template: S4D430_JOIN_AND_SELECTION (DDL Source) Solution: S4D430_ANNOTATIONS (DDL Source) Create a copy of a DDL Source For the next exercise, you need a copy of your solution of the previous exercise (DDL Source Z##_JOIN_AND_SELECTION). If you did not complete the previous exercise, you can copy from DDL Source S4D430_JOIN_AND_SELECTION. Note: ADT does not yet support a Duplicate function for DDL Sources. If you want to create a copy, you have to create a new DDL Source, first. You then can copy and paste the source code manually. 1. In your own Package, create a new DDL Source (suggested name: Z##_ANNOTATIONS, where ## stands for your group number) based on template defineView. 0 Hint: Even though you want to copy from another DDL Source, it is advisable to create the DDL Source based on template defineView. This ensures that the name of the CDS View and the name of the DDL Source correspond to each other and that the short description of the DDL Source matches the text in annotation @EndUserText.label. 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##ANNO). 3. Open the DDL Source you want to duplicate and copy the FROM clause, the field list, and the WHERE clause to the new DDL Source. Switch on buffering 1. In the DDL Source, add the relevant annotations to activate buffering. Set the buffering type to “Generic Buffering”. Make sure that all bookings on the same flight date are buffered together. © Copyright. All rights reserved. 73 Unit 2: Basic SQL Features in CDS Views 2. How many key fields do you have to specify to achieve this? 3. Activate the DDL source. 4. Open the SQL View and check the technical settings. Assign currency key and unit fields to all amount and quantity fields 1. Use the relevant field annotations to link the fields amount and currency. 2. Use the relevant field annotations to link the fields luggweight and wunit. Activate and Test 1. Activate the DDL Source. 2. Open the Data Preview for the CDS View and ensure that the displayed data are correct. 74 © Copyright. All rights reserved. Unit 2 Solution 5 Use Annotations in DDL Sources Business Example Template: S4D430_JOIN_AND_SELECTION (DDL Source) Solution: S4D430_ANNOTATIONS (DDL Source) Create a copy of a DDL Source For the next exercise, you need a copy of your solution of the previous exercise (DDL Source Z##_JOIN_AND_SELECTION). If you did not complete the previous exercise, you can copy from DDL Source S4D430_JOIN_AND_SELECTION. Note: ADT does not yet support a Duplicate function for DDL Sources. If you want to create a copy, you have to create a new DDL Source, first. You then can copy and paste the source code manually. 1. In your own Package, create a new DDL Source (suggested name: Z##_ANNOTATIONS, where ## stands for your group number) based on template defineView. 0 Hint: Even though you want to copy from another DDL Source, it is advisable to create the DDL Source based on template defineView. This ensures that the name of the CDS View and the name of the DDL Source correspond to each other and that the short description of the DDL Source matches the text in annotation @EndUserText.label. a) See the corresponding step in the previous exercise. 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##ANNO). a) See source code extract from the model solution. 3. Open the DDL Source you want to duplicate and copy the FROM clause, the field list, and the WHERE clause to the new DDL Source. a) Locate the DDL Source you want to copy from in the Project Explorer (e.g. by adding the package to your favorites or by searching for it). b) Open the DDL Source in the editor window by double-clicking on it. © Copyright. All rights reserved. 75 Unit 2: Basic SQL Features in CDS Views c) Select the source code you want to copy. d) Hit Ctrl + C to copy the source code to the clipboard. e) Open the new DDL Source in the editor window. f) Select the source code you want to replace and hit Ctrl + V. g) See source code extract from the model solution. Switch on buffering 1. In the DDL Source, add the relevant annotations to activate buffering. Set the buffering type to “Generic Buffering”. Make sure that all bookings on the same flight date are buffered together. a) See source code extract from the model solution. 2. How many key fields do you have to specify to achieve this? 4 (MANDT, CARRIO, CONNID,FLDATE) 3. Activate the DDL source. a) See the corresponding step in the previous exercise. 4. Open the SQL View and check the technical settings. a) Locate the SQL View (Z##ANNO) in the the view in the ABAP Dictionary tool. b) On the SAP GUI Window, choose buffer settings. Project Explorer and double-click on it to open Menu → Goto → Technical Settings to display the Assign currency key and unit fields to all amount and quantity fields 1. Use the relevant field annotations to link the fields amount and currency. a) See source code extract from the model solution. 2. Use the relevant field annotations to link the fields luggweight and wunit. a) See source code extract from the model solution. Activate and Test 1. Activate the DDL Source. a) See the corresponding step in the previous exercise. 2. Open the Data Preview for the CDS View and ensure that the displayed data are correct. a) See the corresponding step in the previous exercise. DDL Source S4D430_ANNOTATIONS @AbapCatalog.sqlViewName: 'S4D430_ANNO' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'Solution: ABAP Annotations' @AbapCatalog.buffering.type: #GENERIC @AbapCatalog.buffering.numberOfKeyFields: 4 @AbapCatalog.buffering.status: #ACTIVE 76 © Copyright. All rights reserved. Lesson: Using ABAP Annotations in CDS Views define view S4D430_Annotations as select from sbook as b inner join scustom as c on b.customid = c.id { key b.carrid, key b.connid, key b.fldate, key b.bookid, b.class, b.forcuram as amount @<Semantics.amount.currencyCode:'CURRENCY', b.forcurkey as currency @<Semantics.currencyCode: true, b.luggweight @<Semantics.amount.currencyCode: 'WUNIT', b.wunit @<Semantics.currencyCode: true, b.order_date, b.agencynum, b.counter, b.customid, c.name, c.street, c.postcode, c.city, c.country } where cancelled <> 'X' © Copyright. All rights reserved. 77 Unit 2: Basic SQL Features in CDS Views LESSON SUMMARY You should now be able to: 78 ● Use ABAP Annotations in CDS Views ● Work with Translatable Texts in CDS © Copyright. All rights reserved. UNIT 3 More SQL Features in CDS Views Lesson 1 Using SQL Expressions in CDS Views Exercise 6: Use Expressions in a CDS View 80 87 Lesson 2 Using Built-in SQL Functions in CDS Views Exercise 7: Use Built-in Functions in a CDS View 93 101 Lesson 3 Understanding Nested Views Exercise 8: Define a CDS View based on other CDS Views 107 109 Lesson 4 Using Aggregations in CDS Views Exercise 9: Define a CDS View with Aggregation 116 121 Lesson 5 Using Additional Join Types and UNION (ALL) Exercise 10: Define a CDS View with a UNION statement 126 137 UNIT OBJECTIVES ● Use SQL Expressions in CDS Views ● Use Built-in SQL Functions in CDS Views ● Define CDS Views Based on Other CDS Views ● Use Aggregate Functions, Group By And Having in CDS Views ● Understand Additional Join Types ● Understand UNION and UNION ALL © Copyright. All rights reserved. 79 Unit 3 Lesson 1 Using SQL Expressions in CDS Views LESSON OBJECTIVES After completing this lesson, you will be able to: ● Use SQL Expressions in CDS Views Literals Character Uterals I ... 'Hello' as c::oI_charJ '32768' as col_numcJ I ... I /Type CHAR I /Type NUMC (only digits) Numeric Uterals I ... 255 col_int4lJ //Type INT4 col_int2J //Type INT2 in Range [-32768,32767] as c::ol_intlJ //Type INT! in Range [0,255] 1.5 as 32768 4711 L·· as as col_fltp, //Type FLTP Literals with Domain Prefix r l I ... #S_CLASS. Y' as col _ecol, //S_CLASS is a domain in DDIC #S_CLASS.Y as col _eco2, //S_CLASS has fixed values :S_CLASS.Y as col _eco3 I /Value 'V' checked by syntax check ... Figure 57: Literals ABAP CDS syntax offers the following types of literals: Character Literals ● Series of characters enclosed in single quotes ● Type NUMC if it consists only of digits ● Type CHAR otherwise Numeric Literals 80 ● Series of digits without quotes ● May contain a decimal point, but not before the first digit © Copyright. All rights reserved. Lesson: Using SQL Expressions in CDS Views ● Type FLTP if it contains a decimal point ● Type INT1, INT2 or INT4 otherwise, depending on the size I» Note: There are no numeric literals of type INT8. This means that integer literals must lie in the value range of INT4. Domain Prefixes for Literals In certain operand positions, a literal can have a domain prefix. A domain prefix consists of the name of a repository object of type DOMAIN, introduced with character "#" or ": "and separated by a period ("."). For most of the text literals, the quotes can be omitted when they are prefixed with a domain. If a literal is prefixed with a domain, syntax check will issue a warning in case the literal does not match the fixed values of the domain or does not lie in the value range specified by the domain. CASE Distinction Simple Case Di.stinction CASE operand WHEN operandl THEN resultl [WHEN operand2 THEN result2] [El.SE resultn] END • Comparable toABAPSlatementCASE ... WHEN ... ENOCASE. • Result depends on a series nf "EQUALS"-comparisons Complex Case Distinction(= Searched Case) CASE WHEN s.ql_co11ditionl THEN resuLtl [WHEN sql_condition2 THEN result2] [ElSE resultn] END • Comparable toABAP Statement IF ... ELSEIF .... ENDIF. • Result depends on a sequence of SQL conditions (logical expressions) .. I Figure 58: Case Distinctions ABAP CDS offers case distinctions that can be used in the element list of a SELECT statement and as operands for other expressions. A case distinction returns exactly one value. This value depends on a series of conditions. A case distinction always starts with key work CASE and ends with key word END. The rest depends on the type of case distinction: Simple Case Distinction The result depends on the values of several operands. The simple case distinction is comparable to the CASE statement in ABAP. © Copyright. All rights reserved. 81 Unit 3: More SQL Features in CDS Views Complex Case Distinction Also known as searched distinction. The result depends on a sequence of logical expressions. The complex case distinction is comparable to the IF statement in ABAP. l@AbapCatalog. sqlViewNlame: 'S4D430_ EXPRCASE' define view S4d430 _Expression_Case as select from sboolk I { ... II Simple Case case class ... whe11 'Y' then 'Economy' when 'C' then 'Business' when 'FI then 'First' end as class _txt } ] Figure 59: Example 1: A Simple Case Expression The figure above gives an example of a simple case distinction in a CDS View. Field CLASS of table SBOOK is of type CHAR length 1 and can have three different values. To make this more readable, the case distinction replaces the technical one-character key with a longer text. Note: If, like in the example above, the ELSE branch is missing, syntax check will issue a warning. 82 © Copyright. All rights reserved. Lesson: Using SQL Expressions in CDS Views l@Abap(atalog .. sqlViewN1ame: '540430_ EXPRCASE' define view S4d430_Expression __case as select from sboolk I { ... II Complex Case case = = wunit = ,, when class when wunit when else 'F' then and luggweight ) 20 then 'X' 'LB' and luggweight > 44 then 'X' 'KG' I as excess_luggage1, end ... I I } Figure 60: Example 2: A Complex Case Expression The figure above gives an example of a complex case distinction in a CDS View. Customers with a luggage weight larger than 20 kilogram or 44 pound will be classified as having excess luggage. First class passengers, however, are always excluded from this classification. I @Abap(atalog. sqlViewName: 'S4D430_EXPRCASE' define view S4d430_cxpression_:Case as select from sboolk { II Nested case case dass when 'F' thern else case when ( wunit .... 'KG' and luggweight > 20 or ( wunit then 'X' else 'LB' and luggweight > then 'X' 44 'X' end end as excess_luggage2 } Figure 61: Example 3: Two Nested Case Expressions The figure above gives an example of nested case distinctions in a CDS View. The outer CASE expression checks whether this is a first class booking. The result in the ELSE branch of the outer CASE expression is not just literal but it consists of another case expression based on the luggage weight and unit. Of course, also the result after a WHEN … THEN branch could be a case expression. © Copyright. All rights reserved. 83 Unit 3: More SQL Features in CDS Views Arithmetic Expressions Four arlthmetlc opera.t.ors (+, -, ", /) and brackets Three Types of C:.xp:ressions • Integer Expression - All Operands have integer type (INT1, INT2, INT4, INTS) • D'eeimal Expression - At least one operand has decimal type (DEC, CURR, QUAN) - No operand of type FLTP • Floating Point Expression - All operands have type FLTP Important Rest,rictions • If one operand has type FLTP, all operands require type FLTP Operator "I" only allowed in floating point expressions I J See next section for the possibility of type conversions I Figure 62: Arithmetic Expressions In ABAP CDS, arithmetic expressions can be used as elements of the field list. ABAP CDS supports four operators, brackets and three different arithmetics (integer, decimal and floating point). The value range and precision of intermediate results highly depends on the arithmetic that is used. Note: Numeric literals without decimals have integer type. Numeric Literals with decimals have type FLTP! l@Abap(atalog. sqlViewNlame: 'S4D430_ EXPRARITH' define view s4d430 _Expression_ arithmetic as select from sf ight { seatsmax, saat socc , seatsmax - seatsocc as seatsfree, seatsocc + seatsocc_ b + seatsocc -f as seatsmax_tot, 2 * price as double_price I} I Figure 63: Example: Arithmetic Expressions in CDS Views The figure above gives some examples for arithmetic expressions in CDS Views. 84 © Copyright. All rights reserved. Lesson: Using SQL Expressions in CDS Views Type Conversions • What. it looks I i,ke: CAST ( operand AS target_ type ) What it does: - Converts the value of operand into target_type Two Options for target_type: A predefined dictionary type, e.g. abap. i.nt4, abap. char-(19),, abap. dec(S,, 2) Any Dictionary data element, e.g. 5_CARRID, 8UKRS Many Options for operand: Literal (without a domain prefix) Field or a data source - Arithmetic expression - Case distinction with CASE - Predefined function ] Figure 64: Type Conversion with CAST Expression Unlike ABAP, ABAP CDS does not know implicit type conversions. On the contrary, CDS inspects very strict type compatibility rules. The CAST expression of CDS allows you to implement explicit type conversions. In NW 7.40, the target type could only be specified as technical type, i.e., as a predefined Dictionary type like INT4, CHAR or DEC. As of NW 7.50, any data element from the Dictionary can be the target type of a type conversion with CAST. The operand for a type conversion cannot only be a literal or a field of the data source (for example, of a database table). All kinds of other expressions are possible like arithmetic expressions, CASE distinctions, predefined functions, and many others. Note: There are restrictions with regard to the combination of source type and target type. Some combinations are not supported at all. Others only work with limitations. For example, it is currently not possible to use operands of type FLTP as source for the CAST expression. A detailed matrix can be found in the ABAP Language documentation. © Copyright. All rights reserved. 85 Unit 3: More SQL Features in CDS Views @AbapCatalog. sqlViewName: 'S4D430_EXPIRCAST' define view S4d430_Expression_cast as select from sf light { '19891109' as col_char, cast(' 19891109' as abap. int4) cast(' 1989U09' as abap.dec(l6,.2)) cast(' 19891109' as abap.fltp) as col_int4., as col_dec, as colJltp, cast('19891109' as abap.Bats ) as coL_datsJ cast( castt ' 19891109' as abap .. dats) as s_date) as col_ddic., cast(seatsocc as abap.fl tp) I cast(seatsmax as abap.fltp) as ratio } cot�hu !1m1100 19891100 ,;;oljrrtA 19.891.109 1i:i.&11.109 col_dK 19891109.00 19891109.00 col_fllp 1. 989'1109000000000E·07 1. 989rl 109000000000£�01 tr.t)('l,ii�.r,.,. I col_dm 19S9·1Ml9 1989·'11·09 col_ddi<; 1989·11·09 1989·11-09 r.tliii 9. 702 S9740259740lE·01 9.fl62ll766233J6622E-01 I ,.",.,,:..,""'l '),,.,","1:11"1.'i Figure 65: Example: Type Conversions With CAST The figure above gives some examples of type conversions in CDS Views. 86 © Copyright. All rights reserved. Unit 3 Exercise 6 Use Expressions in a CDS View Business Example Template: S4D430__ANNOTATIONS (DDL Source) Solution: S4D430_EXPRESSIONS (DDL Source) Create a copy of your DDL Source For the next exercise, you need a copy of your solution of the previous exercise (DDL Source Z##_ANNOTATIONS). If you did not complete the previous exercise, you can copy from DDL Source S4D430_ANNOTATIONS. 1. In your own Package, create a new DDL Source (suggested name: Z##_EXPRESSIONS, where ## stands for your group number) based on template defineView. 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##EXPR). 3. Open the DDL Source you want to duplicate and copy the FROM clause, the field list and the WHERE clause to the new DDL Source. Return readable text for the flight class Field CLASS of table SBOOK contains a single character key for the flight class of the booking. Possible values are “Y”, “C” and “F”. Use the CASE expression to return longer texts for the three flight classes. 1. In the field list, replace field CLASS with a simple CASE expression to return texts “Economy”, “Business” and “First” instead of values “Y”, “C” and “F”. Return the customer’s discount as a factor Field DISCOUNT of table SCUSTOM contains a customer-specific discount rate. This discount rate is stored as an integer number between 0 and 100. Implement an arithmetic expression to return the discount as a value between 0.00 and 1.00 instead. 1. Use an arithmetic expression with operator “/” to divide the discount value by 100. Why do you have to cast the discount value to another data type? 2. Use the respective annotations to provide a label and a tooltip for the calculated discount field. Activate and Test © Copyright. All rights reserved. 87 Unit 3: More SQL Features in CDS Views 1. Activate the DDL Source. 2. Open the Data Preview for the CDS View and ensure that the displayed data are correct. 88 © Copyright. All rights reserved. Unit 3 Solution 6 Use Expressions in a CDS View Business Example Template: S4D430__ANNOTATIONS (DDL Source) Solution: S4D430_EXPRESSIONS (DDL Source) Create a copy of your DDL Source For the next exercise, you need a copy of your solution of the previous exercise (DDL Source Z##_ANNOTATIONS). If you did not complete the previous exercise, you can copy from DDL Source S4D430_ANNOTATIONS. 1. In your own Package, create a new DDL Source (suggested name: Z##_EXPRESSIONS, where ## stands for your group number) based on template defineView. a) See the corresponding step in the previous exercise. 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##EXPR). a) See source code extract from the model solution. 3. Open the DDL Source you want to duplicate and copy the FROM clause, the field list and the WHERE clause to the new DDL Source. a) See the corresponding step in the previous exercise. Return readable text for the flight class Field CLASS of table SBOOK contains a single character key for the flight class of the booking. Possible values are “Y”, “C” and “F”. Use the CASE expression to return longer texts for the three flight classes. 1. In the field list, replace field CLASS with a simple CASE expression to return texts “Economy”, “Business” and “First” instead of values “Y”, “C” and “F”. a) See source code extract from the model solution. Return the customer’s discount as a factor Field DISCOUNT of table SCUSTOM contains a customer-specific discount rate. This discount rate is stored as an integer number between 0 and 100. Implement an arithmetic expression to return the discount as a value between 0.00 and 1.00 instead. 1. Use an arithmetic expression with operator “/” to divide the discount value by 100. © Copyright. All rights reserved. 89 Unit 3: More SQL Features in CDS Views Why do you have to cast the discount value to another data type? Because operator “/” only supports type abap.fltp. a) See source code extract from the model solution. 2. Use the respective annotations to provide a label and a tooltip for the calculated discount field. a) See source code extract from the model solution. Activate and Test 1. Activate the DDL Source. a) See the corresponding step in the previous exercise. 2. Open the Data Preview for the CDS View and ensure that the displayed data are correct. a) See the corresponding step in the previous exercise. DDL Source S4D430_EXPRESSIONS @AbapCatalog.sqlViewName: 'S4D430EXPR' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'Solution: Expressions' define view S4D430_Expressions as select from sbook as b inner join scustom as c on b.customid = c.id { key b.carrid, key b.connid, key b.fldate, key b.bookid, case b.class when 'Y' then 'Economy' when 'C' then 'Business' when 'F' then 'First' else '???' end as class, b.forcuram as amount @<Semantics.amount.currencyCode:'CURRENCY', b.forcurkey as currency @<Semantics.currencyCode: true, b.luggweight @<Semantics.amount.currencyCode: 'WUNIT', b.wunit @<Semantics.currencyCode: true, b.order_date, b.agencynum, b.counter, b.customid, c.name, c.street, c.postcode, c.city, c.country, @EndUserText.label: 'Discount Factor' @EndUserText.quickInfo: 'Customer Specific Discount Factor' 90 © Copyright. All rights reserved. Lesson: Using SQL Expressions in CDS Views cast(c.discount as abap.fltp(16,16)) / 100.0 as discount } where cancelled <> 'X' © Copyright. All rights reserved. 91 Unit 3: More SQL Features in CDS Views LESSON SUMMARY You should now be able to: ● 92 Use SQL Expressions in CDS Views © Copyright. All rights reserved. Unit 3 Lesson 2 Using Built-in SQL Functions in CDS Views LESSON OBJECTIVES After completing this lesson, you will be able to: ● Use Built-in SQL Functions in CDS Views Arithmetic Functions ABAP CDS offers a variety of built-in functions that supplement calculations with arithmetic expressions. Built-in Functions for Calculations • div(arg1,arg2) - Input: Only integer values (INT1, INT2, INT4, INTS or DEC, CURR, QUAN with decimals= 0) - Result type: type of arg 1 - Result a I ways rounded to integer value • mod(arg1,arg2) - Input Only integer types (INT1, INT2, INT4, INTS) - Result type: type of arg1 - Result can be negative • division(arg1, arg2, dee) - Input Integer values, values with fixed decimal (Types INT1, INT2, INT4, INT8 and DEC, CURR, QUAN with any number of decimals) - Result type: DEC with dee decimal places, length depends on type of a,gl - Result is always rounded to dee decimals Figure 66: Numeric Functions (1) The main differences between functions div( ) and division( ) are as follows: Input: Div( ) only allows integer values as input. Division( ) only excludes floating point numbers (binary or decimal). Result: Div( ) always returns an integer value as result. Division( ) allows you to specify the precision of the result. © Copyright. All rights reserved. 93 Unit 3: More SQL Features in CDS Views Note: With respect to the signs, functions div( ) and mod( ) behave differently than the ABAP operators DIV and MOD. In SQL function div( ), the amounts of the arguments are divided and then the sign is assigned (positive if the arguments have the same signs, and negative if they have different signs). Accordingly, the result of MOD can be negative. The ABAP operator MOD, on the other hand, only produces positive results. Ill Built-in Rounding Functions abs(arg) abs( 1.5)::!l 1 - returns the absolut amount of arg, abs( -1.5) = -1 flo,or( 1.5) floor( -1.5) = = -2 ceil( 1.5) ceil( �1.5) = = �1 i.e always rounds towards zero • floor(arg), - rounds to the next lower integer i.e. towards zero ifarg > 0, away from zero ifarg < 0 ceil(arg), - rounds to the next higher integer i.e. away from zero if arg > 0, towards zero if a rg < 0 1 2 • round(arg,pos), - pos > 0: Round arg to pos decimal places - pos -c I o: Round arg to position round(3 .. 1514, 2) round(273.15,-1) = 3.15 = 270 Figure 67: Numeric Functions (2) String Functions ABAP CDS offers a variety of built-in functions for string processing. Some of them were already available in release NW 7.40, some others are new in NW 7.50. 94 © Copyright. All rights reserved. Lesson: Using Built-in SQL Functions in CDS Views Some Built-in Functions for String Processing (NW 7.40) concat(arg1 ,arg2) - Returns resu It of type CHAR or SSTR I NG (depending on types of arg 1 and arg2) - All trailing blanks are removed - Corresponds toABAP statement CONCATENATE without addition SEPJmATED BY replace{arg1, arg2, arg3) - Result type depends on type of arg1 - corresponds to ABAP statement REPLACE ALL OCCURENCES OF arg2 IN arg1 RITH arg3. substri ng(arg,p·os,len) - Result type depends on type of arg - Similar to ABAP function substring[) or direct substring access: dobj [ +off] [ ( lenl I Important difference: pos denotes the position not the offset! .. J • Figure 68: String Processing Functions(1) The figure shows some important string functions available as off NW 7.40. A complete list can be found in the ABAP language help. Some Built.in Functions for String Processing (NW 7.50) concat_with_spa.ce(arg1,arg2,count) - Like concat( ) but with count spaces between arg1 and arg2 - Similart:oABAP statement CONCATENATEWithaddition SEPARATED BY • length(arg) - Returns resu It of type I NT 4 - Trailing blanks do not count - Corresponds to ABAP built-in fu net ion n umof char < ) • left,(arg,n) and right(arg,n) - Similar to substring(), but returns first or last n characters of arg - left{ ) corresponds to ABAP expression arg ( n) l Figure 69: String Processing Functions(2) In NW 7.50 the existing functions for string processing were supplemented to fill gaps and to cover special cases. The figure shows some examples. A complete list can be found in the ABAP language help. Note: Built-in functions can be chained at will. This was actually used quite often, when in NW 7.40 function concat_with_space was not yet available. The solution based on function concat looked like this: concat(concat(arg1,' '),arg2) © Copyright. All rights reserved. 95 Unit 3: More SQL Features in CDS Views I @AbapCatalog. sqlViewNlame: 'S4D430_FUNCCHAR, define view s4d430 - Function_strirng as select from scarr { car-r-Id, carrname, concat(carrid,carrname) as col _concat, concat_with_space(carrid,carrname,3) as col con cat _space, replace(carrname, 'HaNs', 'fritz') as col _replace, substring(carrname,5,4) as col _substring, length (car-r-Id) as col _length II II II => 'LH => 'Lufthansa' -=> 'l.H1ufthansa' II => 'LH II => 'Luftfritza' II => 'hans' Lufthansa' II => 2 (trailing blank!) } where carrname = 'Lufthansa' I Figure 70: Example: String Processing in a CDS View The figure above gives some examples of string processing in CDS Views. Note: ● ● ● The second argument of function replace( ) is upper-case but content of carrname is lower-case. The second argument of function substring( ) is 5, not 4! Function length( ) returns value 2 because the third character in CARRID is a trailing blank Coalesce Currency and Unit Conversion Amounts and measurements are usually stored on the database in a source unit and source currency. To make values in different units or currencies comparable with each other, they need to be converted. Traditionally, we do these conversions with standard function modules provided by SAP (e.g. UNIT_CONVERSION_SIMPLE or CONVERT_TO_LOCAL_CURRENCY). 96 © Copyright. All rights reserved. Lesson: Using Built-in SQL Functions in CDS Views Built-in functions • Unit_Conversion(p1 => al, p2 => az , .•• ) - Returns result of type abap.quan - Converts a quantity in source unit into a value in target unit - Ru less maintained in transaction CUNI and stored in database table T()()6 • Currency_conversion(pl => a1, p2 => a2, .•• ) - Returns result of type abap.curr - Converts an amount in source currenoy into a value in target currency - Based on the exchange rale valid on a target date - Rules maintained in transaction OB08 and stored in database tables TCUR .... General Remairks - Pcarameter assignment with operator "=>" - Komma-separated Parameters - Optional parameter error_handling with default value "FAIL_ON_ERROR" Other options: "SET_TO_NULL" and "KEEP_UNCONVERTED" - Result may depend on the database (different rounding rules) ,I Figure 71: Currency and Unit Conversions The function modules make use of conversion rules that are maintained in standard transactions and stored in (client-dependent) tables. ABAP CDS allows you to move the conversions from the ABAP stack onto database level. Two built-in functions are available to implement conversions in the DDL Source. Note: Although the built-in functions use the same rules and logic as the corresponding ABAP function modules, you must not expect the exact same results. This is obvious when you take into consideration that different rounding rules may apply for calculations on the database and for calculations in ABAP. @Abapcata og. sqlV' ewNlame: 'S4D430_FUNCCONrV1' define view S4d430_Function_Convertion1 as select from spfli { carrid, connid, @Semant ·cs.quantity .un · tOfMeasure: Casting of literal 'Ml' into expected type 'DIST ID' Unit_C:onversion( quantity => distance, source_unit => distid, target_unit => cast( 'MI' as abap.uni:t) ) as distance, @Semant"cs.unitOfMeasure: true cast( 'MI' as abop , unit) as distid Parameter assignment with operator .,=>" Figure 72: Example: Unit Conversion From Kilometers to Miles Database table SPFLI contains a field DISTANCE in which the flight distance is stored for each flight connection. The corresponding unit of measure is found in field DISTID. © Copyright. All rights reserved. 97 In the CDS View definition above, the value in table field DISTANCE is converted into miles ("MI") and returned as view field DISTANCE. Literal "MI" is returned as view field DISTID. Semantics annotations are used to link the two view fields to each other. Note: The text literal has to be converted into ABAP Dictionary type Unit twice: To make it compatible with input parameter target_unit and to make use of annotation Semantics.unitOfMeasure. @AbapCatalog. sqlViewName: 'S4D430_FUNCCONrV2' define view s4d430_Function_Conversion2 as select from sfliglht { carrid, connid, fldate, @Semantics. amount. c ur-r-encyccde: 'CURRENCY' currency_conve,rsion ( aa) price, amount source_currency round => currency, => 'X'' target_currency exchange_rate_type exchange_rate_;date aa) error_handling => aa) aa) Casting of literal 'USO' into expected type cast( 'USO' as abap. cuky), 'M'' fldate., I SET_ TO_NUILL I ) as price, @Semantics.cu rren cyCode: true cast(' USD' as abap . cuny ) as currency } Behaviour in Case of error Figure 73: Example: Currency Conversion Database table SFLIGHT contains a field PRICE in which the standard ticket price is stored for each flight. The corresponding currency code is found in field CURRENCY. In the CDS View definition above, the value in table field PRICE is converted into US Dollar ("USD") and returned as view field PRICE. Literal "USD" is returned as view field CURRENCY. Semantics annotations are used to link the two view fields to each other. Note: The text literal has to be converted into ABAP Dictionary type CUKY twice: To make it compatible with input parameter target_currency and to make use of annotation Semantics.currencyCode. ERROR: stackunderflow OFFENDING COMMAND: ~ STACK: Unit 3: More SQL Features in CDS Views With other options, you can make the function return the NULL value, the initial value ('00000000') or the unaltered input value. 100 © Copyright. All rights reserved. Unit 3 Exercise 7 Use Built-in Functions in a CDS View Business Example Template: S4D430_EXPRESSIONS (DDL Source) Solution: S4D430_FUNCTIONS (DDL Source) Create a copy of your DDL Source For the next exercise you need a copy of your solution of the previous exercise (DDL Source Z##_EXPRESSIONS). If you did not complete the previous exercise you can copy from DDL Source S4D430_EXPRESSIONS. 1. In your own Package, create a new DDL Source (suggested name: Z##_FUNCTIONS, where ## stands for your group number) based on template defineView. 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##FUNC). 3. Open the DDL Source you want to duplicate and copy the FROM clause, the field list and the WHERE clause to the new DDL Source. Use String Function concat_with_space( ) 1. In the field list, replace the name of the flight customer (field NAME) with string function concat_with_space( ) to concatenate the two fields SALUTATION and NAME. Note: This function is available as of AS ABAP 7.50. In AS ABAP 7.40 a nested call of function concat( ) had to be used to achieve the same result. Use Arithmetic Function division( ) 1. In the calculation of the discount, replace the arithmetic expression with arithmetic function division( ). Make sure the result is given with two decimal places. 2. What is the advantage of using this function? © Copyright. All rights reserved. 101 Unit 3: More SQL Features in CDS Views 3. Do you still need to cast the value of field discount befor you can use it as input for the function? Perform a Currency Conversion Use function currency_conversion( ) so that field AMOUNT returns the booking price in currency USD (US Dollar). 1. In the field list, replace field loccuram with a call of built-in function currency_conversion( ). Hint: Use the editor’s auto-completion capabilities to generate the function call and parameter list. 2. Use fields LOCURRAM and LOCURKEY as input values for parameters source_amount and source_currency. 3. Set the target currency to literal value “USD.” Why is the literal “USD” itself not compatible with the functions input parameter target_currency? 4. Choose exchange rate type “M” and do the calculation based on the exchange rate that was valid on the day of booking (field ORDER_DATE). 5. Make sure that for all bookings, field currency returns the literal “USD” rather than the value of table field LOCURKEY. Calculate the Number of Days between two Dates Calculate the number of days between the purchase of the ticket (field ORDER_DATE) and the actual flight date (field FLDATE). 1. In the field list, add a new field after the field ORDER_DATE (suggested name: DAYS_AHEAD). Use function dats_days_between( ) to calculate the number of days between the date fields FLDATE and ORDER_DATE Activate and Test 1. Activate the DDL Source. 2. Open the Data Preview for the CDS View and ensure that the displayed data are correct. 102 © Copyright. All rights reserved. Unit 3 Solution 7 Use Built-in Functions in a CDS View Business Example Template: S4D430_EXPRESSIONS (DDL Source) Solution: S4D430_FUNCTIONS (DDL Source) Create a copy of your DDL Source For the next exercise you need a copy of your solution of the previous exercise (DDL Source Z##_EXPRESSIONS). If you did not complete the previous exercise you can copy from DDL Source S4D430_EXPRESSIONS. 1. In your own Package, create a new DDL Source (suggested name: Z##_FUNCTIONS, where ## stands for your group number) based on template defineView. a) See the corresponding step in the previous exercise. 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##FUNC). a) See source code extract from the model solution. 3. Open the DDL Source you want to duplicate and copy the FROM clause, the field list and the WHERE clause to the new DDL Source. a) See the corresponding step in the previous exercise. Use String Function concat_with_space( ) 1. In the field list, replace the name of the flight customer (field NAME) with string function concat_with_space( ) to concatenate the two fields SALUTATION and NAME. Note: This function is available as of AS ABAP 7.50. In AS ABAP 7.40 a nested call of function concat( ) had to be used to achieve the same result. a) See source code extract from the model solution. Use Arithmetic Function division( ) 1. In the calculation of the discount, replace the arithmetic expression with arithmetic function division( ). Make sure the result is given with two decimal places. a) See source code extract from the model solution. © Copyright. All rights reserved. 103 Unit 3: More SQL Features in CDS Views 2. What is the advantage of using this function? The function supports many different numeric data types as input — not only type abap.fltp and it returns the result in type abap.dec with the possibility to set the number of decimal places for the result. 3. Do you still need to cast the value of field discount befor you can use it as input for the function? Yes. because the table field has type NUMC which is a character- like data type. Perform a Currency Conversion Use function currency_conversion( ) so that field AMOUNT returns the booking price in currency USD (US Dollar). 1. In the field list, replace field loccuram with a call of built-in function currency_conversion( ). Hint: Use the editor’s auto-completion capabilities to generate the function call and parameter list. a) See source code extract from the model solution. 2. Use fields LOCURRAM and LOCURKEY as input values for parameters source_amount and source_currency. a) See source code extract from the model solution. 3. Set the target currency to literal value “USD.” Why is the literal “USD” itself not compatible with the functions input parameter target_currency? The parameter expects an input value pf type abap.cuky. a) See source code extract from the model solution. 4. Choose exchange rate type “M” and do the calculation based on the exchange rate that was valid on the day of booking (field ORDER_DATE). a) See source code extract from the model solution. 5. Make sure that for all bookings, field currency returns the literal “USD” rather than the value of table field LOCURKEY. a) See source code extract from the model solution. Calculate the Number of Days between two Dates Calculate the number of days between the purchase of the ticket (field ORDER_DATE) and the actual flight date (field FLDATE). 1. In the field list, add a new field after the field ORDER_DATE (suggested name: DAYS_AHEAD). Use function dats_days_between( ) to calculate the number of days between the date fields FLDATE and ORDER_DATE 104 © Copyright. All rights reserved. Lesson: Using Built-in SQL Functions in CDS Views a) See source code extract from the model solution. Activate and Test 1. Activate the DDL Source. a) See the corresponding step in the previous exercise. 2. Open the Data Preview for the CDS View and ensure that the displayed data are correct. a) See the corresponding step in the previous exercise. DDL Source S4D430_FUNCTIONS @AbapCatalog.sqlViewName: 'S4D430FUNC' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'Solution: Functions' define view S4D430_Functions as select from sbook as b inner join scustom as c on b.customid = c.id { key b.carrid, key b.connid, key b.fldate, key b.bookid, case b.class when 'Y' then 'Economy' when 'C' then 'Business' when 'F' then 'First' else '???' end as class, currency_conversion( amount => b.forcuram, source_currency => b.forcurkey, round => 'X', target_currency => cast( 'USD' as abap.cuky), exchange_rate_type => 'M', exchange_rate_date => b.order_date, error_handling => 'SET_TO_NULL' ) as amount @<Semantics.amount.currencyCode:'CURRENCY', cast('USD' as abap.cuky) as currency @<Semantics.currencyCode: true, b.luggweight @<Semantics.amount.currencyCode: 'WUNIT', b.wunit @<Semantics.currencyCode: true, b.order_date, dats_days_between(b.order_date, b.fldate) as days_ahead, b.agencynum, b.counter, b.customid, concat_with_space(c.form, c.name, 1) as name, // Workaround in 7.40 // concat(concat( c.form, ' '), c.name) as name, c.street, c.postcode, c.city, c.country, @EndUserText.label: 'Discount Factor' @EndUserText.quickInfo: 'Customer Specific Discount Factor' division(cast(c.discount as abap.int4), 100, 2) as discount } where cancelled <> 'X' © Copyright. All rights reserved. 105 Unit 3: More SQL Features in CDS Views LESSON SUMMARY You should now be able to: ● 106 Use Built-in SQL Functions in CDS Views © Copyright. All rights reserved. Unit 3 Lesson 3 Understanding Nested Views LESSON OBJECTIVES After completing this lesson, you will be able to: ● Define CDS Views Based on Other CDS Views CDS Views Based on Other CDS Views Up to now, our CDS Views were all based on a single database table or on a join of several database tables. In CDS you can also define CDS views that are based on one or more other CDS Views. This is sometimes referred to as “View on View concept” or as “Nested Views”. CDS Views as data source of other CDS Views - Join of CDS Viev.rs and join of CDS View with DB table supported - No technical limit of nesting depth and complexity • Improved Re-use - e.g. calou lation done in one basis view that is used in several other views instead of coding (and maintaining) identical expressions • Improved Readability - e.g. join of 2 Views that contain joins instead of a complicated join of many tables Figure 76: Nested Views (View on View Concept) Building Nested Views is another important difference between the classical database views in ABAP Dictionary and the new CDS Views. The big advantages are the improved re-use of views and the improved readability. Note: Regarding the advantages there is a striking similarity with the advantages of modularization of source code. © Copyright. All rights reserved. 107 Unit 3: More SQL Features in CDS Views Advantages and Pitfalls • Unintended Circular References - Ever1tually, all views have to be based on tables - Circular references are not allowed - At the moment, circular references lead to timeouts during activation • Too many Nesting Levels - increase the likelihood for recursive references - deteriorate the rea.dability of the model - increase the likelihood for redundancies Figure 77: Pitfalls of Nested Views Recommendations G,roup your views into levels {preferably 3 levels) Only access views that are assigned to a lower level I 108 Figure 78: Recommendations for Nested Views © Copyright. All rights reserved. Unit 3 Exercise 8 Define a CDS View based on other CDS Views Business Example Template: S4D430_FUNCTIONS (DDL Source) Solution: S4D430_BOOKING (DDL Source) S4D430_CUSTOMER (DDL Source) S4D430_BOOKING_AND_COSTOMER (DDL Source) Define a CDS View that returns only the booking-related information In this exercise you want to define a new CDS View that returns only the booking-related information from your solution of the previous exercise (DDL Source Z##_FUNCTIONS). If you did not complete the previous exercise you can copy from DDL Source S4D430_FUNCTIONS. 1. In your own package, create a new DDL Source (suggested name: Z##_BOOKING, where ## stands for your group number) based on template defineView. 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##BOOK). 3. In the FROM clause of the SELECT statement specify database table SBOOK as data source. 4. Open DDL Source Z##_FUNCTIONS (or DDL Source S4D430_FUNCTIONS) and copy the field list and the WHERE clause to the new DDL Source. 5. Remove everything from the field list, that is based on SCUSTOM. Hint: If you specify an alias for table SBOOK you can leave the rest of field list unchanged. 6. Activate the DDL Source. Define a CDS View that returns only the customer-related information In this exercise you want to define a new CDS View that returns only the customer-related information from your solution of the previous exercise (DDL Source Z##_FUNCTIONS). If you did not complete the previous exercise you can copy from DDL Source S4D430_FUNCTIONS. © Copyright. All rights reserved. 109 Unit 3: More SQL Features in CDS Views 1. In your own package, create a new DDL Source (suggested name: Z##_CUSTOMER, where ## stands for your group number) based on template defineView. 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##CUST). 3. In the FROM clause of the SELECT statement specify database table SCUSTOM as data source. 4. Open DDL Source Z##_FUNCTIONS (or DDL Source S4D430_FUNCTIONS) and copy the field list to the new DDL Source. 5. Remove everything from the field list, that is based on SBOOK. Hint: If you specify an alias for table SCUSTOM you can leave the rest of field list unchanged. 6. Activate the DDL Source. Define a CDS View that combines data from the two CDS Views You now want to define a new CDS View that returns exactly the same information as your solution of the previous exercise (DDL Source Z##_FUNCTIONS). But instead of reading from the database tables directly and doing the calculations itself, the new CDS View will read from two other CDS Views that encapsulate the calculations. 1. In your own Package, create a new DDL Source (suggested name: Z##_BOOKING_AND_CUSTOMER, where ## stands for your group number) based on template defineView. 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##BOOKCUST). 3. Open the DDL Source Z##_FUNCTIONS (or DDL Source S4D430_FUNCTIONS) and copy the FROM clause, the field list and the WHERE clause to the new DDL Source. 4. In the new DDL Source, edit the FROM clause. Replace tables SBOOK and SCUSTOM with the two CDS Views you created earlier in this exercise (Z##_Booking and Z##_Customer). 5. Edit the field list. Remove all components with expressions and functions and replace them with the corresponding fields of the CDS Views. Note: If you copied the WHERE clause, too, don’t forget to remove it. It is superfluous in Z##_Booking_And_Customer as it is already contained in CDS View Z##_Booking. Activate and Test 1. Activate the DDL Sources. 2. Open the Data Preview for CDS View S4D430_BOOKING_AND_CUSTOMER and ensure that the displayed data are correct. 110 © Copyright. All rights reserved. Unit 3 Solution 8 Define a CDS View based on other CDS Views Business Example Template: S4D430_FUNCTIONS (DDL Source) Solution: S4D430_BOOKING (DDL Source) S4D430_CUSTOMER (DDL Source) S4D430_BOOKING_AND_COSTOMER (DDL Source) Define a CDS View that returns only the booking-related information In this exercise you want to define a new CDS View that returns only the booking-related information from your solution of the previous exercise (DDL Source Z##_FUNCTIONS). If you did not complete the previous exercise you can copy from DDL Source S4D430_FUNCTIONS. 1. In your own package, create a new DDL Source (suggested name: Z##_BOOKING, where ## stands for your group number) based on template defineView. a) See the corresponding step in the previous exercise. 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##BOOK). a) See source code extract from the model solution. 3. In the FROM clause of the SELECT statement specify database table SBOOK as data source. a) See source code extract from the model solution. 4. Open DDL Source Z##_FUNCTIONS (or DDL Source S4D430_FUNCTIONS) and copy the field list and the WHERE clause to the new DDL Source. a) See the corresponding step in the previous exercise. 5. Remove everything from the field list, that is based on SCUSTOM. Hint: If you specify an alias for table SBOOK you can leave the rest of field list unchanged. a) See source code extract from the model solution. 6. Activate the DDL Source. © Copyright. All rights reserved. 111 Unit 3: More SQL Features in CDS Views a) See the corresponding step in the previous exercise. DDL Source S4D430_BOOKING @AbapCatalog.sqlViewName: 'S4D430_BOOK' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'Solution: Flight Booking w Calculations' define view S4D430_Booking as select from sbook as b { key b.carrid, key b.connid, key b.fldate, key b.bookid, case b.class when 'Y' then 'Economy' when 'C' then 'Business' when 'F' then 'First' else '???' end as class, currency_conversion( amount => b.forcuram, source_currency => b.forcurkey, round => 'X', target_currency => cast( 'USD' as abap.cuky), exchange_rate_type => 'M', exchange_rate_date => b.order_date, error_handling => 'SET_TO_NULL' ) as amount @<Semantics.amount.currencyCode:'CURRENCY', cast('USD' as abap.cuky) as currency @<Semantics.currencyCode: true, b.luggweight @<Semantics.amount.currencyCode: 'WUNIT', b.wunit @<Semantics.currencyCode: true, b.order_date, dats_days_between(b.order_date, b.fldate) as days_ahead, b.agencynum, b.counter, b.customid } where cancelled <> 'X' Define a CDS View that returns only the customer-related information In this exercise you want to define a new CDS View that returns only the customer-related information from your solution of the previous exercise (DDL Source Z##_FUNCTIONS). If you did not complete the previous exercise you can copy from DDL Source S4D430_FUNCTIONS. 1. In your own package, create a new DDL Source (suggested name: Z##_CUSTOMER, where ## stands for your group number) based on template defineView. a) See the corresponding step in the previous exercise. 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##CUST). a) See source code extract from the model solution. 112 © Copyright. All rights reserved. Lesson: Understanding Nested Views 3. In the FROM clause of the SELECT statement specify database table SCUSTOM as data source. a) See source code extract from the model solution. 4. Open DDL Source Z##_FUNCTIONS (or DDL Source S4D430_FUNCTIONS) and copy the field list to the new DDL Source. a) See the corresponding step in the previous exercise. 5. Remove everything from the field list, that is based on SBOOK. Hint: If you specify an alias for table SCUSTOM you can leave the rest of field list unchanged. a) See source code extract from the model solution. 6. Activate the DDL Source. a) See the corresponding step in the previous exercise. DDL Source S4D430_CUSTOMER @AbapCatalog.sqlViewName: 'S4D430_CUST' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'Solution: Flight Customer w Calculations' define view s4d430_Customer as select from scustom as c { key c.id, concat_with_space(c.form, c.name, 1) as name, // concat(concat( c.form, ' '), c.name) as name, // Workaround in 7.40 c.street, c.postcode, c.city, c.country, @EndUserText.label: 'Discount Factor' @EndUserText.quickInfo: 'Customer Specific Discount Factor' division(cast(c.discount as abap.int4), 100, 2) as discount } Define a CDS View that combines data from the two CDS Views You now want to define a new CDS View that returns exactly the same information as your solution of the previous exercise (DDL Source Z##_FUNCTIONS). But instead of reading from the database tables directly and doing the calculations itself, the new CDS View will read from two other CDS Views that encapsulate the calculations. 1. In your own Package, create a new DDL Source (suggested name: Z##_BOOKING_AND_CUSTOMER, where ## stands for your group number) based on template defineView. a) See the corresponding step in the previous exercise. 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##BOOKCUST). a) See source code extract from the model solution. © Copyright. All rights reserved. 113 Unit 3: More SQL Features in CDS Views 3. Open the DDL Source Z##_FUNCTIONS (or DDL Source S4D430_FUNCTIONS) and copy the FROM clause, the field list and the WHERE clause to the new DDL Source. a) See the corresponding step in the previous exercise. 4. In the new DDL Source, edit the FROM clause. Replace tables SBOOK and SCUSTOM with the two CDS Views you created earlier in this exercise (Z##_Booking and Z##_Customer). a) See source code extract from the model solution. 5. Edit the field list. Remove all components with expressions and functions and replace them with the corresponding fields of the CDS Views. Note: If you copied the WHERE clause, too, don’t forget to remove it. It is superfluous in Z##_Booking_And_Customer as it is already contained in CDS View Z##_Booking. a) See source code extract from the model solution. DDL Source S4D430_BOOKING_AND_CUSTOMER @AbapCatalog.sqlViewName: 'S4D430_BOOKCUST' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'Solution: Join of Booking and Customer' define view S4d430_Booking_And_Customer as select from S4D430_Booking as b inner join s4d430_customer as c on b.customid = c.id { key b.carrid, key b.connid, key b.fldate, key b.bookid, b.customid, b.amount, b.currency, b.days_ahead, c.name, c.street, c.postcode, c.city, c.country } Activate and Test 1. Activate the DDL Sources. a) See the corresponding step in the previous exercise. 2. Open the Data Preview for CDS View S4D430_BOOKING_AND_CUSTOMER and ensure that the displayed data are correct. a) See the corresponding step in the previous exercise. 114 © Copyright. All rights reserved. Lesson: Understanding Nested Views LESSON SUMMARY You should now be able to: ● Define CDS Views Based on Other CDS Views © Copyright. All rights reserved. 115 Unit 3 Lesson 4 Using Aggregations in CDS Views LESSON OBJECTIVES After completing this lesson, you will be able to: ● Use Aggregate Functions, Group By And Having in CDS Views Aggregate Expressions Aggregate Functions Operand can be a field of the data source MIN( operand) a.nd MAXi( operand) - Returns the smallest/greatest value in operand a literal a case distinction SUM( operand) - Calculates the sum of lhe values or operand • AVG( oper:and) - Calculates the average value of the values of operand • COUNT(") - Returns the number of entries in the resu It set • COUNT( DISTINCT operand) - Returns the number of distinct values of operand Figure 79: Aggregate Functions An aggregate expression calculates a single value from an operand (operand) by calling an aggregate function for multiple rows of a results set. The figure above shows the possible aggregate functions. Aggregate expressions can be used in the field list of a SELECT statement or in an (optional) HAVING clause. Note: For aggregate functions in the field list, it is mandatory to provide an alias (addition AS). Regarding the result type, the following rules apply: ● 116 The result type of expression AVG is type FLTP. © Copyright. All rights reserved. Lesson: Using Aggregations in CDS Views ● Expressions COUNT and COUNT( DISTINCT …) return an integer value. ● Expressions MIN, MAX, and SUM have the same result type as operand. Usually, operand is a column or field in the data source of the current CDS View. Other options for operand are: ● Literals ● Case distinctions @Abap(atalog. sql ViewName: 'S4D430AGGREGATE ' define view S4d430_Aggregates as select from sflight Alias name mandatory for aggregate expressions { count(*) as c,ol_count, count(distinct planetype) as col_cnt-dist, sumi( seatsocc ) as ,c,ol_sum1; avg ( seatsocc ) as col_avg, max( seatsocc) as c,ol_max, min( seatsocc ) as col_min as ce l_li te ral.1 sum( 1 ) sumi( case 11,1hen seatsocc > seatsmax then 1 else 0 Sum of literal 1 (Same result as count( *) ) I Sum of a case distinction (Count overbooked flights) end ) as col_overbooked } Figure 80: Example: Aggregate Functions The example above shows one example for each aggregate function. The last two elements of the field list are examples of alternative operands. l@Aba pCatalog. sql ViewName: 'S4D430_AGGRGRP1' define view S4D430_Aggregat,es_Group_By_l as select from sflight { car rid, conn id, count(*) avg( seatsocc as col_count, as col_avg, } I group by carrid, Field list consists not only of aggregate expressions I GOUP BY is need for all fields in the field list con1nid I @Abapcatalog. sqlViewName: '54D430_AGGRGRP2' define view $4D430_Aggregat:,es_Group_By_2 as select from sflight: { concart_w.ith_space(ca1rrid" cennfd, 1) as ID, count(*) as col_count, as col_avg, avg( seat sncc ) group by carrid;, connid 1 Field list contans expression or function l Arguments of the expression or function listed individually Figure 81: Example: Aggregate Functions with GROUP BY © Copyright. All rights reserved. 117 Addition GROUP BY groups those rows in the result set that have the same content in the elements specified by the fields field1, field2, ... as a single row. The fields must be specified using the same names as the fields in the data source. Any elements of the CDS view that are not specified after GROUP BY must be defined in the SELECT list using aggregate expressions. Conversely, GROUP BY must be used if aggregate expressions are contained in the SELECT list and all elements not defined using aggregate expressions must be specified after GROUP BY. Literals and other expressions cannot be specified after GROUP BY. If expressions or calls of predefined functions are specified as elements of the SELECT list using aggregate expressions, all the fields used must be specified in the GROUP BY clause. Hint: The ABAP DDL Source Editor is able to generate the correct GROUP BY clause automatically from the element list of the view. You can use this feature as follows: ● Go to the Problemstab below the editor. ● Expand node Errors. ● Right-click error message GROUP BY clause is missing and choose Quick Fix. ● On the following dialog window, choose Finish. ERROR: stackunderflow OFFENDING COMMAND: ~ STACK: Unit 3: More SQL Features in CDS Views 120 © Copyright. All rights reserved. Unit 3 Exercise 9 Define a CDS View with Aggregation Business Example Template: Solution: S4D430_CUSTOMER_WITH_REVENUE (DDL Source) Create a New DDL Source 1. In your own Package, create a new DDL Source (suggested name: Z##_CUSTOMER_WITH_REVENUE, where ## stands for your group number) based on template defineView. 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##CUSTREV). Let the New View Read Data from Z##_Booking_And_Customer 1. In the new DDL Source, edit the FROM clause. Make the new CDS View read data from the CDS View you created in the previous exercise (Z##_Booking_And_Customer). If you did not complete the previous exercise, you can read from CDS View S4D430_Booking_And_Customer instead. 2. Edit the field list. Add field CUSTOMID as key field and provide an alias name ID. 3. Add name and address data of the customer (name, street, postcode, city, country). Add Aggregations and a GROUP BY clause 1. Edit the field list. Add a sum over the converted amount. Specify an alias name ( suggested value: amount) for the sum. 2. After the sum, add the corresponding currency code. 3. Add the required semantics annotation to link the sum to the field with the currency code. Why is it not necessary to denote field CURRENCY as currency field? 4. Add the average over field DAYS_AHEAD (i.e. the number of days between booking date and flight date). Specify an alias name (suggested value: days_ahead) for this average. © Copyright. All rights reserved. 121 Unit 3: More SQL Features in CDS Views 5. Add a GROUP BY clause that lists all fields from the field list that are not aggregate functions. Hint: You can use the Quick Fix for the respective error message to let the editor insert the correct GROUP BY clause. Activate and Test 1. Activate the new DDL Source. 2. Open the Data Preview for the CDS View and ensure that the displayed data are correct. 122 © Copyright. All rights reserved. Unit 3 Solution 9 Define a CDS View with Aggregation Business Example Template: Solution: S4D430_CUSTOMER_WITH_REVENUE (DDL Source) Create a New DDL Source 1. In your own Package, create a new DDL Source (suggested name: Z##_CUSTOMER_WITH_REVENUE, where ## stands for your group number) based on template defineView. a) See the corresponding step in the previous exercise. 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##CUSTREV). a) See source code extract from the model solution. Let the New View Read Data from Z##_Booking_And_Customer 1. In the new DDL Source, edit the FROM clause. Make the new CDS View read data from the CDS View you created in the previous exercise (Z##_Booking_And_Customer). If you did not complete the previous exercise, you can read from CDS View S4D430_Booking_And_Customer instead. a) See source code extract from the model solution. 2. Edit the field list. Add field CUSTOMID as key field and provide an alias name ID. a) See source code extract from the model solution. 3. Add name and address data of the customer (name, street, postcode, city, country). a) See source code extract from the model solution. Add Aggregations and a GROUP BY clause 1. Edit the field list. Add a sum over the converted amount. Specify an alias name ( suggested value: amount) for the sum. a) See source code extract from the model solution. 2. After the sum, add the corresponding currency code. a) See source code extract from the model solution. 3. Add the required semantics annotation to link the sum to the field with the currency code. a) See source code extract from the model solution. © Copyright. All rights reserved. 123 Unit 3: More SQL Features in CDS Views Why is it not necessary to denote field CURRENCY as currency field? Annotation @Semantics.currencyCode: true is inherited from the source CDS View. 4. Add the average over field DAYS_AHEAD (i.e. the number of days between booking date and flight date). Specify an alias name (suggested value: days_ahead) for this average. a) See source code extract from the model solution. 5. Add a GROUP BY clause that lists all fields from the field list that are not aggregate functions. Hint: You can use the Quick Fix for the respective error message to let the editor insert the correct GROUP BY clause. a) See source code extract from the model solution. Activate and Test 1. Activate the new DDL Source. a) See the corresponding step in the previous exercise. 2. Open the Data Preview for the CDS View and ensure that the displayed data are correct. a) See the corresponding step in the previous exercise. DDL Source S4D430_CUSTOMER_WITH_REVENUE @AbapCatalog.sqlViewName: 'S4D430_CUSTREV' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'Solution: Customer w Aggregated Values' define view S4d430_Customer_With_Revenue as select from S4d430_Booking_And_Customer as c { key c.customid as id, c.name, c.street, c.postcode, c.city, c.country, sum(c.amount) as amount @<Semantics.amount.currencyCode: 'currency', c.currency, //@<Semantics.currencyCode: true, avg(c.days_ahead) as days_ahead } group by c.customid, c.name, c.postcode, c.street, c.city, c.country, c.currency 124 © Copyright. All rights reserved. Lesson: Using Aggregations in CDS Views LESSON SUMMARY You should now be able to: ● Use Aggregate Functions, Group By And Having in CDS Views © Copyright. All rights reserved. 125 Unit 3 Lesson 5 Using Additional Join Types and UNION (ALL) LESSON OBJECTIVES After completing this lesson, you will be able to: ● Understand Additional Join Types ● Understand UNION and UNION ALL Outer Joins SQL supports a large variety of join types. Only Inner Joins are supported in classical database views in ABAP Dictionary. L 2 3 4 5 x 3 4 5 Figure 83: Reminder: Inner Join As a reminder, the picture above illustrates an inner join: One row of the left table and one row of the right table are combined to a common result row if they fulfill the JOIN condition. 126 © Copyright. All rights reserved. Lesson: Using Additional Join Types and UNION (ALL) • Left Outer Join - Special treatment for left table - Resu It set may contain entries of left table without matching entries in right table - Supported in classical Open SOL Right Outer Join Special treatment for right table - Result set may contain entries of right table without matching entries in left table - Supported in Open SQL (as off NW 7.40 SP05) and ABAP CDS Full Outer Join - Special treatment for both tables - Resu It set may contain entries of left table without matching entries in right table - Result set may contain entries of right table without matching entries in left table - Not yet supported in Open SQL and ABAP CDS I • Figure 84: Types of Outer Joins SQL standard knows three (sub)types of outer joins. L x 2 NULL NULL NULL NULL 3 4 5 Figure 85: Left Outer Join In a left outer join, one row of the left table and one row of the right table are combined to a common result row if they fulfill the JOIN condition (like in inner joins). 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. A left outer join ensures that any entry of the left table that fulfills the selection criteria appears at least once in the join result. © Copyright. All rights reserved. 127 Unit 3: More SQL Features in CDS Views Note: These NULL values are set to a type-friendly initial value when the CDS view is used in Open SQL. NULL L 2 3 4 5 x 3 4 5 6 NULL NULL 7 NULL NULL Figure 86: Right Outer Join In a right outer join the role of left and right table are exchanged: 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. A right outer join ensures that any entry of the right table that fulfills the selection criteria appears at least once in the join result. 128 © Copyright. All rights reserved. Lesson: Using Additional Join Types and UNION (ALL) NULL L 2 3 4 5 x 11 NULL NULL 2 NULL NULL 3 4 5 6 7 NULL NULL NULL NULL Figure 87: Full Outer Join (not supported in ABAP CDS) In a full outer join, both tables are treated in the same way. Rows of both tables without matching row in the other table are copied to the query result. The missing values (from the other table) are filled with NULL values. I» Note: Full outer joins are not yet supported in Open SQL or ABAP CDS. As a work around, you can use a UNION (see later) of a left outer join and a right outer join. @AbapCatalog. sql ViewNlarne; 'S4D430_JOINRIGHT' define view S4d430_Join_Right_outer as select from spfli as c: right outer join sc:arr as a on c.carrid = a.carrid key a.carrid, a.carrname, c.connid, c. ci ty+r-on, c.cityto } cemd coanid No flight connections in table SPFLI for Carriers "AB", "AC" and "AF" <il)d,oo, 0011 N�IYOAA .Amerian.Air1inM 0064 Sl>INFIIANDSCO N[WYORK Air8e,t;a 0000 0000 0000 O�S'i RO E fRANl(flU.Rf Amtri<1r1Airli es A,,C,nJdo AirfrfllCC Alitllla Figure 88: Example: Right Outer Join © Copyright. All rights reserved. 129 Unit 3: More SQL Features in CDS Views The figure gives you an example of a CDS View with a right outer join. The Data Preview for this CDS View clearly shows the entries from the right table (SCARR) without matching entries in the left table (SPFLI). Cross Join I L x I y 3 4 -------- 2 3 R 5 �--,--............,,__.......,,,.....�IN Co� x y 3 4 2 2 2 3 3 3 5 3 4 5 3 4 5 Figure 89: Cross Join (As off Release 7.51) When two data sources are joined using CROSS JOIN, the result is the cross product of these two data source: All entries on the left side are combined with all entries on the right side. The number of rows in the results set is the number of rows on the left side multiplied by the number of rows on the right side. It is not possible to specify a join condition for cross joins. Note: A cross join behaves like an inner or outer join whose ON condition is always true. A cross join with a WHERE condition has the same result as an inner join with an identical ON condition. Unlike the inner join, in a cross join all data is read first before the condition is evaluated. In an inner join only data that meets the ON condition is read. 130 © Copyright. All rights reserved. Lesson: Using Additional Join Types and UNION (ALL) l@AbapCatalog.sqlViewName; 'S4D430_JOINCROSS' define view S4D430 JOIN CROSS as select from spfli-as cjcr,oss jo.1nl scal"r as a k.eyja.carr1a1as carrid_scarr, a.carrname., jc. ca rl"id jas cal"rid_spfli, c.connidi� c. ci tyfrom., c.cityto I} .:ii 100 row, retrieved • 3 rm ,��1 resuh) <!'1\id_�fli sa om AmfflunAirlin6 RO Ml <ilyfron, <rl,10 FAANl':l'UftT rn i';Wl FMN!J'UITT 8ERllN AmMunAillin� UA @all FA:AN!J'UITT SANFIUlN ... Ame,i.:.anA.iflinitS A?. ll-l Of om � TOKYO F�IIJ'UITT ROMt NfWVOIII: 0005 SING,11.PORE fAANKl'Ultf Amc,ionAirtln� Amak•n Ailline> l itonnid AmittlunAirtlnH Figure 90: Example: Cross Join • All Data Is Read - No preseleclion through a join condition Exception: If both tables are client specific an implicit join condition for the client field is used • Large Data Sources-· Huge Result Set - Number or results is always the product or the number of all r(W{S of both data sources Figure 91: Warnings Regarding Cross Join Caution: A cross join should only be used with extreme caution. Since it is not possible to specify an ON condition, all data of all involved data sources is read. In the case of very large datasets, the results set (whose number of rows is always the product of the number of all rows of both data sources) can quickly become very large. Multiple Joins • Explicit (with parantheses) or Implicit (no pa.rantheses) - Parentheses are recommended (makes the code easier to read) • Implicit Order of Evaluation INNER and OUTER JOINS: Arrangement of the ON conditions - CROSS JOINS from left to right Figure 92: Nested Join Expressions – Order of Evaluation © Copyright. All rights reserved. 131 Unit 3: More SQL Features in CDS Views The FROM clause of a CDS View definition allows nested join expressions. You can use parentheses (brackets) in order to influence the sequence in which the system evaluates these nested expressions. Note: The use of parentheses is recommended for making the code easier to read and to avoid unexpected behavior. Without parentheses, nested join expressions are evaluated in the following order: ● ● In the case of inner and outer joins, by the arrangement of the ON conditions. From left to right, the most adjacent ON conditions are assigned to each JOIN and this expression is parenthesized implicitly. Cross joins are evaluated from left to right. Note: If several cross joins are combined, the order of the evaluation is irrelevant. The result is always the same and the number of rows is the product of the number of rows of all involved data sources. If cross joins are combined with inner and outer joins, the result can depend on the order of evaluation or the parentheses. Ill @Abap(atalog. sql ViewNlame: 'S4D430_JOINNEST' Join in parentheses is evaluated first define view S4d430_Join_Nested as select from scarr as a left outer join ( sairport asp left outer join scounter as c on p.id on a.carrid a. carrid = c.airport c.carrid as carrier_id, p.id as airport_id, c.countnum as counter_number } Figure 93: Example: Nested Join Expression This example reads information about ticket counters (table scounter). This information is joined with details about the airport where the ticket counter is located (table sairport) and the carrier which runs the counter (table scarr). The example uses outer joins because the result set should also include airports, where there are no ticket counters, and carriers, that do not run any ticket counters at all. The parentheses are not required. But they are used to increase the readability of the expression. 132 © Copyright. All rights reserved. Lesson: Using Additional Join Types and UNION (ALL) I @Abap(atalog. sqlViewNlame; 'S4D430_JOINIMPL' define view S4d430_Join_Nested_Implicite as select from scarr as a left outer join sairport asp left outer join scounter as c: on p.id = c.airport on a.carrid = c.carrid a. carrid No parantheses: Sequence of ON-conditions rules as carrier_id, p.id as airport_id, c:.countnum as counter_number } l Figure 94: Example: Same Join with Implicite Ordering The figure above shows the same nested join expression, but this time without parentheses. This has no influence on the result. The two joins are evaluated in exactly the same order. But even for experienced developers, the evaluation order will not be obvious at first glance. Note: When defining views with nested joins, always add the parentheses to improve readability. Prerequisites and Result Set of UNION SELECT A, Bj C, D FROM ... WHIERE u, • B c o 2 2 3 4 3 4 2 3 4 2 3 4 A A B c D 1 1 2 2 3 1 2 1 2 3 4 2 UNION 3 SELECT A, B., x as FROM ... WHERE ... A 2 3 4 B 2 3 4 x 2 3 4 y .2 Duplicates are removed from the result set 3 4 Figure 95: UNION If you place keyword UNION ALL between two select statements, you create the union of rows in the two results sets. Completely identical entries are removed from the result set. A union results set can itself be the left side of a further union. © Copyright. All rights reserved. 133 Unit 3: More SQL Features in CDS Views Prerequisites Compatible Structure of Result. Sets - Same number of eleDlents - Elements in same position have coml)atlble data type - Elements in same position have identical name/alias Properties of Result SET • Element Names - Are (identical) in both original resu It sets and are taken from there Key Definition - taken from first SELECT statement Element Type - ABAP Dictionary ty-pe with sufficient value range I Figure 96: UNION: Prerequisites and Result Set A prerequisite for UNION (ALL) is that the structures of the results sets are compatible. This means that the results sets must have the same number of elements and that the pairs of elements in each position have a compatible data type. The element names of the result sets must match. The properties of the union results set are defined as follows: ● ● ● The element names are taken either from an explicitly specified name list or, if no list is specified, the matching names from the SELECT lists of all SELECT statements are used. The definition of the key elements is taken from the SELECT list of the first SELECT statement. The data type of each element is a data type from ABAP Dictionary whose value range covers the data types of the associated columns of all results sets involved. @Abap(atalog .. s ql ViewNlame: 'S4D430_ UNIIO' define view S4d430_Union as select from scustom { Ikey id, Ikey 'Customer' as type) name, city, country Key defin1itiion in second select is ignored r } union select from stravelag { �ey agencynum 'Agency name, city, country as id, as type, Alias id is needed to have identical element names l Additional blanks needed to have compatible types Figure 97: Example: UNION 134 © Copyright. All rights reserved. Lesson: Using Additional Join Types and UNION (ALL) The CDS view in this example reads flight customers from table SCUSTOM and travel agencies from table STRAVELAG. The two result sets are merged into one by using key word UNION. A field with name TYPE is filled with literal 'Customer' or 'Agency ' to make the rows in the result set distinguishable. This field is a key field of the resulting view because it is labelled with "key" in the first select. Note: The two literals have to be of identical length to fulfill the requirement, that corresponding elements need compatible types! Difference between UNION and UNION ALL Iii SELECT A, B,. C,. D FROM ... WHERE ... A B c D 2 3 4 2 3 4 2 3 4 2 3 4 UNION ALL SELECT A, B, X as C, Y as ID FROM .... WH'ERE .... A 2 3 4 B 2 3 4 x y 2 3 2 3 4 4 c D 1 4 1 2 3 4 2 3 4 2 3 4 3 B 1 2 3 I 3 4 4 I 2 3 4 3 4 A 1 .2 2 2 I I Figure 98: UNION ALL If the addition ALL is not specified, all duplicate entries are removed from the results set. They are not removed if ALL is specified. © Copyright. All rights reserved. 135 Unit 3: More SQL Features in CDS Views @Aba peat a log. sql ViewName: • 54D430_UNIOAL Ll" define view S4d4l3,0_Urnion_All_l as select from scustom { key id } where city� 'Walldorf' u-n�i no -a·�1""';1 ..j ,. j select from sbook { key c:ustomid as id } wlh,ere agencynum = '00000100' L f;ba peat a log. sql ViewName: '54!D430_UNIOAL L2" define view S4dU0_Ut11ioJl_Al1_2 as select from scustom { key i.d } where city = 'Walldorf' jun1on I select L I from sbook { key customid as id} where aeencynum = ·00000100' • l• Same definition without ALL L id .... 00000001 !ooooooo1 00000002 00000003 ooooooos OOOCil0006 R�w� --; id 00000001 00000002 00000003 00000005 00000006 Figure 99: Example: UNION vs UNION ALL The CDS views in this example read customer ids from table SCUSTOM (Customers with address in 'Walldorf') and from table SBOOK (customers that booked with travel agency '00000100'). In the first data definition key word UNION ALL is used. The second CDS view reads exactly the same data but uses UNION without addition ALL. Customer '00000001' has an address in Walldorf and made one booking with travel agency '00000100'. Consequently, the result set of the first CDS View contains customer ID '00000001' twice. With keyword 'UNION' instead of 'UNION ALL' the second entry is removed from the result set. Advantages of UNION (ALL) 136 © Copyright. All rights reserved. Unit 3 Exercise 10 Define a CDS View with a UNION statement Business Example Template: Solution: S4D430_PARTNER_WITH_REVENUE (DDL Source) Create a New DDL Source 1. In your own Package, create a new DDL Source (suggested name: Z##_PARTNER_WITH_REVENUE, where ## stands for your group number) based on template defineView. 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##PARTREV). Select Customers with Revenues Implement a first SELECT statement to read customers with revenue 1. In the new DDL Source, edit the FROM clause. Implement a select from your CDS View Z##_Customer_With_Revenue. If you did not complete the previous exercise, you can read from CDS View S4D430_Customer_With_Revenue, instead. 2. Edit the field list. Add field id as key field. 3. Add all other fields from the basis view, i.e. name and address data, total amount with currency and field DAYS_AHEAD. Implement a UNION statement Add a SELECT statement to read travel agencies with revenue. 1. After the first SELECT statement, at the very end of your DDL Source, type another SELECT statement to read from CDS View S4D430_Agency_With_Revenue. 2. Select the same fields (in the same order!) as in the first SELECT. 3. Link the two SELECT statements with keyword UNION to have the two result sets combined on the database level. Add a Field for the Partner Type Add a field that helps to distinguish flight customers from travel agencies. 1. Edit the field list of the first SELECT statement. Add a literal ‘C’ (for Customer) between fields ID and NAME. 2. Provide an alias for the literal (suggested alias: type). © Copyright. All rights reserved. 137 Unit 3: More SQL Features in CDS Views 3. Edit the field list of the second SELECT statement. This time, add literal ‘A’ (for Agency). Note: Make sure that in both SELECT statements the literal has the same position in the field list and alias name. Activate and Test 1. Activate the new DDL Source. 2. Open the Data Preview for the CDS View and ensure that the displayed data are correct. 138 © Copyright. All rights reserved. Unit 3 Solution 10 Define a CDS View with a UNION statement Business Example Template: Solution: S4D430_PARTNER_WITH_REVENUE (DDL Source) Create a New DDL Source 1. In your own Package, create a new DDL Source (suggested name: Z##_PARTNER_WITH_REVENUE, where ## stands for your group number) based on template defineView. a) See the corresponding step in the previous exercise. 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##PARTREV). a) See source code extract from the model solution. Select Customers with Revenues Implement a first SELECT statement to read customers with revenue 1. In the new DDL Source, edit the FROM clause. Implement a select from your CDS View Z##_Customer_With_Revenue. If you did not complete the previous exercise, you can read from CDS View S4D430_Customer_With_Revenue, instead. a) See source code extract from the model solution. 2. Edit the field list. Add field id as key field. a) See source code extract from the model solution. 3. Add all other fields from the basis view, i.e. name and address data, total amount with currency and field DAYS_AHEAD. a) See source code extract from the model solution. Implement a UNION statement Add a SELECT statement to read travel agencies with revenue. 1. After the first SELECT statement, at the very end of your DDL Source, type another SELECT statement to read from CDS View S4D430_Agency_With_Revenue. a) See source code extract from the model solution. 2. Select the same fields (in the same order!) as in the first SELECT. a) See source code extract from the model solution. © Copyright. All rights reserved. 139 Unit 3: More SQL Features in CDS Views 3. Link the two SELECT statements with keyword UNION to have the two result sets combined on the database level. a) See source code extract from the model solution. Add a Field for the Partner Type Add a field that helps to distinguish flight customers from travel agencies. 1. Edit the field list of the first SELECT statement. Add a literal ‘C’ (for Customer) between fields ID and NAME. a) See source code extract from the model solution. 2. Provide an alias for the literal (suggested alias: type). a) See source code extract from the model solution. 3. Edit the field list of the second SELECT statement. This time, add literal ‘A’ (for Agency). Note: Make sure that in both SELECT statements the literal has the same position in the field list and alias name. a) See source code extract from the model solution. Activate and Test 1. Activate the new DDL Source. a) See the corresponding step in the previous exercise. 2. Open the Data Preview for the CDS View and ensure that the displayed data are correct. a) See the corresponding step in the previous exercise. DDL Source S4D430_PARTNER_WITH_REVENUE @AbapCatalog.sqlViewName: 'S4D430PARTREV' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'Solution: Union of Customers & Agencies' define view S4D430_Partner_With_Revenue as select from S4d430_Customer_With_Revenue { key id, 'C' as type, name, street, city, country, amount, currency, days_ahead } union select from S4d430_Agency_With_Revenue { key id, 140 © Copyright. All rights reserved. Lesson: Using Additional Join Types and UNION (ALL) 'A' as type, name, street, city, country, amount, currency, days_ahead } © Copyright. All rights reserved. 141 Unit 3: More SQL Features in CDS Views LESSON SUMMARY You should now be able to: 142 ● Understand Additional Join Types ● Understand UNION and UNION ALL © Copyright. All rights reserved. UNIT 4 Advanced Concepts Lesson 1 Defining CDS Views with Input Parameters Exercise 11: Define and Use a CDS View with Input Parameter 145 153 Lesson 2 Building CDS Views with Associations Exercise 12: Define a CDS View with Associations Exercise 13: Use a CDS View with Associations 161 169 181 Lesson 3 Enhancing a CDS View Exercise 14: Enhance a CDS View 188 197 Lesson 4 Linking a CDS View with Authorization Rules Exercise 15: Create and Use a DCL Source 203 213 UNIT OBJECTIVES ● Define CDS Views with Input Parameters ● Provide Values for Input Parameters of a CDS View ● Specify a Default Value for an Input Parameter ● Define Views with Associations ● Expose Associations ● Use Exposed Associations in Path Expressions ● Understand Filtered Associations ● Understand the Concept of CDS View Enhancements ● Enhance a CDS View ● Understand the Concept of CDS DCL © Copyright. All rights reserved. 143 Unit 4: Advanced Concepts ● 144 Create a DCL Source © Copyright. All rights reserved. Unit 4 Lesson 1 Defining CDS Views with Input Parameters LESSON OBJECTIVES After completing this lesson, you will be able to: ● Define CDS Views with Input Parameters ● Provide Values for Input Parameters of a CDS View ● Specify a Default Value for an Input Parameter Input Parameter Declaration In the previous unit we learned how powerful CDS Views are when it comes to making calculations and pre-processing of the raw data found in database tables. Examples for·the Need of Input Parameters • Input for SQL expressions and functions, e.g. - a discount factor when ca.lculaling a price - the separation character when concatenating text - the target currency for a currency conversion Selection o·f Data. to Enter an Aggregation, e.g. - date up to which revenue shall enter a summation Madatory Selection Criteria, e.g. - language key - user name I Figure 100: Input Parameters in CDS Views The new possibilities immediately rise the question in how far the consumer of the CDS View (ABAP program, other CDS View) can influence the way the calculations are done. Of course the consumer can provide a WHERE clause to make a selection of the results. But how does that help when you want to specify the target currency for a currency conversion? CDS Views that contain an aggregation expression are another important example for the need of input parameters. If, for example, a CDS View calculates the sum of revenues, the view itself can restrict the revenues that enter the equation. But fields like the booking date will not be part of the views element list and the consumer of the view will have no chance to refer to it in his WHERE clause. Finally, SQL does not know such things as mandatory selection criteria. A consumer may provide a WHERE clause or might not. With a mandatory input parameter the view can force the consumer to provide a necessary selection criterion like e.g. a language key or a user name. © Copyright. All rights reserved. 145 Unit 4: Advanced Concepts I @Abapcatalog. sqlViewName: Addition "S4D430_PARAM' WITH PARAMETERS define view S4d430_Parameter with parameters parameteirl: abap. char-(16)., 1 Predefined Dictionaiy parameter2: s_carr_ id., type or data element l l @EndUserlext. label: 'Disc,ou11t' @EndUserlext. quick Info: 'Discount Fa,ct,or for Price ' factor: o·bap.dec(3., 2), EndUserT ext-Annotations separator: abap.char(l) before the parameter .. @< EndUserText. label: 'Separation Character' as select from sflight L: ... or after the parameter Figure 101: Example: View Definition with Input Parameters You define input parameters by placing addition WITH PARAMETERS after the CDS View name. The parameters are then defined in a comma-separated list. Each input parameter must be typed with an elementary data type. This can be a predefined ABAP Dictionary type (in the form abap.<type>(<len>) ), or a data element. Structure types, table types or reference types are not allowed. You can use annotations to provide additional information for parameters. Annotations Like annotations in the element list, annotations in the parameter list can be specified before the parameter or after the parameter. Template defineViewWithParameters x 0 NcwO�tD Ddinitio,i Templa.te·s I Select eae C>f the avait�ble temp1�t.e:.. 0, U,e Un� •elected lempl•le @lDelim.e�ew @1De me1/i....,wlthJl>i:ri Dtlii\e__�ewwith A��o<iati,on__ D.tin .. • vlowwith • .ingl• input psremeter, The input pam11ete1 ca" be u� .u �n e!9'1"19't in �l"le st!fct lirt •Ot u � n optrancl in tonclilic.nal er� rill1milic 1 e:xpressr:Dns. Caned Figure 102: Template "defineViewWithParameter" 146 © Copyright. All rights reserved. Lesson: Defining CDS Views with Input Parameters There is a dedicated template for creating a view definition with input parameter. Access to Input Parameters @Abapcatalog.sqlViewName: 'S4D430_PARAM' define view S4d430_Parameter with parameters para1meter1: abap. char(10), para1meter2: s_carr_ id Prefix.ed with ,.$parameters.'' (recommended} as select from sflight $pa1rameters. parameterl as par-am1, : parameter.2 as param2; } Prefixed with ,.:" (not recommended) Figure 103: Example: How to Access Input Parameters There are two ways to address input parameters: The long version is with prefix "$parameters.", the short version is a simple colon(":") before the parameter name. It is recommended to use the long version. Only the long version is supported by source code completion. • In the Element List - as standalone element • In Expressions - as operand in an expression as input for a predefined SQL function dir-ectly after case in a case distinction • In the WHERE clause or HAVING clause - Right side of a condition • In the ON ,condition of a Join - Righi side of a condition Figure 104: Where to Access Input Parameters You can use an input parameter in the following positions: ● Element in the SELECT list. ● Operand of an arithmetic expression. ● Operand directly after case in a case distinction. ● Right side of a condition in a WHERE clause or HAVING clause. © Copyright. All rights reserved. 147 Unit 4: Advanced Concepts ● Right side of a condition in an ON condition in a join. Input Parameters in Data Preview Ill Cl Optn widi Dat� Pre.itw x IEnter Parome1er Values Q) Type:cha!(10) I ! PAIIAMETER1:" Anythin� PARAMHER:2: FACTOR:' SE!PARATOR.:" l�L=H====================================================�I l::0=90==========================�1 . l._x __,1 OK J �, Figure 105: Input Parameters in Data Preview If you open Data Preview for a CDS View with input parameter(s), you are prompted to enter actual values for all input parameters. I» Note: It is currently not possible to define optional input parameters for CDS views. Only such entries are accepted that are compatible with the parameter type. But the tool does not perform any further checks. If, for example, the parameter is typed with a data element that is based on a domain, the entry is not checked against the allowed fixed values in this domain. Hint: When the focus is on an input field, the screen displays the expected type above the input mask. 148 © Copyright. All rights reserved. Lesson: Defining CDS Views with Input Parameters Input Parameters in CDS DDL @AbapCatalog. sql ViewNarne; 'S4D430_US EP.ARAM' CDS View with Parameters as data source define view S4d430_Use_Parameters with parameters factor : obap .. dee( 3,. 2 ) Parameter passing 1 in parantheses ,,()'' as selec:t from S4d430_Parameter( parameter!.: 'Any Text', parameter2: 'LH', factor: $parameters.factor, separator: 'X' This parameter is { ,,forwarded" } Figure 106: Example: Use Input Parameters in CDS DDL When a CDS View reads from another CDS view that has input parameters, all these input parameters have to be supplied with actual values. This is done within parantheses immediately after the the name of the source view in the FROM clause (see the example above). No blank is allowed before the opening parenthesis. Note: All parameters have to be supplied and they have to be in the same order as in the definition of the view. [o Hint: If you use the auto-completion capabilities of the editor, you don't have to look up the names and sequence of the parameters. You can use the following as actual value for an input parameter: ● Literal (text or number) ● An input parameter of your own CDS View ("forwarding" of a parameter) ● A session variable © Copyright. All rights reserved. 149 Unit 4: Advanced Concepts Input Parameters in Open SQL Assignment with .. =" instead of .:" SELECT FROM s4d430_param.eter( parameterl = @( 'Carrier' && pa_car ), '0.93', factor parameter2 @pa_car, separator = ·x· > FIELDS* WHERE carrid = @pa_car INTO TABLE @gt_data. Sequence of parameters not fixed Literals, host variables or host expressions Figure 107: Example: CDS View With Parameters in Open SQL In Open SQL, actual parameters for the input parameters of a CDS view are specified in a parenthesized comma-separated list. The syntax is very similar to that used in CDS DDL. There are two important differences: ● ● Open SQL uses assignment operator "=". CDS DDL uses character ":", instead. The sequence of the parameters does not have to match the sequence in the view definition. The following can be used as actual parameters: 150 ● Literals ● Host variables (of elementary type) ● Host expressions (with elementary result type) © Copyright. All rights reserved. Lesson: Defining CDS Views with Input Parameters Before Release 7.50: Input parameters. only supported on SAP HANA database • Check of system capability needed: DATA gt_fea.ture_set TYPE cl_abap:.._dbfeatures=>features sett. I:NSF.RT cl_abap_dbfeatures=>views_with_parameters INTO TABLE gt_feature_set. IF cl_abap_dbfeatures=>use_features( gt_fea.ture_set = abap_false. END[F. As of elease 7 so· Input parameters supported on all DB platforms • Syntax above obsolete (warning from syntax check) l Figure 108: Restricted support in Release 7.40 Before Release 7.50, CDS views with input parameters were only supported on SAP HANA database. Reading from them when the system was connected to another database will result in runtime errors. To avoid these runtime errors, it is necessary to query property VIEWS_WITH_PARAMETERS using method USE_FEATURES of class CL_ABAP_DBFEATURES (See sample code above). With Release 7.50 and higher, the input parameters of CDS views are supported by all database platforms and can be used in Open SQL. The check mentioned above is no longer required. Querying this property results in a warning check from the syntax check. Default Value for Parameters in Open SQL No actual parameters in Open SQL SELECT Internal session System Fields ABAP Program DATUM SELECT' FROM My_Cds_View FIELDS * .... CDS View {witlh annotated Parameters) Input Parameters are supplied from related system fields p_langu ,______� define view My_Cds_View with parameters p_date syst_datum @<l:nvironment. systemFieLd: #SYSTEM_DA Tl:J p_langu : syst_Langu @<Environment.systemFieLd; #SYSTEM_LANGUA6E as select Figure 109: Optional Parameters for CDS Views © Copyright. All rights reserved. 151 Unit 4: Advanced Concepts You learned already that optional parameters are currently not supported in CDS views. In other words: When you access a CDS View with parameters, you have to provide actual values for all parameters. There is one exception from this rule: You can use annotation Environment.systemField to link an input parameter to a system field of the ABAP runtime environment. Examples of such system fields are sy-datum for system date or sy-langu for the logon language. When a CDS View is used as data source in an Open SQL SELECT statement, any parameter annotated with Environment.systemField is considered optional. If no actual value is supplied, like in the example above, the system automatically supplies the parameter with the content of the related system field. • 5 diffe,rent values system rield #CLIENT sy-mandt #SYSTEM_DATA sy-datum #SYSTEM_ TIME sy-vzeit #SYSTEM_LANGUAGE sy-langu #USER sy-uname • Strictly o:nce per parameter • Has an ·e·ff,ect only in Open SQL (when using the view iin another CDS view, the annetanon Is ig1nol'edl) • Special rulle for #CI..IENT: Explicit Actual value not allowed Figure 110: Rules for Annotation Environment.systemField The list above shows the supported values for annotation Environment.systemField and the system fields they are related to. You can use annotation Environment.systemField strictly once per parameter. It is not supported (and wouldn't make any sense) to link the same parameter to more than one system field. Note: Annotation Environment.systemField only has an effect in Open SQL. When you use the CDS View in another CDS View, the annotation will be ignored and the parameter remains mandatory. If a parameter is annotated with Environment.systemField, you can either make use of the default value from the system field or "override" that value with an explicit actual parameter. There is only one exception: For parameters annotated with Environment.systemField: #CLIENT, it is forbidden to specify an actual parameter explicitly. This rule has been introduced to avoid conflicts with Open SQL addition USE CLIENT. 152 © Copyright. All rights reserved. Unit 4 Exercise 11 Define and Use a CDS View with Input Parameter Business Example Template: S4D430_CUSTOMER_WITH_REVENUE (DDL Source) S4D430_INTRO_S2 (Executable Program) Solution: S4D430_CUSTOMER_WITH_PARAMETER (DDL Source) S4D430_PARAM_S1 (Executable Program) Define a CDS View with Input Parameter Create a copy of your CDS View for Customers with Revenue and extend it with an input parameter that allows the user to specify a date up to which the bookings enter the calculation. 1. In your own Package, create a new DDL Source (suggested name: Z##_CUSTOMER_WITH_PARAMETER, where ## stands for your group number) based on template defineViewWithInputParameters. 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##CUSTREV2). 3. Provide a meaningful name for the generated input parameter (suggested name: P_) and type it with the appropriate abap data type for date fields. Hint: When in doubt, type abap. and hit Ctrl + Space. Search the offered data types for one with description Date in Format YYYYMMDD. 4. Open your DDL Source Z##_CUSTOMER_WITH_REVENUE and copy the FROM clause and the field list to the new DDL Source. If you did not complete the respective exercise, you can copy from DDL Source S4D430_CUSTOMER_WITH_REVENUE. 5. Edit the new DDL Source (i.e,. the one with the input parameter). Add a WHERE clause to the SELECT statement and use the input parameter to restrict the selection to flights that took place before the given date. 6. Activate your new DDL Source and open the data preview for the new CDS View. Use Input Parameters in Open SQL Use your CDS View with input parameter in Open SQL and provide a value for the parameter. © Copyright. All rights reserved. 153 Unit 4: Advanced Concepts 1. Create a copy of your executable program Z##R_OPEN_SQL (suggested name: Z##R_OPEN_SQL_PARAM, where ## is your group number). If you did not complete the respective exercise, you can copy executable program S4D430_INTRO_S2, instead. 2. Change the definition of local data type ty_t_customers. Replace line type S4d430_Customer_With_Revenue with your new CDS View Z##_Customer_With_Parameter. 3. Change the SELECT statement. In the FROM clause, replace CDS View S4d430_Customer_With_Revenue with your new CDS View Z##_Customer_With_Parameter. Supply the CDS View’s input parameter with system field sy-datum. 4. Activate and test your program. System Field as Default Value for Input Parameter Use an annotation to link your input parameter with system field sy-datum. 1. Edit your DDL Source Z##_CUSTOMER_WITH_PARAMETER. Use annotation @Environment.systemField for the input parameter to use the system date as default value. 2. Activate the DDL Source and open the data preview for the new CDS View. Why are you still prompted to enter a value for the input parameter? And why is there no default value for the parameter? 3. Return to your executable program Z##_PARAM_S1 and perform a syntax check. Why do you suddenly get a syntax error that requires that you move the INTO clause to the very end of the SELECT statement? 4. Adjust the SELECT statement according to the new syntax rules of release 7.50: Move the INTO clause to the very end of the statement. 5. Edit your program Z##_PARAM_S1. Copy the entire SELECT statement. In the copied SELECT statement, remove the parameter passing (brackets after the name of the CDS View). 6. Perform a syntax check to verify, that now a parameter passing is not needed anymore. 154 © Copyright. All rights reserved. Unit 4 Solution 11 Define and Use a CDS View with Input Parameter Business Example Template: S4D430_CUSTOMER_WITH_REVENUE (DDL Source) S4D430_INTRO_S2 (Executable Program) Solution: S4D430_CUSTOMER_WITH_PARAMETER (DDL Source) S4D430_PARAM_S1 (Executable Program) Define a CDS View with Input Parameter Create a copy of your CDS View for Customers with Revenue and extend it with an input parameter that allows the user to specify a date up to which the bookings enter the calculation. 1. In your own Package, create a new DDL Source (suggested name: Z##_CUSTOMER_WITH_PARAMETER, where ## stands for your group number) based on template defineViewWithInputParameters. a) See the corresponding step in the previous exercise. 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##CUSTREV2). a) See source code extract from the model solution. 3. Provide a meaningful name for the generated input parameter (suggested name: P_) and type it with the appropriate abap data type for date fields. Hint: When in doubt, type abap. and hit Ctrl + Space. Search the offered data types for one with description Date in Format YYYYMMDD. a) See source code extract from the model solution. 4. Open your DDL Source Z##_CUSTOMER_WITH_REVENUE and copy the FROM clause and the field list to the new DDL Source. If you did not complete the respective exercise, you can copy from DDL Source S4D430_CUSTOMER_WITH_REVENUE. a) See the corresponding step in the previous exercise. © Copyright. All rights reserved. 155 Unit 4: Advanced Concepts 5. Edit the new DDL Source (i.e,. the one with the input parameter). Add a WHERE clause to the SELECT statement and use the input parameter to restrict the selection to flights that took place before the given date. a) WHERE fldate < $Parameters.P_FlightsBefore or WHERE fldate < :P_FlightsBefore b) See source code extract from the model solution. 6. Activate your new DDL Source and open the data preview for the new CDS View. a) See the corresponding step in the previous exercise. b) When prompted to enter values for parameters, enter a valid date, e.g. today, in “technical” format YYYYMMDD. DDL Source S4D430_CUSTOMER_WITH_PARAMETER @AbapCatalog.sqlViewName: 'S4D430CUSTREV2' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'Solution: Input Parameter' define view S4d430_Customer_With_Parameter with parameters @EndUserText.label: 'Consider flights up to this date' P_FlightsBefore : abap.dats as select from S4d430_Booking_And_Customer as c { key c.customid as id, c.name, c.street, c.postcode, c.city, c.country, sum(c.amount) as amount @<Semantics.amount.currencyCode: 'currency', c.currency, //<@Semantics.currencyCode: true, avg(c.days_ahead) as days_ahead } where fldate < $parameters.P_FlightsBefore group by c.customid, c.name, c.postcode, c.street, c.city, c.country, c.currency Use Input Parameters in Open SQL Use your CDS View with input parameter in Open SQL and provide a value for the parameter. 1. Create a copy of your executable program Z##R_OPEN_SQL (suggested name: Z##R_OPEN_SQL_PARAM, where ## is your group number). If you did not complete the respective exercise, you can copy executable program S4D430_INTRO_S2, instead. a) See the corresponding step in the previous exercise. 2. Change the definition of local data type ty_t_customers. Replace line type S4d430_Customer_With_Revenue with your new CDS View Z##_Customer_With_Parameter. a) See source code extract from the model solution. 156 © Copyright. All rights reserved. Lesson: Defining CDS Views with Input Parameters 3. Change the SELECT statement. In the FROM clause, replace CDS View S4d430_Customer_With_Revenue with your new CDS View Z##_Customer_With_Parameter. Supply the CDS View’s input parameter with system field sy-datum. a) See source code extract from the model solution. 4. Activate and test your program. a) Perform this step as you did in the previous exercise. Executable Program S4D430_PARAM_S1 REPORT s4d430_param_s1. TYPES ty_t_customers TYPE STANDARD TABLE OF s4d430_customer_with_parameter WITH NON-UNIQUE KEY id. DATA gt_customers TYPE ty_t_customers. * ALV Processing DATA go_salv TYPE REF TO cl_salv_table. DATA gx_excp TYPE REF TO cx_salv_error. * Selection Screen PARAMETERS pa_city TYPE s_city DEFAULT 'New York' LOWER CASE. START-OF-SELECTION. * Data Retrieval ************************************************************* SELECT * FROM s4d430_customer_with_parameter( p_flightsbefore = @sy-datum ) WHERE city = @pa_city ORDER BY city, name INTO TABLE @gt_customers. * output ************************************************************* TRY. cl_salv_table=>factory( IMPORTING r_salv_table = go_salv CHANGING t_table = gt_customers ). * Display *-------------------------* go_salv->display( ). CATCH cx_salv_error INTO gx_excp. " MESSAGE gx_excp TYPE 'I'. ENDTRY. System Field as Default Value for Input Parameter Use an annotation to link your input parameter with system field sy-datum. © Copyright. All rights reserved. 157 Unit 4: Advanced Concepts 1. Edit your DDL Source Z##_CUSTOMER_WITH_PARAMETER. Use annotation @Environment.systemField for the input parameter to use the system date as default value. a) See source code extract from the model solution. 2. Activate the DDL Source and open the data preview for the new CDS View. Why are you still prompted to enter a value for the input parameter? And why is there no default value for the parameter? Annotation @Environment.systemField is only evaluated when the view is accessed from L. a) See the corresponding step in the previous exercise. 3. Return to your executable program Z##_PARAM_S1 and perform a syntax check. a) Choose Sxntax Check from the toolbar. Why do you suddenly get a syntax error that requires that you move the INTO clause to the very end of the SELECT statement? Annotation @Environment.systemField is a feature available as off release 7.50. As soon as you use a 7.50 feature. your Open SQL statement has to fulfill the stricter syntax rules introduced with this release. 4. Adjust the SELECT statement according to the new syntax rules of release 7.50: Move the INTO clause to the very end of the statement. a) See source code extract from the model solution. 5. Edit your program Z##_PARAM_S1. Copy the entire SELECT statement. In the copied SELECT statement, remove the parameter passing (brackets after the name of the CDS View). a) See source code extract from the model solution. 6. Perform a syntax check to verify, that now a parameter passing is not needed anymore. a) Choose Sxntax Check from the toolbar. DDL Source S4D430_CUSTOMER_WITH_PARAMETER ... define view S4d430_Customer_With_PARAMETER with parameters @EndUserText.label: 'Consider flights up to this date' @Environment.systemField: #SYSTEM_DATE P_FlightsBefore : abap.dats as select from S4d430_Booking_And_Customer as c ... Executable Program S4D430_PARAM_S1 * Option 2: Do not provide a value * (possible if parameter is linked to a system field) ************************************************************ 158 © Copyright. All rights reserved. Lesson: Defining CDS Views with Input Parameters * * * * SELECT * FROM s4d430_customer_with_PARAMETER WHERE city = @pa_city ORDER BY city, name INTO TABLE @gt_customers. © Copyright. All rights reserved. 159 Unit 4: Advanced Concepts LESSON SUMMARY You should now be able to: 160 ● Define CDS Views with Input Parameters ● Provide Values for Input Parameters of a CDS View ● Specify a Default Value for an Input Parameter © Copyright. All rights reserved. Unit 4 Lesson 2 Building CDS Views with Associations LESSON OBJECTIVES After completing this lesson, you will be able to: ● Define Views with Associations ● Expose Associations ● Use Exposed Associations in Path Expressions ● Understand Filtered Associations Syntax of Associations CDS provides extended support for treating relationships between entities. Such relationships are often reflected as foreign key relationships in the database, but in SQL the relations are often concealed behind non-trivial join conditions. This is cumbersome and error-prone for application developers, and requires considerable effort when joins are to be reused. • The syntax of associations keeps the relations between data model entities visible. Path expressions and filtered associations make it easier to read the CDS View definitions, as well as the SELECT statements accessing the views. • A High-value Wrapping of the Syntax for Joins - Associations define relationships (they not just join data sources) - Associations are translated into joins on database level • Easier t.o Read Associations may contain additional semantic information (e.g. cardinality) Path expressions reveal the underlying data model and origin of data - Filter conditions are easier to read than WHERE conditions or CASE-expressions • Improved Performance - Ej{posed associations are only evaluated when needed J r JOIN on Demand") Figure 111: What Are Associations? Although associations and joins look different, there is no difference on database level. Eventually, any association is translated into an ordinary join. But in the case of so-called exposed associations, it depends on the way a view is consume. The join is only executed if the consumer requests data from the associated data source. This can have a positive effect on the performance and sometimes is referred to as “JOIN on Demand”. © Copyright. All rights reserved. 161 Unit 4: Advanced Concepts View Definition with Association I @Abap(atalog. s ql ViewName: 'S4D430_ASS01' define view S4d430_Association_l as select from spfli assoctataon to scer-r on .spfli. carr-Id .. scarr. car-r-Id { key carrid, key connid, sea rr. carrname ---=-==------- L } L Association target 1 Name of data source mandatory for all fields from association target ---------------------� View Definition with Join @AbapCatalog.sqlViewName: '54D430_JOININN' define view S4dl430_JOIN_ININER as select from spfLi inner join scar-r on L spfli.carrid Name of data source only mandatory for non-unique field names = scarr.carrid { key spfli.carrid, key conrrid, carrname } Figure 112: Example: Association Instead of Join At first glance, associations are just another syntax for defining joins. In the example above, the two FROM clauses only differ in the use of keywords "association to" or "inner join". The ON condition remains exactly the same (though, strictly speaking, we must not refer to it as “Join condition” any more). There is also a small difference in the element list: In the element list of a join, specifying the data source for a field is only mandatory for non-unique field names (like field name CARRID in the example). In the field list of an view with association, all fields without an explicit source are taken from the primary data source (table SPFLI in the example). For all fields from the associated table, it is mandatory to specify the data source (field SCARR.CARRNAME in the example). View Definition with Associiation @Abap(atalog.,:;qlViewName: 'S4D430_ASS01' define view S4dl430_A.ssociation_l as select from spfli association to scar-r on spfli. carr-Ld = scarr. carr-Id { key carrid, key connid, scarr.carrname } Gorrespondiing SQl Create Statement CREATE VIEW "54 .43 _ASSOl" .AS SELECT "SPFL-". �MANDT" AS "!WJDT" I "SPFI.-". '�CARRIO" I "SJ:1-L.". CONNID", "S?F:t·","C.TYFRO ", "S?FLI n. -crrzto- I "•A" ON ( Figure 113: Technical Realization of Associations 162 © Copyright. All rights reserved. The SQL Create Statement of a CDS view definition visualizes its technical realization. The SQL Create Statement for view definition above reveals, that on database level, it is nothing more than a join definition. Cardinality ( exactly one carrier @AbapCatalog. sqlViewName; 'S40430_ASS02 • define view S4d430_Association_2 as select related to a oonnection) from spf li as c assocfatfonj t.. .1] to scar+ as _carrier on c.carrid = _carrier.carrid Name of the association { key c.carrid, Ikey c.connid) c.dtyfrom, c .ct tyto, Replaced with Alias in SOL Create Statement _carrier.carrname } Extract Fmm the SQL Create Statement H=A ". Hl:A!, KNA.,Y�H FR H j"SPF1 " "C ... '"HtiNDI" c I. "'CARRI Ltf'T O TER O N rsdi.RR" "C"L = =:AO". "MMfDTH AND H - .. ....A "iO� -A '",, "CARR: .. Figure 114: Example: Additional Semantics When you define an association, you can use addition AS to specify an alias. This syntax looks very similar to the definition of aliases in the join syntax. But strictly speaking, it is not an alias for the data source but a name for the association. The difference becomes clear when we look at the SQL Create Statement again: In the SQL Create statement, the association name is replaced by a more generic alias ("A0" in the example). This means that the association name is only a semantic information. Hint: It is recommended, but not a fixed rule, that names for associations begin with character "_". A meaningful name for the association further improves the readability of the view definition. ERROR: undefined OFFENDING COMMAND: ‘~ STACK: Unit 4: Advanced Concepts Associations and Cardinality Cardinality is optlonal - Default cardinality is (0 .. 1) Minimum value is opttcnal - Defau It Value for mimimum is O [11 means [0 .. 11 [41 means (0 .. 41 [") means (0 .. "] • Forbidden Values - Minimum can not be ' - Maximum can not be O Syntax Check for Maximum> 1 - Association cannot be used in a WHERE condition (syntax error) - Association should not be used outside aggregate expressions (syntax warning) J Figure 115: Some Rules Regarding Cardinality The list above shows some rules regarding cardinalities in associations. There are a few short forms and defaults. And there are some forbidden values. Specifying a cardinality with maximum larger than 1 can lead to the following syntax errors and warnings: ● ● 164 Syntax error “Value-set associations are not allowed here” is issued of the association is used in a WHERE condition. Syntax warning “Association <…> can influence the cardinality of the resulting set” is issued if the association is used in the element list. © Copyright. All rights reserved. Lesson: Building CDS Views with Associations @AbapCatalog.sqlViewName: 'S4D430_ASSOWARN' define view S4d430_Association_WARNING as select from spfli as c association[*] to sf light as _flights on c.carrid and c. conn id I I short for [ 0 .. "l = _flights.carrid = _fl i.ght s , conn id { Access to association with cardina1llity [*] increases result set key carrid, key conmd, _flights. fldate } Result without field fldate .... and with field fldat.e t:'l RewO.t� --------, amid AA AA AA AA AA 0017 AA AA ronnid 0017 0017 0017 0017 0017 0017 fl'dat• 2015-11·18 2.015-12·16 2.0lfi.-01-B :?016-02-10 2l)1t;.03.(J!I 2.0lf>.OMJ6 Figure 116: Example: Syntax Warning for Cardinality [*] Syntax of Exposed Associations In the previous examples, the views directly accessed fields of the associated data source. This kind of associations is called ad-hoc association. • The benefit of associations becomes clearer when looking at exposed associations. @AbapCatalog.sqlViewName; 'S4D430_ASSOEXP' define view S4d430_Assoc:iation_Exposed as select from spfli as c association[l] to scarr as _carrier on c.carrid = _carrier.carrid association[*] to sflight as _fli!ihts on c.carrid _flights.carrid and c , conndd = _flights. conn id Prerequisite: all fields used in the ON condition also in element llist key c .. carrid, key c. ccnndd , c.cityfrom, c.cityto, _carrier, _flights Association target visible to consumer of this CDS View l } Figure 117: Example: Exposed Association Instead of accessing individual fields of the associated data source, a CDS view can place the association name itself in its element list. The association is then exposed to the consumer of the CDS view, which is either another CDS View or an ABAP Open SQL statement. The consumer of the view gets full access to all components of the associated data source. © Copyright. All rights reserved. 165 Unit 4: Advanced Concepts There is a prerequisite for exposing an association: All fields used in the ON condition of the association have to be part of the element list. In the example above, field c.carrid is required for exposing association _carrier. Fields c.carrid and c.connid are required for exposing association _flights. @AbapCatalog.sqlViewName; 'S4D430_ASSOEXP' define view S4d430...;Association_Exposed as select from spfli as c association[l] to on association[*] to on and scarr as _carrier c.carrid = _carrier.carrid sflight as _flights c.carrid _flights.carrid c.connid"' _flights.connid Exposed Associations are not (yet) joined on database level1 { key c.carrid, key c.connid, c.cityfrom, c .. dtyto, _carrier, _flights } CREATE VIEW' "S 43 ASSOEXP" AS SELECT "C". "MANDT" nS .. �DT .. , .. c". "CARRI .. , "C". "CONN!-", No warning if association with cardinality [1 is . . c·•. "C.i.IYFRO •• ", '"C". "C- tY!O" ::-RO·I "SPF'LI" "'C" exposed Figure 118: Difference Between Exposed and Ad-hoc Associations First of all, by exposing an association, you do not preselect the fields of the data source which you think might be of interest. You delegate this task to the consumer of the view. But there is an important technical difference that becomes relevant if the consumer chooses not to select any fields from the association. The example above shows the SQL Create Statement for a CDS View with exposed association. You can see that in the case of an exposed association the SQL View does not immediately join the associated data source. The actual join of the data source is not done, until the consumer actually accesses individual fields of the associated data source. You can put it that way: By exposing an association, the actual join of the data sources is postponed until it is clear that the consumer actually wants to see data from the associated data source. As a consequence, you can add any number of exposed associations to your view without having to fear that you might create a SQL View with a monster join expression. Note: Because the join is not done yet, there is no syntax warning if an association with a cardinality with maximum greater 1 is exposed. 166 © Copyright. All rights reserved. Lesson: Building CDS Views with Associations Template defineViewWithAssociation x CJ Templetes I S<IKI "'"" o! lh� av•ilabl• �om;plot ... rJh@.us.o<:illlicn can be w�d in lh! selKII litt M Yl'll!!!I M by ether ,.._ whict. ijle th,i .iew ,� , cltt� iou,ce. finish Figure 119: Template "defineViewWithAssociation" There is a dedicated template for creating a view definition that contains an association to a second data source. Exposed Associations in Data Preview � ll!i S4DA30_ASSOCIATIOt,t�POSED � Gt � 26 rows rel!rieved - 0 ms connid earrld I cityfrom 2407 2402 BERillN 0400 FRANKFURT FRANKFURT Q Q\Jicl<: 111er on IFRANKFURTI EID Distinct v�lues fo,r I cityf,oml Follow Association Coi:iyrow 0783 lW <;AN FRANCJ<;. •• 1699 om 0790 , _,.rriOI-<CIHI0 •. 11 +-i _flig;trt, - >light I O •. " l \!YORK I FAAfll ... t} NEWYORiK NEW YORK NEWYORiK NEWYORIK ROME ROME ROME 0401 5S16 0017 dtyto NEW YORK NEWY,QRK FRANKFURT 04oz lis1of """'"1atlom f. FRANKFURT BERLIN NKFURT FRANKFURT FftANKFllRT SANFll,AN ... SAN,FP.AN ... FRANKFURT OSAKA TOKYO FIRANKFIIRT Figure 120: Exposed Associations in Data Preview If a CDS View definition contains exposed associations, you can evaluate these associations in Data Preview as follows: © Copyright. All rights reserved. 167 Unit 4: Advanced Concepts 1. Open the CDS View in Data Preview. 2. Choose one of the displayed rows, then click on the arrow next to the view name in the header toolbar (see figure above). 10 Hint: Alternatively, you can right-click the entry and choose Follow Association. 3. Choose an association from the list of available associations. 168 © Copyright. All rights reserved. Unit 4 Exercise 12 Define a CDS View with Associations Business Example Template: S4D430_BOOKING_AND_CUSTOMER (DDL Source) Solution: S4D430_ASSOCIATION (DDL Source) Define a CDS View With An Association Create a copy of your CDS View that joins booking data and customer data. Replace the join with an (ad-hoc) association. 1. In your own Package, create a new DDL Source (suggested name: Z##_Association, where ## stands for your group number). 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##ASSO). 3. Open your DDL Source Z##_BOOKING_AND_CUSTOMER and copy the FROM clause and the field list to the new DDL Source. If you did not complete the respective exercise, you can copy from DDL Source S4D430_BOOKING_AND_CUSTOMER. 4. Edit the new DDL Source. In the FROM clause, replace the inner join with an association to the CDS View with customer data. Based on the data model, which would be the most appropriate cardinality for the relation from a flight booking to the flight customer? 5. Add the cardinality information to the association statement. 6. Perform a syntax check and activate your new DDL Source. Expose the Association In the element list of your CDS view, comment out all elements that come from the associated view with customer data. Expose the complete association, instead. 1. In the element list of your CDS view, place characters “//” in front of all fields starting with “C.”. © Copyright. All rights reserved. 169 Unit 4: Advanced Concepts Hint: You can comment out several lines by marking them and hitting keys Strg + <. 2. At the end of the element list, add the name of the association. 3. Apply the recommended naming rule for associations. Note: The rule recommends meaningful aliases for associations, starting with an underscore (“_”). 4. Activate your new DDL Source. Use an Exposed Association in Data Preview Open the data preview for your new CDS View and follow the association to the flight customer. 1. Open data preview for your new CDS View. 2. Choose a flight booking and display details of the flight customer associated to this booking. 170 © Copyright. All rights reserved. Unit 4 Solution 12 Define a CDS View with Associations Business Example Template: S4D430_BOOKING_AND_CUSTOMER (DDL Source) Solution: S4D430_ASSOCIATION (DDL Source) Define a CDS View With An Association Create a copy of your CDS View that joins booking data and customer data. Replace the join with an (ad-hoc) association. 1. In your own Package, create a new DDL Source (suggested name: Z##_Association, where ## stands for your group number). a) See the corresponding step in the previous exercise. 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##ASSO). a) See source code extract from the model solution. 3. Open your DDL Source Z##_BOOKING_AND_CUSTOMER and copy the FROM clause and the field list to the new DDL Source. If you did not complete the respective exercise, you can copy from DDL Source S4D430_BOOKING_AND_CUSTOMER. a) See the corresponding step in the previous exercise. 4. Edit the new DDL Source. In the FROM clause, replace the inner join with an association to the CDS View with customer data. a) Instead of inner join <...> as C write association to <...> as C. b) See source code extract from the model solution. Based on the data model, which would be the most appropriate cardinality for the relation from a flight booking to the flight customer? As exactly one flight customer is assigned to every single flight booking. the most appropriate cardinality is 1..1. 5. Add the cardinality information to the association statement. a) Add [1..1] immediately after key word ASSOCIATION. b) See source code extract from the model solution. 6. Perform a syntax check and activate your new DDL Source. © Copyright. All rights reserved. 171 Unit 4: Advanced Concepts a) See the corresponding step in the previous exercise. Expose the Association In the element list of your CDS view, comment out all elements that come from the associated view with customer data. Expose the complete association, instead. 1. In the element list of your CDS view, place characters “//” in front of all fields starting with “C.”. Hint: You can comment out several lines by marking them and hitting keys Strg + <. a) See source code extract from the model solution. 2. At the end of the element list, add the name of the association. a) See source code extract from the model solution. 3. Apply the recommended naming rule for associations. Note: The rule recommends meaningful aliases for associations, starting with an underscore (“_”). a) Replace as C with as _Customer. b) Adjust all references to the alias. c) See source code extract from the model solution. 4. Activate your new DDL Source. a) See the corresponding step in the previous exercise. Use an Exposed Association in Data Preview Open the data preview for your new CDS View and follow the association to the flight customer. 1. Open data preview for your new CDS View. a) See the corresponding step in the previous exercise. 2. Choose a flight booking and display details of the flight customer associated to this booking. a) In the result list, right-click the booking for which you want to see customer details. b) Choose Follow Association. c) From the list of available associations, choose the one that leads to flight customer data. DDL Source S4D430_ASSOCIATION @AbapCatalog.sqlViewName: 'S4D430ASSO' @AbapCatalog.compiler.compareFilter: true @AbapCatalog.preserveKey: true 172 © Copyright. All rights reserved. Lesson: Building CDS Views with Associations @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'Solution: Exposed Association' define view S4d430_Association as select from S4D430_Booking as b association [1..1] to s4d430_Customer as _Customer on b.customid = _Customer.id { key b.carrid, key b.connid, key b.fldate, key b.bookid, b.customid, b.agencynum, b.amount, b.currency, b.days_ahead, _Customer // Make association public // c.name, // c.street, // c.postcode, // c.city, // c.country } © Copyright. All rights reserved. 173 Unit 4: Advanced Concepts Path Expressions in CDS DDL i @AbapCatalog.sqlViewName: 'S4D430_PATHEXPR1' Read from CDS View that exposes Associations defin1e view S4d430,_Path_Expressions_1 as select from S4d430_Associa,tion_Exposed as c { key carr-Id, key connidJ Read field carrname from target of c .. _carrier. carrnaae as carrier_name; association _carrier _flights Propagate association _Jlights (Do not use it directly) CR!ATt VIEW nS4 430 PA l'!EXPR " as S!tLE.C'.t "C".n!-oomf" JI.S "MAJf[)f•, "C"". "CAAAID", ·c··. "CONNID", "-AO". �CA.�lUIA.l.!EH AS "CAREUER NllME" FROM "SIID,30 ASSOEX?'' "C" LEn-Ov""I'ER JOIN "SCA..i:l..�" "-AO" 0. I '"C ... "HDDT':" • "'11,J;.Q N. "Mi!ND!" AND '"C". "C.MUl " " ·�AO"."' MA " Join of SCARR, but no join of SFLIGHT Figure 121: Example: Use Exposed Associations in a View Definition The CDS View in the example above reads data from a CDS View that contains exposed associations. The element list contains a path expression to read field carrname from the association target of association _carrier. Association _flights is not used directly. Instead, it is propagated, which means it is exposed again under the same name. In the SQL Create Statement for this view, we find a join of the SQL view created for CDS View S4d430_Association_Exposed with database table SCARR. This is because SCARR is the target of association _carrier. Table SFLIGHT, the target of association _flights, is not joined here. This is because the association is not used but only exposed. Note: To define this view, it is not necessary to know that SCARR is the target of association _carrier. Nor is it necessary to know the details of the relation between connections and carriers, i.e., the join condition. 174 © Copyright. All rights reserved. Lesson: Building CDS Views with Associations I @Aba pCatalog. sql ViewName: "S4D430_PATHEXPR2, define view S4d430_Pa.th_Expressions_2 as select from S4d430_Path_Expressions_1 as c key carr-Ld , Read field seatsocc from target of association _flights key connid, ca,rrier_name, sum(c._flights.seatso,cc) as occupied_total group by carrid, ccnrud, L carrier_name CREA-:: V!Eti "S4 43 ·c·. "MANDT" AS ·c· - "CAAAl!l", PAT!!�.i!'R.2" AS SELE.CT AMiNDr·. ·c·. "C<JN!i!il", Now also talble SFUGHT is joined "C" • "CARR! !:R.Jil1M1:", Sir.,![ "•AO" , • S�TSOCC" I AS "SE'.ATS_TC>TAL" !'!\<*! ·s�D�JO l'J\:T!!E:XPRl. ·c· L:E,T our� JOU. "Sfl.IG!!T" "-.AD" OH ( "C" • "CMtltlii" • "II.AO",. "CllR&ID" .WU ·c· . "CO!ffi!O" • -. ", "Co+mID" ·c· . -�or • ··AO·. "IWl'DT • WO Figure 122: Example: Propagation of Associations The CDS View in this example reads from the CDS View of the previous example. The element list contains a path expression to read field seatsocc from the association target of association _flights. In the SQL Create Statement for this view, we find a join of the SQL View created for CDS view S4d430_Path_Expressions_1 with table SFLIGHT, the target of association _flights. • Path Expressions in Open SQL SELECT FROM s4d430_association_exposed AS c FIELDS carrid, connid, Prefix ,.\" for all association names Component selector j-" (in CDS DDL it is ,,. ") \_carrler-carrnane, Optional:: With Alias .c" for the data source c-\_carrier-currcode Pa�h expressions WHERE c-\_carrier-currcode INTO TABLE @gt_data. 'USO' supported in all clauses l Figure 123: Example: Use Exposed Associations in Open SQL As of Release 7.50, path expressions also exist in Open SQL. They are supported in all clauses, e.g. the field list, the WHERE clause, the GROUP BY clause, the HAVING clause. Compared to path expressions in CDS DDL, the following important differences exist regarding the syntax: © Copyright. All rights reserved. 175 Unit 4: Advanced Concepts ● Prefix "\" is needed for association names ● Component selector is "-" (in CDS DDL it is ".") Syntax of Filtered Associations DDL Source from tl association t.o t2 as _asso onl<on-condition> { I _as so Qdil ter-condi hon >U . field_, } SQL View Definition FROM Tl LEFT OUTER JOIN T2 ON <on-condition> AND <filter-condition> Figure 124: Filtered Associations – The Principle Path expressions in CDS DDL can be extended using a filter condition. The filter condition becomes part of the ON - condition, when the system translates the path expression into a join on database level. I» Note: Filter conditions are currently not supported in Open SQL path expressions. @Abap(ata og.sq1v·ewName: ,S4D430_ASSOFILT' define view S4d430--'Association_FILTERED with parameters language : syst_ l angu @<Environment. systemFie ta: #SYSTEM_ LANGUAGE as select from scarr as a association to tcurt as ....:currency on a .cur re ode = _currency. waers and _currency.spras II = Do not restrict to one language in the ON condition $parameters.language j { carr-Ld, car rname, curr-code, $parameters.language as lang, But use a filter condition in the Path Expression _currency[spras = $parameters.language] .ktext as currency_name } Figure 125: Example: Filter Condition in Path Expression 176 © Copyright. All rights reserved. Lesson: Building CDS Views with Associations In this example, table tcurt is associated to table scarr (master data for airlines). Table tcurt is a so-called text table. It contains names and descriptions for currencies in many different languages. The ON condition of the association defines the basic foreign key relation between the two tables, i.e., the currency code in table scarr (field currcode) is linked to the key field waers in table tcurt. This association links one carrier with all descriptions of its local currency, independent of the language. Instead of restricting the selection to one language in the ON condition of the association, the example uses a filter condition in the path expression. Technically, that is on the database, the result is the same. But with the filter condition in the path expression, it becomes clearer which conditions are part of the foreign key relation, and which conditions reflect an additional selection. • Allowed Operators • Left-hand Side - Must be a field of association target • Right·hand Side - field of association target - literal - parameter - session variable I Figure 126: Rules for Filter Conditions When implementing a filter condition, the following rules apply: ● ● ● All relational operators are allowed ( =, <, >, <=, >=, <> ). The left-hand side of the condition expects a field of the association target (a field of _currency in our example). The right-hand side can be another field of that target data source, a literal, a parameter, or a session variable. © Copyright. All rights reserved. 177 Unit 4: Advanced Concepts Cardinality in Filtered Associations @Abapcatalog. sql ViewName: 'S4D430_FI L TCARD' @EndUserText. label: "Demo: Cardinality in Filtered Asso." define view S4D430_Asso_Filter_Cardinali'ty with parameters language : syst_Langu @<Environment. systemFieLd.: #5YSTEM_LANGUAGE as select .Foreign key relation has from scarr as a cardinalirty 0 .. * ·• association[*] to tcurt as _currency on a.cur-r-code = _currency.waers { car rid, car-rname, cur re ode, $parameters.language as lang, .But flllter condition reduces this to 0 .. 1 • _currency[l: spr-as .. $parameters. language]. ktext as currency_name } ] Figure 127: Example: Cardinality in Filtered Associations The example above contains an association of table TCURT to table SCARR. The correct cardinality for this association is 0..*: The local currency code of one carrier can have an arbitrary number of texts in table tcurt — one for each language that is maintained. We already learned that, normally, cardinality * leads to syntax warnings and even errors once the association is used in path expressions. In our example, the filter condition reduces the cardinality of the association to "0..1": For a given language, TCURT contains a maximum of one entry per currency code. To document this – and to make the syntax warnings and errors go away – you can specify cardinality "1" in the filter condition of a path expression. Note: It is not allowed to specify a cardinality in a path expression without a filter condition. 178 © Copyright. All rights reserved. Lesson: Building CDS Views with Associations Annotation compareFilter from ti association to t2 as _asso on <on-condition> With Value False L { ... _asso><-------,c .fieldl., _asso < ].field2, ... } _J With Value True FROM Tl LEFT OUTER JOIN T2 AS AO ON <on-condition> AND <filter-condition> FROM Tl LEFT OUTER JOIN T2 ON <on-condition> AND <filter-condition> LEFT OUTER JOIN T2 AS Al ON <on-condition> AND <filter-condition> Figure 128: Annotation AbapCatalog.compiler.compareFilter By default, every new path expression with a filter condition, will lead to a separate join in the generated SQL View. This happens even if the filter conditions are identical (see our example above and the SQL CREATE statement on the left). ABAP annotation AbapCatalog.compiler.compareFilter can be used to specify whether the filter conditions are compared for the path expressions of a view. If the filter condition matches, the associated join expression is created only once, which generally improves performance. I» Note: The results sets of both configurations can differ. © Copyright. All rights reserved. 179 Unit 4: Advanced Concepts -i @AbapCatalog.sqlViewName: 'SD430_FILTCOMP' oompareFilter is switched off @Abapcatalog. compiler. c,ompareF 1l ter: false define view s404;0_Asso_Filt:er_Compare with parameters language : syst_ Langu @<Environment. systemField: #SYSTEM_ LANGUAGE as select from scarr as a association to tcurt as _currency on a .. currcode - _currency. waers { car rid, Two separate joins for the identical paths carr-name, cur re ode, $parameters.language as lang, _currency[spras _:currency[spras .$parameters .. language] . kt ext as currency_name., $parameters. language] .1 text as curr desceaptdon } ___- _ _J Figure 129: Example with compareFilter: False In the example above, the filter conditions in the two path expressions are identical. Annotation ABAPCatalog.compiler.compareFilter is listed with value false. This makes the system generate two separate joins of scarr and tcurt to retrieve fields ktext and ltext. With value true, the system would compare the filters, realize that they are identical, and use just one join to retrieve the two fields. Note: All data definition templates contain annotation ABAPCatalog.compiler.compareFilter with value true. 180 © Copyright. All rights reserved. Unit 4 Exercise 13 Use a CDS View with Associations Business Example Template: S4D430_CUSTOMER_WITH_PARAMETER (DDL Source) S4D430_PATH_T1 (Executable Program) Solution: S4D430_CUSTOMER_WITH_PATH (DDL Source) S4D430_PATH_S1 (Executable Program) Use an Exposed Association in Another CDS View Create a copy of your CDS View that aggregates booking data per customer. Instead of reading from a CDS View with a join, read from the CDS view with an association. 1. In your own Package, create a new DDL Source (suggested name: Z##_Customer_With_Path, where ## stands for your group number). 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##CUSTASSO). 3. Open your DDL Source Z##_CUSTOMER_WITH_PARAMETER and copy the FROM clause and the field list to the new DDL Source. If you did not complete the respective exercise, you can copy from DDL Source S4D430_CUSTOMER_WITH_PARAMETER. 4. Edit the new DDL Source. Replace the CDS View in the FROM clause with your CDS View Z##_Association, which contains an exposed association. If you did not complete the respective exercise, you can read from CDS View S4d430_Association, instead. 5. Perform a syntax check. Why do you get syntax errors? How can you read the customer-related information? 6. Use path expressions to read the flight customer data from the associated data source. 7. Perform a syntax check and activate your new DDL Source. © Copyright. All rights reserved. 181 Unit 4: Advanced Concepts Use an Exposed Association in Open SQL Access your CDS View with exposed association in Open SQL. Use path expressions to follow the association. 1. Create a copy of executable program S4D430_PATH_T1 (suggested name: Z##R_PATH, where ## is your group number). 2. Change the SELECT statement. Replace the CDS View in the FROM clause with your CDS View Z##_Association. If you did not complete the respective exercise, you can use CDS View S4d430_Association, instead. I» Note: Do not adjust the definition of local data type ty_s_customer! 3. Perform a syntax check for your executable error. Why do you get syntax errors? How can you access the customer-related information, now? 4. In your SELECT statement, use a path expression for all flight customer-related fields. Do not forget fields in the WHERE clause and ORDER BY clause. Hint: Path expressions in Open SQL require a backslash (character “\”) in front of each association name and dash (character "-") is used as component selector. 5. Activate and test your program. 182 © Copyright. All rights reserved. Unit 4 Solution 13 Use a CDS View with Associations Business Example Template: S4D430_CUSTOMER_WITH_PARAMETER (DDL Source) S4D430_PATH_T1 (Executable Program) Solution: S4D430_CUSTOMER_WITH_PATH (DDL Source) S4D430_PATH_S1 (Executable Program) Use an Exposed Association in Another CDS View Create a copy of your CDS View that aggregates booking data per customer. Instead of reading from a CDS View with a join, read from the CDS view with an association. 1. In your own Package, create a new DDL Source (suggested name: Z##_Customer_With_Path, where ## stands for your group number). a) See the corresponding step in the previous exercise. 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##CUSTASSO). a) See source code extract from the model solution. 3. Open your DDL Source Z##_CUSTOMER_WITH_PARAMETER and copy the FROM clause and the field list to the new DDL Source. If you did not complete the respective exercise, you can copy from DDL Source S4D430_CUSTOMER_WITH_PARAMETER. a) See source code extract from the model solution. 4. Edit the new DDL Source. Replace the CDS View in the FROM clause with your CDS View Z##_Association, which contains an exposed association. If you did not complete the respective exercise, you can read from CDS View S4d430_Association, instead. a) See source code extract from the model solution. 5. Perform a syntax check. a) See the corresponding step in the previous exercise. Why do you get syntax errors? The customer- related fields (NAME. STREET. POSTCODE. CITY. COUNTRY) are not contained in the new data source. © Copyright. All rights reserved. 183 Unit 4: Advanced Concepts How can you read the customer-related information? Use the association in path expressions. 6. Use path expressions to read the flight customer data from the associated data source. a) Use path expressions like c._Customer.name. b) See source code extract from the model solution. 7. Perform a syntax check and activate your new DDL Source. a) See the corresponding step in the previous exercise. DDL Source S4D430_CUSTOMER_WITH_PATH @AbapCatalog.sqlViewName: 'S4D430_CUSTPATH' @AbapCatalog.compiler.compareFilter: true @AccessControl.authorizationCheck: #CHECK @EndUserText.label: 'Solution: Path Expressions in CDS DDL' define view S4d430_Customer_With_Path with parameters @EndUserText.label: 'Consider flights up to this date' @Environment.systemField: #SYSTEM_DATE P_FlightsBefore : abap.dats as select from S4d430_Association as c { key c.customid as id, c._Customer.name, c._Customer.street, c._Customer.postcode, c._Customer.city, c._Customer.country, sum(c.amount) as amount @<Semantics.amount.currencyCode: 'currency', c.currency, avg(c.days_ahead) as days_ahead } where c.fldate < $parameters.P_FlightsBefore group by c.customid, c._Customer.name, c._Customer.street, c._Customer.postcode, c._Customer.city, c._Customer.country, c.currency Use an Exposed Association in Open SQL Access your CDS View with exposed association in Open SQL. Use path expressions to follow the association. 1. Create a copy of executable program S4D430_PATH_T1 (suggested name: Z##R_PATH, where ## is your group number). a) See the corresponding step in the previous exercise. 2. Change the SELECT statement. Replace the CDS View in the FROM clause with your CDS View Z##_Association. If you did not complete the respective exercise, you can use CDS View S4d430_Association, instead. 184 © Copyright. All rights reserved. Lesson: Building CDS Views with Associations I» Note: Do not adjust the definition of local data type ty_s_customer! a) See source code extract from the model solution. 3. Perform a syntax check for your executable error. a) See the corresponding step in the previous exercise. Why do you get syntax errors? The customer- related fields (NAME. STREET. POSTCODE. CITY. COUNTRY) are not contained in the new CDS View. directly. How can you access the customer-related information, now? Use the association in path expressions. 4. In your SELECT statement, use a path expression for all flight customer-related fields. Do not forget fields in the WHERE clause and ORDER BY clause. Hint: Path expressions in Open SQL require a backslash (character “\”) in front of each association name and dash (character "-") is used as component selector. a) Your path expressions should look like \_Customer-name, \_Customer-street, etc. b) See source code extract from the model solution. 5. Activate and test your program. a) Perform this step as you did in the previous exercise. Executable Program S4D430_PATH_S1 REPORT s4d430_path_s1. TYPES: BEGIN OF ty_s_customer, id TYPE s4d430_customer_with_parameter-id, name TYPE s4d430_customer_with_parameter-name, street TYPE s4d430_customer_with_parameter-street, postcode TYPE s4d430_customer_with_parameter-postcode, city TYPE s4d430_customer_with_parameter-city, country TYPE s4d430_customer_with_parameter-country, amount TYPE s4d430_customer_with_parameter-amount, currency TYPE s4d430_customer_with_parameter-currency, days_ahead TYPE s4d430_customer_with_parameter-days_ahead, END OF ty_s_customer. TYPES ty_t_customers TYPE STANDARD TABLE OF ty_s_customer © Copyright. All rights reserved. 185 Unit 4: Advanced Concepts WITH NON-UNIQUE KEY id. DATA gt_customers TYPE ty_t_customers. * ALV Processing DATA go_salv TYPE REF TO cl_salv_table. DATA gx_excp TYPE REF TO cx_salv_error. * Selection Screen PARAMETERS pa_city TYPE s_city DEFAULT 'New York' LOWER CASE. START-OF-SELECTION. * Data Retrieval ************************************************************* SELECT FROM s4d430_association FIELDS customid as id, \_customer-name, \_customer-street, \_customer-postcode, \_customer-city, \_customer-country, sum( amount ) as amount, currency, avg( days_ahead ) as days_ahead WHERE \_customer-city = @pa_city and fldate < @sy-datum group by customid, \_customer-name, \_customer-street, \_customer-postcode, \_customer-city, \_customer-country, currency ORDER BY \_customer-city, \_customer-name INTO TABLE @gt_customers. * output ************************************************************* TRY. cl_salv_table=>factory( IMPORTING r_salv_table = go_salv CHANGING t_table = gt_customers ). * Display *-------------------------* go_salv->display( ). CATCH cx_salv_error INTO gx_excp. " MESSAGE gx_excp TYPE 'I'. ENDTRY. 186 © Copyright. All rights reserved. Lesson: Building CDS Views with Associations LESSON SUMMARY You should now be able to: ● Define Views with Associations ● Expose Associations ● Use Exposed Associations in Path Expressions ● Understand Filtered Associations © Copyright. All rights reserved. 187 Unit 4 Lesson 3 Enhancing a CDS View LESSON OBJECTIVES After completing this lesson, you will be able to: ● Understand the Concept of CDS View Enhancements ● Enhance a CDS View Reminder - Append View Software Provider (e.91. SAP) Customer ABAP Repository (Dictionary) Database Object (= Database View) I I I I I I Database I Figure 130: Reminder: Append Views for Classical Database Views Database views delivered by SAP can be enhanced by partners and customers using views known as append views, without making any modifications. Further fields from basis tables in the database view can be added to append views as view fields. Append views cannot be used to add further basis tables to the view or to modify the join conditions or selection conditions of a database view. An append view is assigned to exactly one database view. More than one append view can be created for a database view. 188 © Copyright. All rights reserved. Lesson: Enhancing a CDS View """w � [ ljot� ) @" O r-"" ufli! Ul'itiei Bl!Pend E"i"l'.H'U-l\T ��n'I ll!P View LOB H,n111e Sttuc:tur,: ... Dicliolt8,Y. ¢, 6t TtcJ,nal settrios fQrelf,jn i(11n Q.bfea Cl•e"Ol'I En f'I UMUm!!nmtiOn (:mlUO_APPUID Append View :[Qn�oon Vt Short Desailtb11 I New(Revlsed) I Demo: .,';.!)pend View foi Catalme \flew S4D43!1.J',PPeHDEI: Attrtu-t-�-,,_Vie_ - w_Field_s......,. Aptlic:ltiolll-l�p §.ad Il � Fi@id � t'�lrr Table$ Vjl)loll fiiei:IS (ID b�le Sl!!'l! � ml:! llill � � S�FLI £.!:!!!!! SCAlll! � � .......-1 'l/lewfleld r!!All:Dl = Cllll,RID CONJHll T;ible Name Fil!ldNamP gfg !WlD'I Sl'fl.l CARRI II � £2!!!!!!? m:ll � Clt'lf(l Sl'E'l-I CITYIO C1l1U'IIUIY.E SCi'<PJl CJ!RIW'A.'£ .llPP!:HD Z4tl430 .APPEND c n:Ell0)4 l.!R?= IIHO � aw. I(� � :Y.m2 Figure 131: Example: Creating a Classical Append View In the example, database view S4D430_APPENDED has six fields in its field list. Append View Z4D430_APPEND adds fields AIRPFROM and AIRPTO. CDS View Extensions Software Provider ( e.g. SAP} Customer CDS View Definition CDS Extend View Definiitiori Define View •.. AS ••• Extend View ••• WITH ••• SQL View ASAP Repository (Dictionary) (generated) Database Obj,ect {= SQL View) I I I I Database I Figure 132: CDS View Extensions CDS View Extensions are defined in dedicated DDL Sources via DDL statement EXTEND VIEW. Every DDL Source with a CDS view extension defines two objects: The actual CDS view extension and an Append View. This corresponds to the two objects defined by a standard DDL: The CDS View and the SQL View. © Copyright. All rights reserved. 189 Unit 4: Advanced Concepts DDL Source With View Extension (Created by Custom,er) @AbapCatalog. sql ViewAppendName: 'Z4D430 EX TENDA' extend view S4d430 Externd Tar .et A with Z4d430 Extend View A { c .atr-pfr-om, Points at an existing CDS View c.airpto } DDL Source· With View .DefiniUo·n (Created by Softwar·e· Provider) @Abapcatalog. sqlViewName: 'S4D430_E:XTTARGA' define view!S4d!430 Externd Target Aias select from spfli as c inner join scarr as a on c.carrid { key c.carrid, = a.carrid key c.connid, c.dtyfrom, c.dtyto, a.c:arrname } Figure 133: Example: CDS View and CDS View Extension In this example, CDS View S4d430_Extend_Target _A contains six elements in the element list. CDS View extension Z4d430_Extend_View_A adds fields airpfrom and airpto to this list. The link between the two DDL Sources is established through the CDS view name after key word EXTEND VIEW. I» 190 Note: The name of the SQL view cannot be specified here. © Copyright. All rights reserved. Lesson: Enhancing a CDS View Element List • literals, fields, expressions, functions • Input parameters • Path expreeeions • Aggregates (as of 7. 51 , only if target already contains aggregates) • Associations • View Extension can add asseclatlons • G,ROUP BY Clause fas of release7.51) • Only if target view contains a GROUP BY clause • Ma.ndatory for new elements that are not aggregates UNION(ALL) Statements (as of release 7.51) • Mandatory if target view contains UNION (ALL) statements •Same number of UNION(ALL) Statements required Figure 134: Syntax of View Extensions Like classical Append Views, CDS View Extends can add elements to the SELECT list. New is the fact that an extend view can also define additional associations. This can be used, for example, to define an association to a customer-specific database table or CDS View. I» Note: A CDS View Extend may contain associations but no direct joins. As of release 7.51, it is also possible to extend views that contain aggregations and/or UNIONs. But to do so, the target view has to actively allow this via annotation AbapCatalog.viewEnhancementCategory. © Copyright. All rights reserved. 191 Unit 4: Advanced Concepts DDL Source With View Extension @AbapCatalog. sql ViewAppendName: 'Z4D430_EXTENDB' extend view S4d430_Extend_Target_B with Z4d430 Extend View B association to sairport as _from ,on c .airpfrom = _from .. id association to sairport as _to on c.airpto = _to.id { c .airpfrom, ! _from. name as airpfrom_name Add assoclatons to target view I Use elements of the :1 c . count ryf r, c Lajrpto to.name as airpto name1 associated data sources c . count ryto } Figure 135: Example: CDS View Extension with Association In this example, CDS View S4d430_Extend_Target _B CDS View is extended with CDS View Extension Z4d430_Extend_View_B. This view extension not only extends the field list. It also adds two associations to table sairport. Note: Instead of using fields of the associated data sources directly, the view extensions could also have exposed the new associations. 192 © Copyright. All rights reserved. Lesson: Enhancing a CDS View DDL Source With Vi,ew Extension (Created by Custom,er) end Name; I• S4Q430 EXTENDC'i extend view S4D430 Extend Tar etc with S4D430 EXTEND VIEW C @AbapCatalo . s l ViewAi { Addition al aggregations in element list city, countryJ miax( _booking. fldate ) as la,st_booking } group by city1 Extension of the GROUP BY clause country union { city, country, max ( _booking. fl date ) as l.ast_booldng l l Key word UNION, followed by extension for the other SELECT } gr-oup by crty, country Figure 136: CDS View Extension with GROUP BY and UNION In this example, CDS View S4d430_Extend_Target_C contains two SELECT statements linked with a UNION statement. Each SELECT statement has an aggregation expression in the element list and a corresponding GROUP BY clause. CDS View extension Z4d430_Extend_View_C reflects this structure: It contains the extensions for both SELECT statements, linked with key word UNION. In both SELECT statements, the extension adds fields city and country to the element list and expands the GROUP BY clause accordingly. Note: Extensions with GROUP BY and UNION are only possible if explicitly allowed by the extended view via annotation @AbapCatalog.viewEnhancementCategory. © Copyright. All rights reserved. 193 Unit 4: Advanced Concepts Template extendView x Cl I f2I Us�lh• �•dod l•mpl•I• (!JD6ine\liow (!JDdint \litw,,,;lh Join ID Ddin• View walh Am,�i1ticn [Extend� an e:isling ,,;...., by ad<iin9 the o;p«rued elom•ni• ["''l.htc itr«t li1t cftl:itcvii'.w u!in.g a vitw tnMM.Hl'l�n.t. Nert Figure 137: Template "ExtendView" There is a dedicated template for creating the definition of a view extension. After creating the DDL Source, you have to specify the name of the CDS View you want to extend, the name of the new CDS entity (View extend), and the name of the SQL View append. Recommendations and Restrictions for View Extensions Recommendations • Naming - (Customer) Namespace for repository objects (DDL Source and SQLAppend View) - Uncommon names for additional elements and associations (to avoid later conflicts) Identical Name for DDL Source and CDS Entity (besides upper/lower case) • CDS Views from Basis Packages Contact SAP before you extend CDS Views from Basis Packages Rest ictions • No Renaming After Transport - Name of CDS View Extend and SQLAppend View can not be changed after first transport of DDL Source • No Additional Key Fields - Prefix KEY is not allowed in CDS View Extends J Figure 138: Recommendations and Restrictions When extending CDS Views, it is advisable to carefully choose the names of repository objects and additional entities to avoid conflicts in future upgrades. 194 © Copyright. All rights reserved. Lesson: Enhancing a CDS View Placing the additional repository objects in an appropriate namespace is one of the recommendations. The other refers to the additional element list entries and associations. By using very common names, you increase the risk of conflicts with later additions in the standard. I» Note: For append fields to transparent tables, the recommended namespace is ZZ and YY. No such namespace exists for CDS View extends. Like with CDS Views in general, it is advisable but not mandatory to use the same name for the DDL Source and the CDS entity. The most important restriction also refers to naming: After a DDL Source has been transported from the development system, the names of the SQL Append View and the CDS View Extend are fixed and cannot be changed any more. Annotation viewEnhancementCategory An notation AbapCatalog. viewEnhancementCa:tegory[l - Restricts the extensibility of a CDS View - Comma-separated list of values in square brackets • Possible Values - #NONE - #PROJECTION_LIST - #GROUP BY - #UNION Allowed Combinations - #NONE cannot be combined with other values - #GROUP BY and #UNION require #PROJECTION�LIST Default Value - #PROJECTION_LIST l Figure 139: Restricting Extensibility (as of Release 7.51) As of Release 7.51, the extensibility of a CDS View may be restricted by annotation AbapCatalog.viewEnhancementCategory. The annotation may be used with a comma-separated list of values in sqare brackets. The following values exist: #NONE No extensions are allowed. This Value cannot be combined with other values. #PROJECTION_LIST Extensions of the SELECT list and additional associations are allowed; extensions of CDS views whose SELECT lists contain aggregate expressions or have a UNION clause must be permitted using further values. #GROUP BY © Copyright. All rights reserved. 195 Unit 4: Advanced Concepts Aggregated or non-aggregated elements are allowed to be added to a SELECT list with aggregated expressions and the associated extensions of the GROUP-BY clause are also permitted; caan only be specified together with #PROJECTION_LIST. #UNION Extensions of the SELECT list of a CDS view with a UNION clause are allowed; can only be specified together with #PROJECTION_LIST. If the annotation is used without square brackets or if the annotation is missing at all, the view's extensibility is as if the annotation had been specified with value #PROJECTION_LIST. Navigation from Extension Target to View Extension 1- fAbapCatalog. sqlViewllal!".e: 'S4D430_EXTTAAGET' 2 fAbapCatalog.c: piler.c pareFil er: true 3 fAc::cessControl. authori:.".ationChedc: IICHECI< @EndUser-Text . · label: 'De:IIO: Tar e:t for- S4d430_Ext:end_View' ... define view ·, · , • . : . , from �pi'H !IS c lS 8 9 - . -- - S4d430_Extend_Target Di!mo, .arge1 for S4d430_Extend.Vi= 19 11 12 13 14 15 16 > Figure 140: Extended View in DLL Source Editor You can see it directly in the DDL Source if there are any extends for this particular CDS View. If one or more CDS View Extends point to this CDS View, a spiral-shaped symbol appears on the left of the DEFINE VIEW Statement. When you place the pointer over this symbol, a dialog box opens with a list of the existing extensions. Open the definition of the CDS View Extend by clicking on its name in the list. 196 © Copyright. All rights reserved. Unit 4 Exercise 14 Enhance a CDS View Business Example Template: S4D430_ASSOCIATION (DDL Source) Solution: S4D430_EXTENDED (DDL Source) S4D430_EXTENSION (DDL Source) Create a Copy of the Template CDS View Create a copy of your CDS View that exposes an association. If you did not complete the respective exercise, you can copy from CDS View S4d430_Association. 1. In your own Package, create a new DDL Source (suggested name: Z##_Extended, where ## stands for your group number). 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##EXTENDED). 3. Open your DDL Source Z##_ASSOCIATION and copy the FROM clause and the field list to the new DDL Source. If you did not complete the respective exercise, you can copy from DDL Source S4D430_ASSOCIATION. 4. Perform a syntax check and activate your new DDL Source. Define a CDS Extend View Define a CDS Extend View for your CDS View Z##_Extended. Add the counter number and the flight class to the element list. Add an association to table SPFLI and expose it in the field list. 1. In your own Package, create a new DDL Source (suggested name: Z##_Extension, where ## stands for your group number). Choose template extendView. 2. In the new DDL Source, provide a suitable name for the SQL View Append (suggested name: Z##EXTENSION). 3. After key word EXTEND VIEW, enter the name of the CDS View you want to extend (Z##_Extended). 4. In the element list, add fields CLASS and COUNTER from the original data source. Hint: Use the source code completion capabilities of the editor to choose from the available fields. © Copyright. All rights reserved. 197 Unit 4: Advanced Concepts 5. After the name of the Extend View in the WITH addition, add an association to table SPFLI. Provide a suitable name for the association (suggested name: _connection) and specify the join condition. 6. Expose the entire new association in the element list. 7. Perform a syntax check and activate your new DDL Source. Check the View Extension Open the definition of the extended view and analyze the extension. Open the extended view in Data Preview and make sure that the additional fields and associations are displayed. 1. Open the definition of your CDS View Z##_Extended. How can you see that this view has been extended? 2. Navigate from the extended view into the definition of the CDS Extend View. 3. Return to the extended view and open it with data preview. 4. Confirm that fields CLASS and COUNTER are there and that they are filled with data. 5. Confirm that association _Connection is there and that you can follow it in data preview. 198 © Copyright. All rights reserved. Unit 4 Solution 14 Enhance a CDS View Business Example Template: S4D430_ASSOCIATION (DDL Source) Solution: S4D430_EXTENDED (DDL Source) S4D430_EXTENSION (DDL Source) Create a Copy of the Template CDS View Create a copy of your CDS View that exposes an association. If you did not complete the respective exercise, you can copy from CDS View S4d430_Association. 1. In your own Package, create a new DDL Source (suggested name: Z##_Extended, where ## stands for your group number). a) See the corresponding step in the previous exercise. 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##EXTENDED). a) See the corresponding step in the previous exercise. 3. Open your DDL Source Z##_ASSOCIATION and copy the FROM clause and the field list to the new DDL Source. If you did not complete the respective exercise, you can copy from DDL Source S4D430_ASSOCIATION. a) See the corresponding step in the previous exercise. 4. Perform a syntax check and activate your new DDL Source. a) See the corresponding step in the previous exercise. Define a CDS Extend View Define a CDS Extend View for your CDS View Z##_Extended. Add the counter number and the flight class to the element list. Add an association to table SPFLI and expose it in the field list. 1. In your own Package, create a new DDL Source (suggested name: Z##_Extension, where ## stands for your group number). Choose template extendView. a) See the corresponding steps in the previous exercise. 2. In the new DDL Source, provide a suitable name for the SQL View Append (suggested name: Z##EXTENSION). a) See source code extract from the model solution. 3. After key word EXTEND VIEW, enter the name of the CDS View you want to extend (Z##_Extended). a) See source code extract from the model solution. © Copyright. All rights reserved. 199 Unit 4: Advanced Concepts 4. In the element list, add fields CLASS and COUNTER from the original data source. Hint: Use the source code completion capabilities of the editor to choose from the available fields. a) See source code extract from the model solution. 5. After the name of the Extend View in the WITH addition, add an association to table SPFLI. Provide a suitable name for the association (suggested name: _connection) and specify the join condition. a) See source code extract from the model solution. 6. Expose the entire new association in the element list. a) See source code extract from the model solution. 7. Perform a syntax check and activate your new DDL Source. a) See the corresponding step in the previous exercise. Check the View Extension Open the definition of the extended view and analyze the extension. Open the extended view in Data Preview and make sure that the additional fields and associations are displayed. 1. Open the definition of your CDS View Z##_Extended. a) See the corresponding step in the previous exercise. How can you see that this view has been extended? There is a spiral - like (or snail - like) symbol next to the code line that contains the DEFINE VIEW statement. 2. Navigate from the extended view into the definition of the CDS Extend View. a) Click on the spiral-like (or snail-like) symbol next to the code line that contains the DEFINE VIEW statement. b) On the dialog box that appears, click on the name of the CDS Extend View. 3. Return to the extended view and open it with data preview. a) Right-click anywhere in the DDL Source and choose Open With→ Data Preview. 4. Confirm that fields CLASS and COUNTER are there and that they are filled with data. a) You should find the new fields on the far right of the data preview display. Hint: Not many bookings have a value in column COUNTER. You will need to scroll down or might even have to apply a filter to see entries with a noninitial value in this column. 5. Confirm that association _Connection is there and that you can follow it in data preview. a) Right-click on any line in the preview and choose Follow Assocation. 200 © Copyright. All rights reserved. Lesson: Enhancing a CDS View b) In the dialog window, click on associaton _Connection. DDL Source S4D430_EXTENSION @AbapCatalog.sqlViewAppendName: 'S4D430_EXTVIEW' @EndUserText.label: 'Solution: View Extension' extend view S4d430_Extended with S4D430_Extension association[1] to spfli as _connection on b.carrid = _connection.carrid and b.connid = _connection.connid { b.class, b.counter, _connection } © Copyright. All rights reserved. 201 Unit 4: Advanced Concepts LESSON SUMMARY You should now be able to: 202 ● Understand the Concept of CDS View Enhancements ● Enhance a CDS View © Copyright. All rights reserved. Unit 4 Lesson 4 Linking a CDS View with Authorization Rules LESSON OBJECTIVES After completing this lesson, you will be able to: ● Understand the Concept of CDS DCL ● Create a DCL Source Reminder - Classical Approach to Authorization Checks ,object Class ABC Object Class XVZ Authorization X_6 Authorization Profile Role User Master Record Figure 141: Reminder: Authorization Objects, Profiles, and Roles In ABAP systems, all authorizations are based on a special repository object called Authorization Object. Authorizations are defined in authorization profiles which are then assigned to users. Instead of defining and assigning authorization profiles directly, SAP recommends to define and assign user roles (transaction PFCG) with generated authorization profiles. Doing an authorization check means nothing else than looking up the user's master record to see whether a given authorization is part of at least one of the authorization profiles assigned to this user. © Copyright. All rights reserved. 203 Unit 4: Advanced Concepts Implicit Authorization Checks • Performed by the ABAP Framework - Start of a transaction - Start of a Web Dynpro application - Sia.rt of a report - Call of a.n RFC function module - Access to table content with data browser or maintenance dialogue Explicit Authorization Checks • Defined in theABAP Coding ,(AUTHORITY-CHECK stat.ement) - Access to specific functionality - Access to specific data I Figure 142: Reminder: Implicit and Explicit Authorization Checks Some authorization checks are done implicitly by the ABAP framework when the user accesses certain functionality (a transaction, an application, a report), or accesses data via generic display and maintenance tools (SE16, SM30). But most of the authorization checks are implemented in the ABAP coding, using ABAP statement AUTHORITY-CHECK. Sometimes such explicit checks protect access to specific functionality of the program (for example, switching from display to edit mode). In most cases, they are related to data access. The Need for Authorization Checks on Database Level Ill • General Problems; - No visible link between data ano authorization objects - Developer can forget (or ignore) necessary checks Users with debugging rights can bypass authorization checks • Problems related to Code-to-Data: - All authorization checks on application level - Some calculations cannot be done on the database because they require an authorization check between steps l 204 Figure 143: Known Problems of the Classical Approach © Copyright. All rights reserved. Lesson: Linking a CDS View with Authorization Rules DATA gt_connections TYJ?E TABLE OF s4d430_access_control_a. DATA gs_connection LIKE LINE OF gt_connections. PARAMETERS pa_citfr TYPE s_from_cit DEFAULT 'FRANKFURT'. SELECT FR:OM s4d430 access control a FIELDS ca:r:rid, connid, cityfrom, cityto WHERE cityfrom = @pa_citfr INTO TABLE @gt�connections. LOOP AT gt_connections INTO gs_connection. Read all connections departing from given city Check Authorization for each connection AUTHORITY-CHECK OBJECT s CARR ID ID 'CARRIO' FIELD gs_connection I ID I ACTVT IF $y-subrc <> a . r I FIELD ' 03 r • DELETE gt_connections INDEX sy-tabix. Remove connections from the result set ENDIF. ENDLOOP. I Figure 144: Example: Classical Approach to Authorization Checks The example shows a program that displays all flight connections departing from a given city. To make sure the user does only see data for which he has display authorization, the program does a loop aver the selection result set and removes the records for which the users lacks authorization. Note: Of course, a more efficient solution would have been to order the result by field carrid and to make sure that the authority check is only done once per carrier. Repository Object DCL Source DCL Source ASAP Program Define Role ... DDL Source SELECT FROM ... CDS View Figure 145: Access Control on Database – How It Works © Copyright. All rights reserved. 205 Unit 4: Advanced Concepts The figure shows the basic principle of CDS Access Control. A new repository object DCL Source (or CDS Access Control) defines a CDS Role (key word DEFINE ROLE …). It relates the CDS Role to one (or more) CDS Views (key word GRANT SELECT ON …) and defines access conditions for this CDS View (key word WHERE …). Whenever an ABAP program accesses this CDS View, the database interface will automatically filter the selection result according to the access conditions. Note: CDS Access Control only works if the program accesses the CDS View directly. Access Control is ignored if the CDS view is accessed indirectly over another CDS view. @EndUserText label: 'Demo: Authorization Check' @MappingRole: true define role S4d4�0_Role:_B { grant select s on -5--4-3-0--A-� -., -, e-_s_c_o_n_t_r_o�-B--· wher,e carrid < > •AZ'; } i;!1, �rrid AA 4! <onnid 0017 26•-•c�,e,,e,t 0·1n:11 cityhom tl!cWVO.RK fonnid <ityt<> <it,M 0017 N£Wl'0Rt: SAN !AANCISCO SAN FAAr•U:IS.... NEW\i'ORX NEWYO!'.X FRANKRlRJ SAN FRANCISCO NFWVOR AA C064 SANFAAN01S. .. l'{EwYO!tK 006,i sa sa 05>S OWJ ROM[ FRANt.FU!fi TOi:VO I\Z 07a9 TOl';VO Kl. Ol Ol 0711(1 0105 1699 ROME ROME WM 0106 1699 1W N:EWYOltK N:EWVO.RK FMNKfU� SAN FRANCIS<:O ROM[ <ityl1<1m SAN FRANCISCO NEWl'OIIX '-AN,f!AiN('J<...., flight connections with carrid 'AZ' removed from resul� set = Figure 146: Example: DLC Source The example shows the data preview for two identical CDS Views (S4d320_Acess_Cotnrol_A andS4d430_Access_Control_B). The only difference is a CDS Role related to one of them. You can see that connections that do not match the access condition carrid <> 'AZ' are suppressed from the result set of the second CDS View. 206 © Copyright. All rights reserved. Lesson: Linking a CDS View with Authorization Rules Create a New DCL Source Right-Click the Project BCAOO 8C401 > EB > Ill 00102 07SOA,';'/ DEVS41l4�0 (� l'lly x > 'I ) !fl HMOO MAMIO_COLili8_DE l'IDE7ll ) > Efl v !B WOECDS .., Ill Wl!ECDS,_OEIII Co<1:D1tJ! ) Diction:ary ) ) IS ) lliOlCOS_EXER c .. ,.0..1.s..rv Syst,mLibrory 57,JOl_mann•ll.m l>7>. 'il3JlllO_m•an<it..<n IY13, q' 0cre1e Ocletc R,m.,... from Contet Cld•Alt•Shrfl•Down , rs IP,ojca. .. 3 ABAP ftep,osilo<y l•tt--- .1 .. a,., ____ ,...,..._._,:;, F • ,F<>ldu GI ASAP Clm lmpon... l!,:porL. Rd ...... FS Clo.cPr<>j� Ci ABAP Function Groorp ABf\P F"nctiw Mv,M<l ABAP lnt...t•"' Cl ABf\Pl'ro9r•m Clo�Un..,l.alodProj..,.. Vafld•t� THm Com par• l'ol"nh fltttorcfromlr>eill l-limary... 0 SQL(on..,lo Olll!f., Cld•N Figure 147: Create New DCL Source (1) To create a new DDL Source, proceed as follows: 1. Right-click on your project in the Project Explorer. • 2. Choose New→ ABAP Repository Object …. r NtwASAPR!j>l><itoryObjoct D X AIIAP R..,pr,�itg,y 01:ije,:,I Ctc le �· ASAP �q,osiw,. Obje<l L.. ProjKI: _J ! i.QG,_el'Jo.monn•rt,.•n typ•lilt!ft..t e...;...,, ) '1b, E:n�in«rin� ) �(l•l!ili<oliOM Aoc>e!ll!II ) 1 C) C111ntrol Crul••,.A«�> Conlr<>1 ) froj«t: • �-----------------� p�yg�· Add� f I KQG_IIOO.m•nn•rt.•n l������������,J !I.OM• pock 9"' bk Origimllangu•9" ._E_ N _, • l!a•• Figure 148: Create New DCL Source (2) 3. From the list, choose Core Data Services→ Access Control. © Copyright. All rights reserved. 207 Unit 4: Advanced Concepts 1------1 0 Hint: You can use the input field below Project to type a search term, e.g., access 4. Choose Next. 5. Enter the name of an (existing) package, and a name and description for the new DCL Source. Right-Click Access Controls under package Q Add to fa,<>ril• �><f<ag:<!< Nitm�·· -----==:] Oc.(1[ptiOI\:" Origin"11An91Ja9"' �E�N�==------------ C•nc;d Figure 149: Shortcut (If Package Already Contains a DCL Source) If your package already contains a SCL Source, you can use the following shortcut: 1. In the Project Explorer, expand subnode Core Data Services of the favorite package. 2. Right-click Access Control and choose New Data Definition. 208 © Copyright. All rights reserved. Lesson: Linking a CDS View with Authorization Rules CDS DCL Syntax • Same Basiic Rules as for ABAP CDS DDL Syntax - Case of key words and names - Syntax ror I iterals, comments, statement delimiters Key word DEFINE is optional • Statement DEFINE ROLE I [DEFINE] ROLE <role_name> { GRANT SELECT ON <cds_entityh WHERE c condto [AND I OR ccondz»] [GRANT SELECT ON <cds_@ntity2> ••. ;] One or more GRANT statements between .{" and ,,}" At least one condition per GRANT statement ••• J Delimiter .:" mandatory after each GRANT statement Figure 150: ABAP CDS DCL Syntax • DCL Source name: Max. 30 Characters • Unique throughout the system (Customer namespace!) • Always Upper-Case CDS Ro11e name: • • • • J MaJ< 30 Characters Unique throughout the system (Customer namespace!) Not Oase-sensitlve Can be different from DCL Source name (not recommendsdl) Figure 151: Naming Rules and Recommendations © Copyright. All rights reserved. 209 Unit 4: Advanced Concepts Access Conditions in DCL Sources • Literal Conditions [ .. WHERE <field name> = <litel'al value> - Use values specified litera.l ly to restrict access - Allow declaration of new authorizations PFCG conditions ... WHERE ( <fieldl>, <.field2>, ... ) = aspect pfcg_auth( <authorization object>J cauthor-rzat Ion field 1>, <aLJthorization filed 2>, - Evaluate authorizations in user master record - Based on euthorizetion objects - Fit into SAP authorization concept ] Figure 152: Types of Conditions in DCL The following ways of defining conditions in DCL exist: Literal Conditions Compare one field of the CDS View with a literal value. PFCG Conditions Use one or several fields of the CDS View to look up authorizations in the master record of the current user. One PFCG condition is always based on one authorization object. The view fields on the left-hand side are assigned to the fields of the authorization object on the right-hand side. 210 © Copyright. All rights reserved. Lesson: Linking a CDS View with Authorization Rules @EndUserText.label: 'Demo: Authorization Check With Link to User Profile' @MappingRole: true define role S4d43'0_Role_C { grant select on S4d430_Access_control_c where (carrid) = aspect pfcg_auth( s_CARRID, CARRID, ACTVT = and (carrid_. counter) '03' aspect pfcg_auth( S_COUNlER, CARRIO, COUNTNUMJ ACTVT "' '03' )J } Left-hand side: One or more corrma-sepsrated view fields in brackets Right-hand sid:e: Key word ASPECT and function pfcg_auth( ) Arguments of pfcg_auth: One authorization object with its fields Figure 153: Example: PFCG Conditions The CDS role in the example above contains two PFCG conditions. The first condition is based on authorization object S_CARRID. In ABAP, the corresponding AUTHORITY-CHECK statement would look like this: AUTHORITY-CHECK OBJECT 'S_CARRID' ID 'CARRID' FIELD view-carrid ID 'ACTVT' FIELD '03'. The second condition is based on authority object S_COUNTER. This authorization object has three authorization fields: CARRID, COUNTNUM and ACTVT. The corresponding AUTHORITY-CHECK statement would look like this: AUTHORITY-CHECK OBJECT 'S_COUNTER' ID 'CARRID' FIELD view-carrid ID 'COUNTNUM' FIELD view-counter ID 'ACTVT' FIELD '03'. © Copyright. All rights reserved. 211 Unit 4: Advanced Concepts Template defineInstanceRole D x Templnte1ii �lect ,i.ne of titt fVJil41:,lc 1i.npl1lfl. Dumtln.tanc• flol�I Ddino la<taru:o Role wilh lnh,mance Defino Unres1,i�od Aec,,u Ro'le 'Deline ACCfl$ lnh;�.._;,g Rolt -ndUserloxt.lab<l: "S{d<l_sourc•_description} • (IMoppl.ngRol.,: truo dofin" r<>Jc S{dcl,_sQo.-.:e_•_l { gl" .t SIC'J!it:ct S{Cd$_<"tily} ll!lltc:r,ic S(c<>ndition)J < l!o<t. ..i_,__ __ � Ca.ni::el Figure 154: Template Define Instance Role Several templates exist for creating DCL sources. I» Note: In customer development systems, currently only template DefineInstaceRole is supported. Authorization-related Annotations Ill Annotations in DCL Sources @EndUserText.label: - Translatable short text for role (same as in DDL Sources) @Mappi ngRole: - Value true: Role is implicitly assigned to an users - Value false: Currently not supported by ABAP CDS Annotations in DDL Sources • @AccessControl .authorizationCheck: - #CHECK: Perform authorization check. Syntax warning if no role is assigned - #NOT_RE®IRED: Like #CHECK but suppress syntax warning - INOT_ALLOOED: No authorization check. Syntax warning if role is assigned I 212 Figure 155: Authorization-related Annotations © Copyright. All rights reserved. Unit 4 Exercise 15 Create and Use a DCL Source Business Example Template: S4D430_ASSOCIATION (DDL Source) Solution: S4D430_AUTHORIZATION (DDL Source) S4D430_ACCESS_CONTROL (DCL Source) Create a Copy of the Template CDS View Create a copy of your CDS View that exposes an association. If you did not complete the respective exercise, you can copy from CDS View S4d430_Association. 1. In your own Package, create a new DDL Source (suggested name: Z##_Authorization, where ## stands for your group number). 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##AUTH). 3. Open your DDL Source Z##_ASSOCIATION and copy the FROM clause and the field list to the new DDL Source. If you did not complete the respective exercise, you can copy from DDL Source S4D430_ASSOCIATION. 4. Perform a syntax check and activate your new DDL Source. Define A CDS Role Define a CDS Role for your CDS View Z##_Authorization. Make sure only bookings of those airlines are selected for which the user got reading authorization. 1. In your own Package, create a new DCL Source (suggested name: Z##_Access_Control, where ## stands for your group number). Choose template DefineMappingRole. 2. Edit the new DCL Source. After key word DEFINE ROLE, enter a name for the CDS Role. Hint: It is recommended to use the same name for the DCL Source and the CDS Role (apart from capitalization). Therefore, the recommended name for the rule is Z##_Access_Control. 3. After key word GRANT SELECT ON, enter the name of the CDS View you want to link with authorization rules (Z##_Authority). 4. After key word WHERE, enter the name of column CARRID in brackets. © Copyright. All rights reserved. 213 Unit 4: Advanced Concepts 5. Provide input for function aspect_pfcg_auth. First, enter the name of the authorization object, then the name of the authorization field that should be supplied with view field CARRID. The final argument for function aspect_pfcg_auth should be condition ACTVT = '03'. 10 Hint: The correct authorization object is S_CARRID. 6. Perform a syntax check and activate your new DCL Source. Check the Authorization Open the definition of the view for which you just defined a CDS Role. Open the Data Preview and make sure that only the data is displayed for which your user is authorized. 1. Open the definition of your CDS View Z##_Authorization. Where can you see that there is a CDS role assigned to this CDS View? 2. Open the CDS View with data preview. 3. Confirm that the result does not contain bookings for which your user does not have display authorization. Hint: Your user should not have display authorization for carrier UA. 4. Confirm that association _Connection is there and that you can follow it in data preview. 214 © Copyright. All rights reserved. Unit 4 Solution 15 Create and Use a DCL Source Business Example Template: S4D430_ASSOCIATION (DDL Source) Solution: S4D430_AUTHORIZATION (DDL Source) S4D430_ACCESS_CONTROL (DCL Source) Create a Copy of the Template CDS View Create a copy of your CDS View that exposes an association. If you did not complete the respective exercise, you can copy from CDS View S4d430_Association. 1. In your own Package, create a new DDL Source (suggested name: Z##_Authorization, where ## stands for your group number). a) See the corresponding step in the previous exercise. 2. In the new DDL Source, provide a suitable name for the DB View (suggested name: Z##AUTH). a) See the corresponding step in the previous exercise. 3. Open your DDL Source Z##_ASSOCIATION and copy the FROM clause and the field list to the new DDL Source. If you did not complete the respective exercise, you can copy from DDL Source S4D430_ASSOCIATION. a) See the corresponding step in the previous exercise. 4. Perform a syntax check and activate your new DDL Source. a) See the corresponding step in the previous exercise. Define A CDS Role Define a CDS Role for your CDS View Z##_Authorization. Make sure only bookings of those airlines are selected for which the user got reading authorization. 1. In your own Package, create a new DCL Source (suggested name: Z##_Access_Control, where ## stands for your group number). Choose template DefineMappingRole. a) In the ABAP perspective of Eclipse, right-click on your project and choose New → Other ABAP Repository Object. b) On the next window, choose Core Data Services→ DCL Source. c) Enter the name of your package, a name, and a short description for the new object and choose Next. d) If the tool asks for a template, select DefineMappingRole and choose Next. © Copyright. All rights reserved. 215 Unit 4: Advanced Concepts e) Assign the object to your transport request and choose Finish. 2. Edit the new DCL Source. After key word DEFINE ROLE, enter a name for the CDS Role. Hint: It is recommended to use the same name for the DCL Source and the CDS Role (apart from capitalization). Therefore, the recommended name for the rule is Z##_Access_Control. 3. After key word GRANT SELECT ON, enter the name of the CDS View you want to link with authorization rules (Z##_Authority). a) See source code extract from the model solution. 4. After key word WHERE, enter the name of column CARRID in brackets. a) See source code extract from the model solution. 5. Provide input for function aspect_pfcg_auth. First, enter the name of the authorization object, then the name of the authorization field that should be supplied with view field CARRID. The final argument for function aspect_pfcg_auth should be condition ACTVT = '03'. 10 Hint: The correct authorization object is S_CARRID. a) See source code extract from the model solution. 6. Perform a syntax check and activate your new DCL Source. a) See the corresponding step in the previous exercise. Check the Authorization Open the definition of the view for which you just defined a CDS Role. Open the Data Preview and make sure that only the data is displayed for which your user is authorized. 1. Open the definition of your CDS View Z##_Authorization. a) See the corresponding step in the previous exercise. Where can you see that there is a CDS role assigned to this CDS View? On the problems tab below the editor. there is a corresponding message in node Infos. 2. Open the CDS View with data preview. a) Right-click anywhere in the DDL Source and choose Open With→ Data Preview. 3. Confirm that the result does not contain bookings for which your user does not have display authorization. 10 216 Hint: Your user should not have display authorization for carrier UA. © Copyright. All rights reserved. Lesson: Linking a CDS View with Authorization Rules a) Sort the result by field CARRID and scroll down. b) Alternatively, you can right-click on column CARRID and choose Distinct Values for [carrid]. 4. Confirm that association _Connection is there and that you can follow it in data preview. a) Right-click on any line in the preview and choose Follow Assocation. b) In the dialog window, click on associaton _Connection. DCL Source S4D430_ACCESS_CONTROL @EndUserText.label: 'Solution: Role for View S4d430_Authorization' @MappingRole: true define role S4d430_Access_Control { grant select on S4d430_authorization where ( CARRID ) = aspect pfcg_auth( S_CARRID, CARRID, ACTVT = '03' ); } © Copyright. All rights reserved. 217 Unit 4: Advanced Concepts LESSON SUMMARY You should now be able to: 218 ● Understand the Concept of CDS DCL ● Create a DCL Source © Copyright. All rights reserved. UNIT 5 Database-Specific Features of ABAP CDS Lesson 1 Understanding CDS Table Functions Exercise 16: Define and Use a CDS Table Function 220 231 UNIT OBJECTIVES ● Understand the AMDP Framework ● Define CDS Table Functions ● Read Data From CDS Table Functions © Copyright. All rights reserved. 219 Unit 5 Lesson 1 Understanding CDS Table Functions LESSON OBJECTIVES After completing this lesson, you will be able to: ● Understand the AMDP Framework ● Define CDS Table Functions ● Read Data From CDS Table Functions Basic Features of AMDP Almost every database supports database procedures. Such procedures are stored and executed on the database. The implementation is usually written in a scripting language that is highly database-specific. As of release 7.40 SP05, ABAP supports database procedures that are stored in the ABAP repository and transported with standard ABAP transport requests. This technique is known as ABAP-Managed Database Procedures (AMDP). Ill ASAP Program By Database Procedure Stored Procedure on Database Figure 156: Basic idea of ABAP Managed Database Procedures The basic idea of AMDP is the following: The database procedure is defined and implemented as a method of a global class. The implementation of such a method consists of database-specific script that can only be executed on the database but not on the ABAP stack. 220 © Copyright. All rights reserved. Lesson: Understanding CDS Table Functions The AMDP framework creates a stored procedure on the database and redirects (or forwards) any call of the AMDP method to this stored procedure. CLASS cl_s4d430-amdp:._..dem.o IMPLEMENTATION. METHOD procedure BY OA:TABASE PROCEDURE FOR HDB LANGUAcGE. SQLSCRIP'I' OPTIONS READ-ONLY USING scustom. et_normal se].e,ct id, name from scustom where mandt = :iv mandt and name :iv_name; select id, name from scustom where mandt = :iv_mandt and contains( name, :iv_name, fuzz.y) order by score() .-tesc; ENDMBTROD. ENDCLAS,S. contains() and score(} are SAP HANA specific functions (not available in Open S.QL or CDS DOL) Figure 157: Example: Implementation of an AMDP Method This example shows the implementation of an AMDP method. Although the class is an ABAP repository object, the source code between METHOD and ENDMETHOD is not ABAP. The two statements are written in SQL Script as it is understood by SAP HANA database. Note: Although there is a lot of common ground between the syntax ABAP CDS DDL and SAP HANA SQL Script, you must not mistake the two. The following additions are needed in ABAP statement METHOD: FOR Specifies the database on which the AMDP can run. In the example, HDB stands for SAP HANA database. This is currently the only supported value. LANGUAGE Specifies the language of the implementation. In the example, it is SQL Script. This is currently the only value available to customers USING Is required if the method implementation uses objects from the ABAP Dictionary. Transparent tables and Dictionary Views are supported. CDS View names are not supported, here. If you want to use a CDS View in an AMDP, you have to access the corresponding CDS SQL View. OPTIONS Is intended for additional settings. Currently READ-ONLY is the only supported option. © Copyright. All rights reserved. 221 Unit 5: Database-Specific Features of ABAP CDS I Cl.A$$ cl_s4d430_amdp:._demo OEFlNI'fION. Implementation of this in,terfaoe mandatory PUBLIC SECTION. INTERFACES if_amdp_marker_hdb. TYPES ty_t_customers TYPE STANDARD TABLE OF .... CLASS-METHODS procedure Parameters passed by value 1 IMP 0RTING VALQE(iv_name) VALUE (iv_mandt) :EXF 0RTING TYPE s_custnanie DEFAULT 'Sc:hwarz' 'l'YPE mandt 1 VALUE(et_normal) TYPE ty_t_customers VALUE(et_fuzzy) TYPE ty_t_customers. , J ENDCLAS.S . Figure 158: Example: Definition of an AMDP Method This slide shows the definition of an AMDP class. Implementation of interface IF_AMDP_MARKER_HDB is mandatory. The parameters of the AMDP method have to be passed by value, and the parameter types need to be elementary types or table types. Structure types are not allowed. Ill 1 • Class D efi nit ion - Implementation of Interface IF_AMDP_MARKER_HDB • Method Definition - VALUE() addition for all parameters Only scalar or table types for parameters (no structures) • Supported Databases and Languages Only SAP HANA (at present) Only SAP HANA SQL Script (at present) • Use of Dictionary Object.s - Transparent Tables and Dictionary Views - CDS Views only via their CDS SOL Views - Need to be listed after USING l Figure 159: Prerequisites and Limitations AMDP Functions As of release 7.50, the AMDP framework supports AMDP functions alongside the existing AMDP procedures. 222 © Copyright. All rights reserved. Lesson: Understanding CDS Table Functions Global ASAP Class ASAP Program Method with Function script By By Database Procedure Database !Function il··:.� m1 •.1�.n 112 l.:l-11s1·'•we• : . ,., on Database Ill p Figure 160: AMDP Functions AMDP functions use the new addition BY DATABASE FUNCTION of the METHOD statement in AMDP classes. Unlike AMDP procedure implementations, AMDP function implementations have no export or changing parameters. They have exactly one tabular return value. AMDP function implementations cannot be called by an ABAP program directly. But they can be called from other AMDP functions or procedures. CLASS c;1_s4d430_amdp_demo DEFINITION. Same pre-requisites PUBLIC SECTION. as for AMDP procedures INTERFACES if_amdp_marker_hdb. TYPES ty_t_customers T'YPE STAND.ARD T'ABLE OF ...• Thii s method cannot be called in ABAP 1 CLASS-METHODS £unction IMPORTING VALtJE(iv_na.me} VALUE (iv_mandt) TYPE s c.ustname DEFAULT ' Schwarz ' TYPE ma.ndt RETURNING VALCJE(et_customers) TYPE ty_t_customers. ENDCLASS. Exactly one returning parameter Figure 161: Example: Definition of an AMDP Function This slide shows the definition of an AMDP class . AMDP method FUNCTION is intended to be implemented by a database function. It is defined as a functional method, i.e., it has exactly one tabular returning parameter and besides that only import parameter. © Copyright. All rights reserved. 223 Unit 5: Database-Specific Features of ABAP CDS Note: Once this functional method is implemented by a database function, you cannot call it in ABAP any more. CLASS cl_s4d430_amdp_demo IMPLEMENTATION. METHOD function BY DATABASE FUNCTION FOR. HDB LANGUAGE SQLSCRIPT OPTIONIS READ-ONLY USIN:G scustom. Return value is a table with return select id, name from scustom columns ID and NAME where mandt = :iv_mandt a1nd contains( na1me, :iv_name, fuzzy ) order by score() desc; ENDMETHOD, ENDCLASS. I Figure 162: Example: Implementation of an AMDP Function This example shows the implementation of an AMDP function. Addition BY DATABASE FUNCTION is used Instead of BY DATABASE PROCEDURE. The remaining additions have the same meaning and values as for database procedures. In the script for a database function, statement RETURN is mandatory. The RETURN statement defines the values for the return parameter. AMDP Functions for CDS Table Functions AMDP functions are functional methods of global classes which define functions stored and executed on the database. It is not allowed to call functional methods that define AMDP functions directly in ABAP. ABAP CDS introduced CDS table functions to make AMDP functions available as data sources of SELECT statements. 224 © Copyright. All rights reserved. Lesson: Understanding CDS Table Functions ABAP Program DDL Source Global ABAP Class D·efine Table Function ... By Database Function CDS Table Function Figure 163: The Basic Idea of CDS Table Functions The basic idea of CDS table functions is illustrated in the figure above: A CDS table function is defined in a DDL source via key word DEFINE TABLE FUNCTION. (Just like CDS Views are defined in DDL Sources via key word DEFINE VIEW.) The definition of the CDS table function refers to an existing AMDP function via addition IMPLEMENTED BY. An ABAP program (or a CDS View) can use the CDS table function as data source in the from clause of a SELECT statement – just like it would do with a CDS View, database view, or transparent table. • The CDS framework executes the SELECT from the CDS table function by calling the assigned function on the database. @EndUserText.label: 'Demo: Table Function' define table function S4d430_Table_Function with par-emeter s name_in s_ custname Parameters are passed to import parameters of AMDP function returns { mandt id name mandt; s_customer; s; custname; Field list of table function (= line type of AMDP function's return value implemented by m.ethod CL_S4!0430_AMDP_FOR_CDS=>FOR_TABLE_FUNC; _J Niame of AMDP class and AMDP methrod Figure 164: Example: Definition of a CDS Table Function © Copyright. All rights reserved. 225 Unit 5: Database-Specific Features of ABAP CDS The example shows the definition of a CDS table function. From the outside, it looks like the definition of a CDS View with an input parameter name_in and an element list with the three fields mandt, id, and name. I CLASS cl s4d430_amdp_for_cds DEFINITION. PUBLIC SECTION. INTERFACES if_amdp_marker hdb. TYPES ty_t_customers TYPE STANDARD TABLE OF .... No parameter definiition siqnature is taken fr-om CDS table function CLASS-METHODS for - table - func FOR TABLE FUNCTION s4d430_table_function. ENDCLASS. I Figure 165: Example: Definition of an AMDP Function for CDS An AMDP method that implements a CDS table function is defined without parameters. Instead, addition FOR TABLE FUNCTION … is used. The signature of the AMDP method is then taken from the CDS table function. Template defineTableFunctionWithParameters r New D�t, Oefi:nition x D TeJnpla:tes I s.l•ct one aHho •voilablttomp.1at.,,. Defino ti\;; type si,gnatu,c ..1 ,11 dimt dcF)tlndtnt COS ubtc function with impaotin� parameters. Thehbl•lundian i, impl@mi!nt� in the sped li!d AA.AP method\. The lib! funcliesn can be used in Op.ff> SOL !nd ,s, data IOUfC�il'I oth� ,;ic,;, clefi11ition1. @,EndUserTe,c't. labd: '•S{ddl_sourc•_de,cripticn} · d.,fine ta.hle function $,{ddl_sourc•_na=_.,ditabll!} witt> para.eters Hl'arca !!'ter_n• e} : $(pora=<eter_typ.e} relUl'IIS { S{clielllt_de«nt_n } : "b"P'· chit; S,{el, nt_na ,) ; S(el,o:e;it_typ,}; i{.:o,t�(lr'} < 11 ck c ncel Figure 166: Template Define Table Function with Parameters When creating a new DDL Source for a CDS Table function, you are supported by a dedicated template. 226 © Copyright. All rights reserved. Lesson: Understanding CDS Table Functions Creating a CDS Table Function When developing a CDS table function, it is most important to do it in the right order. • Create DDL Source for CDS Table Function - Use Template DefineTableFunctionWithParameters - Define parameters (optional) and return value (don't forget the client field!) - Leave the information after IMPLEMENTED BY as it is (not checked by syntax check) - Activate the DDL Source • Create AMDP Class With AMDP Method - Create a global class and implement interface IF_AMDP_MARKER_HDB - Define a public static method with addition FOR TABLE FUNCTION . - Implement the method as an AMDP function - Activate the global class Complete the Definition of the CDS Table Function - Enter the AMDP class and AMDP method after IMPLEMENTED BY - Activate the DDL Source - Test the CDS table function in data preview Figure 167: CDS Table Function: Recommended Sequence You have to create and activate the DDL Source first! This is because you need the existing, activated CDS Table Function when you define the AMDP method with addition FOR TABLE FUNCTION. On the other hand, it is no problem to activate the DDL Source before the AMDP method. The syntax check accepts a non-existent class and/or method after IMPLEMENTED BY. Once you finished implementing the AMDP function, return to your CDS table function definition and update the name of the AMDP class and the AMDP method. © Copyright. All rights reserved. 227 Unit 5: Database-Specific Features of ABAP CDS CDS Table Functions in Open SQL Use CDS Table function like any other CDS Views DATA gt_data, TYPE TABLE OF s4d430_table_function. PARAMETERS pa_nam lYP'E s_custname LOWER CASE D1EFAULT SELECT FIROM s4d430_table_function( name_in FIELDS id, name INTO TAIBLE @gt_data. = '.Schwarz'. @pa_nam Possible runtime error if AMDP not supported on current system: Cate9ory Rum;.i.De Error:, ASAP pr::Qil'r�n� error SAPSgL_UHSUPPOR!ED_FD.!UR[ Exce_pt. ASAP P'rogram CX_SY_SJ2L_UNSOE'PORTED_E'UJ1JR.[ S4D430_USE_!AB:LE:_roNC!ION Applicu:.1011 Componenr: one anci JUie CA 28.cn.2011 14:3!1:U I IShor,; tex,: Ull:!UPJX>lC1ll!d dai:ab.tsl!: exr.l!:l'.LII ea, J Figure 168: Use of CDS Table Function in Open SQL In Open SQL, you can use CDS table functions like any other CDS View. But you have to be aware that the underlying AMDP functions are not supported by all databases. (Actually, they are only supported by SAP HANA at present.) If a CDS table function is accessed in a system that does not support this feature, a runtime error occurs. You can catch this runtime error via exception class CX_SY_SQL_UNSUPPORTED_FEATURE. Syntax check issues a warning (direct or indirect use of AMDP!) l i The database feature "AMDP _TABLE_FUNCTION" is used here (read the long text). Check system capability and provide alternative coding ' DATA gt_feature_set: TYPE cl_:aba:p_dbfeatures=>features....;set_t. INSERT cl_abap_dhfeatures=>amdp_table_functions INTO TABLE gt_feature_set. IF cl_abap_dbfeatures=>use_features( gt_feature_set) = abap_false. ENDIF. ] Figure 169: Check of System Capabilities Needed To make you aware of this risk, ABAP syntax check issues a warning wherever a program accesses a CDS table function. These warnings are not restricted to direct use of the table function. If you access an ordinary CDS View that uses the table function as its data source, the system issues the same warning. 228 © Copyright. All rights reserved. Lesson: Understanding CDS Table Functions If there is the slightest chance that your coding might run on systems that do not support AMDP functions, use the service method of class CL_ABAP_DBFEATURES to check the systems capability. If it doesn't, stop program execution or provide an alternative coding. © Copyright. All rights reserved. 229 Unit 5: Database-Specific Features of ABAP CDS 230 © Copyright. All rights reserved. Unit 5 Exercise 16 Define and Use a CDS Table Function Business Example Template: CL_TABLE_FUNC_T1 (Global Class) S4D430_TABLE_FUNC_T1 (Executable Program) Solution: CL_TABLE_FUNC_S1 (Global Class) S4D430_Customer_Fuzzy (DDL Source) S4D430_TABLE_FUNC_S1 (Executable Program) Copy Template Class with Dummy Method Create a copy of template class CL_TABLE_FUNCTION_S1 and activate it. 1. In your own Package, create a copy of global class S4D430_TABLE_FUNC_T1 (suggested name: ZCL_##_TABLE_FUNC, where ## stands for your group number). Hint: If you want to perform this step in ADT, right click the global class and choose Duplicate. 2. Activate the new global class. Define a CDS Table Function Define a CDS Table Function that imports a customer name and returns a list of customer data. 1. In your own Package, create a new DDL Source (suggested name: Z##_Customer_Fuzzy, where ## stands for your group number). Choose template defineTableFunctionWithParameters. 2. In the new DDL Source, define an input parameter of type S_CUSTNAME (suggested name: NAME_IN). 3. Within the curly brackets after key word RETURNS, enter a list of customer data that should be returned by the table function. This list should include the client, the customer id, the customer name, the city, and the country. Make sure to use delimiter “;” after each return field (including the last!). © Copyright. All rights reserved. 231 Unit 5: Database-Specific Features of ABAP CDS Hint: You can look up appropriate data elements in the definition of database table SCUSTOM. 4. After key work IMPLEMENTED BY METHOD, specify the name of your global class and the name of the dummy method in this class. Hint: You can use the source code completion capabilities of the editor to enter this information. 5. Perform a syntax check and activate your new DDL Source. Implement the AMDP Method for the CDS Table Function In your global class, define and implement an AMDP method by decommenting the method implementation. Connect this AMDP Method to your CDS Table Function. 1. Edit your global class. Go to the implementation of method customer_fuzzy. Remove the full stop after the method name and decomment the additions BY DATABASE PROCEDURE ... USING SCUSTOM.. 2. Perform a syntax check. What does the syntax error say? 3. Adjust the method definition. Do not add parameters, directly. Use addition FOR TABLE FUNCTION instead and add the name of your CDS Table function. The method then takes over the import parameter(s) and the structure of the returning parameter from the CDS Table Function. 4. Perform another syntax check. What does the next syntax error say? 5. In the global section of the class definition, add interface IF_AMD_MARKER_HDB. 6. Complete the implementation by decommenting the SQL script coding in the AMDP method. 7. Activate your global class. Access CDS Table Function with Open SQL Create a copy of executable program S4D430_TABLE_FUNC_T1. In the FROM clause of the SELECT statement, replace transparent table SCUSTOM with your CDS Table Function. 232 © Copyright. All rights reserved. Lesson: Understanding CDS Table Functions Optionally, add coding that checks whether the current database supports CDS Table functions; and if it doesn’t, issue an error message. 1. Create a copy of executable program S4D430_TABLE_FUNC_T1 (suggested name of the copy: Z##_TABLE_FUNC, where ## stands for your group number). Hint: If you want to perform this step in ABAP Development Tools, choose Duplicate from the context menu. 2. In the From clause of the SELECT statement, remove transparent table SCUSTOM and replace it with your CDS Table Function Z##_Customer_Fuzzy. I» Note: Don’t forget to supply an actual value for the table function’s input parameter. 3. Execute a syntax check. Why do you get a warning from syntax check? 4. Optional: Before the select statement, implement a call of static method use_features of global class CL ABAP DBFEATURES. If table functions are not supported in this system, issue an error message, e.g., message 030 of message class S4D430. 5. Activate and test your program. © Copyright. All rights reserved. 233 Unit 5 Solution 16 Define and Use a CDS Table Function Business Example Template: CL_TABLE_FUNC_T1 (Global Class) S4D430_TABLE_FUNC_T1 (Executable Program) Solution: CL_TABLE_FUNC_S1 (Global Class) S4D430_Customer_Fuzzy (DDL Source) S4D430_TABLE_FUNC_S1 (Executable Program) Copy Template Class with Dummy Method Create a copy of template class CL_TABLE_FUNCTION_S1 and activate it. 1. In your own Package, create a copy of global class S4D430_TABLE_FUNC_T1 (suggested name: ZCL_##_TABLE_FUNC, where ## stands for your group number). Hint: If you want to perform this step in ADT, right click the global class and choose Duplicate. a) See the corresponding step in previous exercises. 2. Activate the new global class. a) See the corresponding step in previous exercises. Define a CDS Table Function Define a CDS Table Function that imports a customer name and returns a list of customer data. 1. In your own Package, create a new DDL Source (suggested name: Z##_Customer_Fuzzy, where ## stands for your group number). Choose template defineTableFunctionWithParameters. a) See the corresponding steps in the previous exercise. 2. In the new DDL Source, define an input parameter of type S_CUSTNAME (suggested name: NAME_IN). a) See source code extract from the model solution. 3. Within the curly brackets after key word RETURNS, enter a list of customer data that should be returned by the table function. This list should include the client, the customer id, the customer name, the city, and the country. Make sure to use delimiter “;” after each return field (including the last!). 234 © Copyright. All rights reserved. Lesson: Understanding CDS Table Functions Hint: You can look up appropriate data elements in the definition of database table SCUSTOM. a) See source code extract from the model solution. 4. After key work IMPLEMENTED BY METHOD, specify the name of your global class and the name of the dummy method in this class. Hint: You can use the source code completion capabilities of the editor to enter this information. a) See source code extract from the model solution. 5. Perform a syntax check and activate your new DDL Source. a) See the corresponding step in the previous exercise. DCDL Source S4d430_Customer_Fuzzy @EndUserText.label: 'Solution: Table Function' define table function S4D430_Customer_Fuzzy with parameters name_in : s_custname returns { mandt : mandt; id : s_customer; name : s_custname; city : s_city; country : country;} implemented by method CL_S4D430_TABLE_FUNC_S1=>CUSTOMER_FUZZY; Implement the AMDP Method for the CDS Table Function In your global class, define and implement an AMDP method by decommenting the method implementation. Connect this AMDP Method to your CDS Table Function. 1. Edit your global class. Go to the implementation of method customer_fuzzy. Remove the full stop after the method name and decomment the additions BY DATABASE PROCEDURE ... USING SCUSTOM.. a) See source code extract from the model solution. 2. Perform a syntax check. a) See relevant steps in previous exercises. What does the syntax error say? The method ... contains a database function. but there is no RETURNING parameter defined. 3. Adjust the method definition. Do not add parameters, directly. Use addition FOR TABLE FUNCTION instead and add the name of your CDS Table function. The method then takes over the import parameter(s) and the structure of the returning parameter from the CDS Table Function. © Copyright. All rights reserved. 235 Unit 5: Database-Specific Features of ABAP CDS a) See source code extract from the model solution. 4. Perform another syntax check. a) See relevant steps in previous exercises. What does the next syntax error say? Database procedures managed by ABAP can only be defined in classes that implement the marker interface "IF_AMDP_MARKER_HDB". 5. In the global section of the class definition, add interface IF_AMD_MARKER_HDB. a) See source code extract from the model solution. 6. Complete the implementation by decommenting the SQL script coding in the AMDP method. a) See source code extract from the model solution. 7. Activate your global class. a) See the relevant steps in previous exercises. Global Class CL_S4D430_TABLE_FUNC_S1 CLASS cl_s4d430_table_func_s1 DEFINITION PUBLIC FINAL CREATE PUBLIC . PUBLIC SECTION. INTERFACES if_amdp_marker_hdb. CLASS-METHODS customer_fuzzy FOR TABLE FUNCTION s4d430_customer_fuzzy. ENDCLASS. CLASS cl_s4d430_table_func_s1 IMPLEMENTATION. METHOD customer_fuzzy BY DATABASE FUNCTION FOR HDB LANGUAGE SQLSCRIPT OPTIONS READ-ONLY USING scustom. RETURN SELECT mandt, id, name, city, country FROM scustom WHERE contains( name, :name_in, fuzzy ) ORDER BY score( ) desc; ENDMETHOD. ENDCLASS. Access CDS Table Function with Open SQL Create a copy of executable program S4D430_TABLE_FUNC_T1. In the FROM clause of the SELECT statement, replace transparent table SCUSTOM with your CDS Table Function. Optionally, add coding that checks whether the current database supports CDS Table functions; and if it doesn’t, issue an error message. 1. Create a copy of executable program S4D430_TABLE_FUNC_T1 (suggested name of the copy: Z##_TABLE_FUNC, where ## stands for your group number). 236 © Copyright. All rights reserved. Lesson: Understanding CDS Table Functions Hint: If you want to perform this step in ABAP Development Tools, choose Duplicate from the context menu. a) See relevant steps in previous exercises. 2. In the From clause of the SELECT statement, remove transparent table SCUSTOM and replace it with your CDS Table Function Z##_Customer_Fuzzy. I» Note: Don’t forget to supply an actual value for the table function’s input parameter. a) See source code extract from the model solution. 3. Execute a syntax check. Why do you get a warning from syntax check? Because table functions are not supported by all database systems. you need to check before this SELECT statement. that it is supported n the current system. a) See relevant steps in previous exercises. 4. Optional: Before the select statement, implement a call of static method use_features of global class CL ABAP DBFEATURES. If table functions are not supported in this system, issue an error message, e.g., message 030 of message class S4D430. a) See source code extract from the model solution. 5. Activate and test your program. a) See relevant steps in previous exercises. *&--------------------------------------------------------------------* *& Report s4d430_asso_s1 *&--------------------------------------------------------------------* *& *&--------------------------------------------------------------------* REPORT s4d430_table_func_s1. TYPES: BEGIN OF ty_s_customer, id TYPE Scustom-id, name TYPE scustom-name, city TYPE scustom-city, country TYPE scustom-country, END OF ty_s_customer. TYPES ty_t_customers TYPE STANDARD TABLE OF ty_s_customer WITH NON-UNIQUE KEY id. DATA gt_customers TYPE ty_t_customers. © Copyright. All rights reserved. 237 Unit 5: Database-Specific Features of ABAP CDS * ALV Processing DATA go_salv TYPE REF TO cl_salv_table. DATA gx_excp TYPE REF TO cx_salv_error. * Selection Screen PARAMETERS pa_nam TYPE s_custname DEFAULT 'Schwarz' LOWER CASE. * Check db feature DATA gt_feature_set TYPE cl_abap_dbfeatures=>features_set_t. START-OF-SELECTION. * Optional: Check if table functions can be used on this DB ************************************************************** INSERT cl_abap_dbfeatures=>amdp_table_function INTO TABLE gt_feature_set. IF cl_abap_dbfeatures=>use_features( gt_feature_set ) = abap_false. MESSAGE e030(S4D430). ENDIF. * Alternative with VALUE expression (Rel. 7.40) *IF cl_abap_dbfeatures=>use_features( * VALUE #( ( cl_abap_dbfeatures=>amdp_table_function ) ) * ) = abap_false. * MESSAGE e030(S4D430). *ENDIF. * Data Retrieval ************************************************************* SELECT FROM s4d430_table_function( name_in = @pa_nam ) FIELDS id, name, city, country ORDER BY country, city, name INTO TABLE @gt_customers. * output ************************************************************* TRY. cl_salv_table=>factory( IMPORTING r_salv_table = go_salv CHANGING t_table = gt_customers ). * Display *-------------------------* go_salv->display( ). CATCH cx_salv_error INTO gx_excp. " MESSAGE gx_excp TYPE 'I'. ENDTRY. 238 © Copyright. All rights reserved. Lesson: Understanding CDS Table Functions LESSON SUMMARY You should now be able to: ● Understand the AMDP Framework ● Define CDS Table Functions ● Read Data From CDS Table Functions © Copyright. All rights reserved. 239 Unit 5: Database-Specific Features of ABAP CDS 240 © Copyright. All rights reserved. UNIT 6 Consumption of CDS Views (Outlook) Lesson 1 Using a CDS View as Data Source for ALV IDA 242 Lesson 2 Using CDS Views as Replacement Objects 249 Lesson 3 Generating OData Services from CDS Views 253 Lesson 4 Understanding the Consumption of CDS Views in SAP Fiori 260 Lesson 5 Understanding Analytics Based on CDS Views 264 Lesson 6 Understanding Virtual Data Models with CDS Views 269 UNIT OBJECTIVES ● Understand ALV with Integrated Data Access (ALV IDA) ● Display Data with ALV IDA ● Use CDS Views as Data Source for ALV IDA ● Understand Replacement Objects ● Describe the benefits of SAP Gateway and OData ● Publish Gateway Services via CDS View Annotation ● Understand the Consumption of CDS Views in SAP Fiori ● Understand Analytics with CDS Views ● Understand Virtual Data Models (VDM) © Copyright. All rights reserved. 241 Unit 6 Lesson 1 Using a CDS View as Data Source for ALV IDA LESSON OBJECTIVES After completing this lesson, you will be able to: ● Understand ALV with Integrated Data Access (ALV IDA) ● Display Data with ALV IDA ● Use CDS Views as Data Source for ALV IDA Reminder: Classic SAP List Viewer (ALV) SAP �®lill � I [i][i)(OO] �l[IL]Li}l���[g) IBGOk. no. c Cost. No. Agem:y ... Stlt,,. ID No. Fil)ht Date 10 118 CXXl AA 64 lO.CM.;1117 468') 10 10 1() 101 0::::0 A2 I Kl_ 55 SSS V.00.2017 5:5-S 05.10.2017 1007 28'1,S:O Kl. 12-0io::::o A2 102 coo A7. 719 27.00.21117 789' OUl7,20.lt 790 30.05.2017 ID 10 1C) a::o ID 10 10 1'0 1080::::0 A2 101 Dl 119 a::o .JL 103 0::::0 LH Kl. cco in 115 10 10 10 112 I LH ll8CC81 QF 254 0:::0 Qf 0:::0 LH 790 790 .1984 407 41)(1 402 41J2 S 6 01.07 .21117 02.06.2017 21.02.2017 lO.CM.21117 2io.02,20.17 28.07. 2017 03.10 .20.17 05.09,2017 30.05.20.17 203 6464 1995 119H 12297 l�SS 16 1251 ss IOOB2 11799 2493 4250 � ml Aif.lre,CI.Jrr. 373,98 185,00 130,55 1.000,00 1.0(30,00 466,44 1.()14,00 1.0,10,23 461,00 961,00 0,00 666,00 604.42 851,78 0,00 ..UR wt EUR WR WR e.JR WR WR EUR EUR EUR EUR EUR EUR f;UR Figure 170: SAP List View (ALV) SAP List Viewer (ALV) is the preferred technique to display and format list-like data in SAP GUI-based applications (reports and dialog transactions). 242 © Copyright. All rights reserved. Lesson: Using a CDS View as Data Source for ALV IDA I 8./Wr'iJ t 1 I ±4± I I � � ----------------------------- : UI Info (@A 1@1') External Format I Raw Data Authority. Business Check Data l Relevant data is extracted in�o an internal table after the application performs the necessary authorization checks Calculated Business Data columns may be added by the application UI information {for example icons or links) is added ALV services manipulate the data (sent via an internal table) based on user interaction Required data is displayed on the screen Figure 171: Classical ALV – How It Works The figure shows the approach to displaying data using the classical ALV. The steps shown provide an example of what the ABAP application would typically do. Classic a I ALV Problems • Working with huge amounts of data (potentially millions of records) • Initial Load -All data needs to be loaded from the database into an internal table • Sorting, filtering, grouping can take a substantial amount of time Demo: Data display with Classical Al V PA_CUR so.cus SO_AGCY to to Users may restrict the amount of data to be shown lo try to speed up processing Waiting too long before results displayed Runtime errors can occur due to memory consumption Figure 172: Classical ALV – Problems For an end user, working with large amounts of data in a classical ALV can be cumbersome and time-consuming. The issue is that it is optimized for the old paradigms and constraints, where the database is considered the bottleneck. The classic ALV requires all data to be first loaded into an internal table in order to display it. Typically, this is larger than what is actually displayed to the user. © Copyright. All rights reserved. 243 Unit 6: Consumption of CDS Views (Outlook) This initial load can lead to very long waiting times for the end user, or even short dumps due to memory consumption. Due to these issues, the user may restrict the amount of data beforehand, leading to incomplete data sets. Once the data is loaded, all processing takes place in the ABAP stack on the internal table, for example, sorting the data set, filtering the data set, grouping, aggregating, or adding calculated columns. Even paging through the result set happens in the ABAP stack. All of these processing steps can take a long time, and again consume a large amount of memory when dealing with large amounts of data. Clearly, the way in which the classical ALV works contradicts the new Code-to-Data approach. This is the reason for the new variant of the SAP List Viewer. ALV with Integrated Data Access (IDA) The ALV with intergrated data access (ALV IDA) is significantly different to the classical ALV – especially when used in combination with ABAP CDS. Table or View -,_)_ L�<R�:· -----.--------�---_] -- ......... UI Info (e,A1@) .... , - External Format . . � Authority checks, table functions, paging, sorting, filtering are now performed by the database via the relevant parameters UI information is still handled by the application Amount of data is severely restricted by the detabese before it is displayed on the UI and it is not required to store ii in an internal table. Figure 173: The new approach – ALV with Integrated Data Access (ALV IDA) Authority checks, table functions, and other processes that were previously carried out by the application are now performed by the database. The application only has to pass the details to the new ALV API; For example, a WHERE clause can be sent to the database by calling relevant methods. Additional UI information is still handled by the application. The amount of data is severely restricted by the database before it is displayed on the UI, and there is no longer a need to store the displayed data inside an internal table. I» 244 Note: Package SALV_IDA_TEST contains sample programs using the ALV IDA. © Copyright. All rights reserved. Lesson: Using a CDS View as Data Source for ALV IDA • Reduced toolbar compared to the classic ALV ll'ltlrt. Nal'l'l4l ml!! Stteel l $,&I A.G Ftma DiBIIMr·HC:W-Aloo 16 2 Ard!!� KID!% f-11!.--r 3 -� 4S� S�th , '*" ... _. Eilll!I' �9 V�.$-1.? 5 Starr �teF.te-r 7 � 8Moore, � Eve"tanfC � lDRal.JII) @:JI Ql'.ltffil:B iilcolrm! SiWellroQ!COR.ood li!!IT @'11 �� . [Ill ,iji'"""""i�··· Cu!lt .... Name 1 s.llJ'A6 �... FIIM 2�Ki)tt He<r 3 1-1.,J>; 9.6"Qel' l-iet1r ,t Stilelclo: Frill.J s� ,� 6 Sl<ll 8 '-b:lfe 9 E\le«on fC m� • Users can select a column or a cell and make use of several options in ·the context menus • The layout, sort and filter settings can also be changed using ·the Change Layout button !Ml Col'11rnn� l:Jde �t ;-, ,a_� cmer· �� Sa,rtn�Order j;lr.�om Flier .. , MIS$ ,r:l_,� "'5w- c ouoAJ lot.I �ltrw ill GCJU'r'm He<r deb:!i, fl! deb!ra fl! LC � �� � S\ LC � II l[ - (ll(ti:irr.� f!Jl"l,H'� ..,"""" -_--.......... ........., ,..,..,,,.,,.., ...... ..., Figure 174: ALV for HANA – End User Perspective The ALV IDA will look and feel familiar to end users who have worked with the classical ALV, but there are some small differences in functionality and behavior. Data Display with ALV IDA Relevant interfaces: if_salv_gui_ ... ida DATA: go_salv TYPE REF TO if_salv_gui_table ida, go_full TYPE REF TO if_salv gui fullscreen ida. Factory method for ALV IDA instance go_salv = cl_salv_gui_table_ida=>create ,( io_gui_container iv table name = 'SBOOK' = -. ), - go_full = go_salv->fullscreen(). go:_full->display(). Optional: Assignment to a container Alternative: Create fullscreen object Same coding with method: chaining cl_salv_gui_table_ida=>create( iv_table;_name = 'SCUSTOM' ) ->full.scrseen ( ) ->display ( ) . I Figure 175: Example: ALV IDA in Fullscreen Mode The coding example shows how you can display the content of a table using the ALV IDA in a report. © Copyright. All rights reserved. 245 Unit 6: Consumption of CDS Views (Outlook) Instead of feeding the ALV instance with the data to be displayed, you only have to specify the table (or Dictionary view) the data come from. The ALV will read the necessary data (and only the necessary data) from that data source. Regarding the display, you can either link the ALV IDA instance to a container control (optional parameter io_gui_container) or you can create a fullscreen object (method fullscreen). Note: With method chaining (available as of Release 7.02) the entire coding becomes a single ABAP statement. ALV IDA Based on a CDS View Ill t DA.Tl\: go salv TYPE REF TO if_salv_gui_table ida, go_full TYPE REF TO if_salv_gui_fullscreen_ida. Special factory method for CDS views go_salv cl_salv_gui_table_ida=>create_for_cds_view( . 0 Cf'_/ i C: , r t el � e 'S4D430 ALV IDA' iv eds view name - , I - ) .- go full; go salv-�fullscreen( l. go_full->display( l. Name of CDS View {not the SOL View) Figure 176: Example: ALV IDA Based On a CDS View The coding example shows how you can display data from a CDS View. You have to call the dedicated factory method create_for_cds_view if you want your ALV IDA to read from a CDS View. Regarding the display, the same options exist as with factory method create. 246 © Copyright. All rights reserved. Lesson: Using a CDS View as Data Source for ALV IDA Selections and Input Parameters SELECT-OPTIONS: so_cus Helper class to FOR gs_dQtQ-customid. aggreg1ate rang:es DATA: go_range_collector TYPE REF TO cl salv range_tab_collector, gt_named_ranges TYPE if salv_service types- ·yt_named_ranges. go_salv cl_salv_gui_table_ida=�create_for_cds_view( iv _cds_view_name = 'S4 u., jJ u ' ) . CREATE OBJECT go_range_collector. go_range_collectox->add_xanges_for_name( iv_name it_xanges I 'CUSTOMID' so_cus [] } . go_range;_collector->get_colleoted_ranges( IMPORTING et_na:med_ranges gt_named_ranges). go_salv->set_select_options{ it-ranges gt_named_ranges). Figure 177: Example: Data Restriction with Select-Options The coding example shows how you can use select options (range tables) to restrict the data your ALV IDA displays. You do so by calling method set_select_options of your ALV IDA instance. For this method, you have to convert the select options and combine them into one internal table. The recommended way to do that is to use an instance of helper class cl_salv_range_tab_collector. PARAMETERS: pa_cur TYPE s4d430_s_classical_alv-currency DEFAULT 'USO'. DATA: gt_params TYPE if_salv_gui_types_ida=�yt_parameter, gs_param TYPE if_salv_gui_types_ida ys_parameter. go_salv cl_salv_gui_table_ida-'create_for eds view( iv_cds_view_name = 'S4J4{v LV �JA' gs_panm-name = 'CURRENCY_IN' · Fill internal table with namelvalue pairs gs_param-value = pa-cur. APPEND gs_param TO gt.yarams. ' go:_salv->set_view_parameters( it_parameters name value J gt_params ) . Alt.ernativ syntax with VALUE expression go_salv->set_view_parameters( it_Farameters =VALUE#( ( ) . 'CURRENCY IN' pa cur ) ) J. Figure 178: Example: Providing Values for an Import Parameters © Copyright. All rights reserved. 247 Unit 6: Consumption of CDS Views (Outlook) The coding example shows how to deal with a CDS View that has input parameters. To provide values, you have to call method set_view_parameters for your ALV IDA instance. The method expects as input an internal table with pairs of parameter names and actual values. As in the example above, you can fill this table with ABAP statement APPEND. Alternatively, you can omit the helper variables gt_params and gt_param if you use a VALUE expression (available as of Release 7.40). LESSON SUMMARY You should now be able to: 248 ● Understand ALV with Integrated Data Access (ALV IDA) ● Display Data with ALV IDA ● Use CDS Views as Data Source for ALV IDA © Copyright. All rights reserved. Unit 6 Lesson 2 Using CDS Views as Replacement Objects LESSON OBJECTIVES After completing this lesson, you will be able to: ● Understand Replacement Objects Replacement Object Principle ASAP Program SELECT FROM ••• CDS View Transparent Table Access redirected to replacement object CDSSQLView Database Table Figure 179: The Basic Idea of Replacement Objects A CDS view can be defined as a replacement object for a database table or a classic database view in ABAP Dictionary. If a replacement object has been assigned, any read access via Open SQL statement SELECT will be redirected to the replacement object. © Copyright. All rights reserved. 249 Unit 6: Consumption of CDS Views (Outlook) ASAP Program INSERT DELETE MODIFY CDS View Replacement ignored for write accesses CDSSQLView Transparent Table Standard Behavor Database Table Figure 180: Replacement Only for Read Access Replacement Objects only take effect for read accesses. Any write access to the table is not redirected. Prerequisites for Replacement Objects • Matching Structure Type - Same number ct components - Same component names (exception: client field) - Same technical types, including length and decimals - Note: Order of the components can be different • Restiriction for the CDS View - No input parameters • Restriction in Customer Syst.ems - Replacement objects only for (own) Dictionary views - No replacement objects for tables J 250 Figure 181: Prerequisites and Restrictions © Copyright. All rights reserved. Lesson: Using CDS Views as Replacement Objects Assigning a Replacement Object � �nment Sr.:tem 1;!!11 T.ble L�!lQ!n . jibhial saa (h . !!le11rdlr Dlipliy C'tdt511tt+IF!2 Sepch �et! for hble ... Ai;tmtilln T:(11a ... Oiil!lgeJD!wbY .I�� CiihlQil'l' �hanc�ment cat@')O.f'I' .•• !"rol\YObi«I. ... �ho-,/H,:le SWlteh @ KQG[I )ff300 Oeflle/01.J,nge Proxy Ot;Ject i3ble: Proi,:yObject fo1 S4 . .: S4!>130_:SFLJGHTJI rS4D43a M:PI.Ji.cri-<.oo "' - Figure 182: Assigning a Replacement Object In order to make a CDS view the replacement object for a table or classical Dictionary view, proceed as follows: 1. Open the table definition or Dictionary view (transaction SE11, SE80). 2. From the menu, choose Extras→ Proxy Object…. 3. On the dialog box, enter the name of the CDS View. 4. Choose Apply. [o Hint: In older releases, the menu path was Extras→ Replacement Object…. If you define a replacement object for the first time, the system checks whether the specified CDS view meets the prerequisites. If a CDS view used as a replacement object is changed later and the prerequisites are no longer met, a runtime error DBSQL_REDIRECT_INCONSISTENCY occurs when an Open SQL read is performed on the database table or on the database view. © Copyright. All rights reserved. 251 Unit 6: Consumption of CDS Views (Outlook) Application Scenarios for Replacement Objects • Elimination of Aggregate Tables - Replacement of aggregate tables (filled in background jobs) - The replacing CDS Views aggregate the data in real time Benefit: Easy and central redirect of all read accesses • Support for Re�design of Data Model - New data model to substitute old data model - Replacement of old database tables - The replacing CDS Views access the new tables ano reconstruct the content of the old tables Benefit: Easy and central redirect of all read accesses Attention: All write accesses have to be adjusted manually! I Figure 183: Important Application Scenarios for Replacement Objects LESSON SUMMARY You should now be able to: ● 252 Understand Replacement Objects © Copyright. All rights reserved. Unit 6 Lesson 3 Generating OData Services from CDS Views LESSON OBJECTIVES After completing this lesson, you will be able to: ● Describe the benefits of SAP Gateway and OData ● Publish Gateway Services via CDS View Annotation SAP Gateway Introduction The growth of the mobile device sector is driving the demand for new innovative applications for business and enterprise. The large number of developers who are developing these applications very often have knowledge of technologies such as .NET, JAVA, and HTML5, but without a strong SAP background, they would need an interface to the SAP Business Suite systems to develop for SAP platforms. -D Support: End-to-end scenarios New devices and experiences Growing new communities of agile developers Simple aooess to complex enterprise systems Expansion or business data and decision makers Manage and control mission critical systems AND deploy innovative solutions Consumer innovations in the enterprise Figure 184: SAP Gateway Mobile access to complex enterprise systems and expanding business data requires that SAP customers can manage and control mission-critical systems, and deploy innovative solutions at the same time. SAP Gateway is an innovative solution for simple and robust business enterprise mobile access. © Copyright. All rights reserved. 253 Unit 6: Consumption of CDS Views (Outlook) Key Challenges in Enterprise Computing for Business Consumers I> SharePoint O Office Socia! Mobae Browser Enti!rprls11 Enterprise Plaifonns Devices Based Software Cloud Point to Point Solutions Increase Costs & Complexity SAP Business Sutte Figure 185: Enterprise Computing for Business Consumers Key Challenges The problem in the past was that for different consumers a developer had to build a specific integration scenario that used its own protocol. However, one-off applications specific to each device or platform were not transferable. For example, a solution built for browser-based applications could not be used for an integration of enterprise software. The solution is to use one protocol, the OData protocol. 254 © Copyright. All rights reserved. Lesson: Generating OData Services from CDS Views The Solution: OData Ill> SharePoint O Office Social Plaifonns Mobne Browser Based Devices Enterprise Enterprise Software Cloud ••••--- -SAP Gateway CRM SRM SCM PLM EIRP SAP Business Suite Figure 186: The Solution: OData OData was originally invented by Microsoft and shared through the open specification promise. It has become an industry standard; the latest version, version 4 is an OASIS standard, which is now driven by SAP, Microsoft, IBM, and a number of other companies. SAP Gateway is used by SAP Business Suite and SAP S/4HANA to publish OData services built on top of the ABAP application server. SAP Gateway enables consumption of SAP Business Suite and SAP S/4HANA data for people-centric applications across multiple channels. What is OData? The most important point is that the OData service forms a kind of contract between the nonSAP side and the SAP side, helping to bring together developers on both sides. OData Benefits Based on Representational State Transfer (REST), OData provides compelling benefits for SAP application development, which include the following: ● ● ● It is relatively lightweight and builds on the HTTP protocol allowing database-like access to data via the web. In addition to being an industry-standard protocol for creating and consuming data APIs, the OData protocol became an Organization for the Advancement of Structured Information Standards (OASIS) standard with its latest version, OData v4. OData allows for a decoupling of the data provisioning from the UI designers by providing a contract between the non-SAP developer or UI designer and the SAP developer. ● Because it is supported by various platforms, it supports multichannel access to SAP Data. ● It has been broadly adopted; the main drivers are SAP, Microsoft, and IBM. © Copyright. All rights reserved. 255 Unit 6: Consumption of CDS Views (Outlook) ● ● The standard address representation or resource is the Uniform Resource Identifier (URI). OData supports two formats for representing the resources it exposes; the XML-based AtomPub format and the JSON format. SAP Gateway Architecture SAP Gateway 2.0 is technically based on ABAP add-ons that are deployed to the SAP NetWeaver stack (7.0, 7.01, 7.02, and 7.31). There are add-ons that provide the SAP Gateway Server functionality (GW_CORE and IW_FND) and there is an add-on (IW_BEP) that provides the SAP Gateway backend functionality. The add-on IW_BEP is deployed on the SAP Business Suite backend because that is where the service development takes place. With SAP NetWeaver 7.40, the software components of these add-ons are delivered as part of the SAP Basis in a single software component, SAP_GWFND. This means that the software components for the backend functionality, as well as the software components for the SAP Gateway server functionality, are available on every system running on top of SAP NetWeaver 7.40. OData SAP Gateway Gateway Backend Enablement SAP HANA I Any DB SAP Business Suite Figure 187: SAP Gateway Architecture 256 © Copyright. All rights reserved. Lesson: Generating OData Services from CDS Views OData Service Development with SAP ABAP CDS Views OData Service Development with CDS 0 fJ e J Mapped Datasource - SEGW Import DDIC structures, create associations and map them to CDS views Referenced Datasource - SEGW Generate an OData Se1ivice from a CDS including associations OData.publish: true· ADT Generate OData Service without SEGW l Figure 188: OData Service Development with CDS There are three options to leverage CDS views in an OData service development in SAP Gateway. The options are as follows: ● First option - ● Second option (no mapping required) - - ● As of SAP NetWeaver 7.40, you can map a CDS view and its associations to the entity sets and navigation properties of an OData service. You can redefine the methods of the MPC_EXT and DPC_EXT class to implement enhancements on the OData model or service implementation level. As of SAP NetWeaver 750, CDS views can be used as Referenced Datasources in SEGW. Third option (no mapping required) - You can set an appropriate annotation OData.publish: true. The generated service does not offer any enhancements on the SAP Gateway level. In this introductory lesson, we will focus only on the third option. © Copyright. All rights reserved. 257 Unit 6: Consumption of CDS Views (Outlook) Oeslgntlme, Runtime Bro� (Fl«I launchpad) SAP Fioriapp SAP Web IDie Ul5 HTTPS HTMl/OOata IIWFNDIMAINT_ SERVICE T�clRFC SAP NecWeaver 7.52 (ABAP OData Provider) SAP Gateway111untlmei (backendJ 1-�&-1 SA!ll {G�n�rl, !lPC!lMll'C] Read ABAP aaehnd Bu$lnou Logfe (ClassEs,aAl!'I, I Developmerit Tools CDS View Figure 189: SAP Fiori Programming Model — SAP NetWeaver 7.4 With SAP NetWeaver 7.40 or later, it is possible to use SAP Gateway for building OData services that read access to CDS objects. Use CDS views as mapped data sources, it is no longer necessary to use coding for read access. Requests that perform changes require additional manual implementation. Gateway Service via CDS View Annotation Publishing @Ab, p(gp loE! &q IViewNall'!e; • ZSEPN_lSOf_TPL. @MapCataloe cor,1piler c0mp�reFilteca tr-ue �ces cootrol. <1u horha @l;ndlJserlext.l_;,llel: on(heck, =CHECK ·�le;sOrders - EPM Demo Data' @Ql!>a:ta. publfs h : true define view l�C��-l�'i9-rd�_l_ "" select fr""' Sll:'!Ll_Scal!tJ,jkol_<tr_� { - ��� l.l'l��l'MIII' ��·Er+1�0MI NPHC:5tfff!'fffPU'I l'Jli .. ,� j�.,._...,p•'"""".......,"""'" ls.y$lelnAl>MeS �ftN.tu�'Sl.a � 'l,wrwd� W':!r,wm.wli � � la4�- Figure 190: Used Code 258 © Copyright. All rights reserved. Lesson: Generating OData Services from CDS Views Development Flow: 1. Create CDS view with annotation: @OData.publish: true 2. Service is generated in the SAP Business Suite Backend System (Name of generated Service: <View Name>_CDS) 3. Service can be published in the SAP Gateway Server (Frontend Servcer) (Transaction / IWFND/MAINT_SERVICE) Actlv.tt-e and M.tlnt-aln Services lype _ TeclYiicil Sem::e Name SEP ZSEPM c SALESORIER TE\ cps I � !CF Node • JI . cal � "'v .. sern:e oescr.:ioon External Service Name 1 Sale:sO!rders • EFlf.t De1111'J Data �SAP Gateway Client ZSEpM c SALESORDER N.;imasp; IP\- cps I ]CiF Nodes System Aliases SAP System Alas LOCAL Desotitbn Local System � Figure 191: Result LESSON SUMMARY You should now be able to: ● Describe the benefits of SAP Gateway and OData ● Publish Gateway Services via CDS View Annotation © Copyright. All rights reserved. 259 Unit 6 Lesson 4 Understanding the Consumption of CDS Views in SAP Fiori LESSON OBJECTIVES After completing this lesson, you will be able to: ● Understand the Consumption of CDS Views in SAP Fiori Fiori Applications Based on ABAP CDS For standard Uls Fiori Elements generates the UII • no coding needed 01 02 D t Model rng Expose OData service Ba.ckend Developer ABAP in Eclipse ABAP I CDS Sources Backend Developer ABAP in Eclipse & SAP Gateway Tools Gateway Services UI Developer Role WeblDE Toolset Ul5 Sources Entities Figure 192: Key steps and Development Tools The development of SAP Fiori applications starts with the data modelling phase. After the back-end developer has built ABAP CDS sources, he or she uses the odata.publish: true annotation to registers the OData service in the backend. Then the developer publishes it to the SAP Gateway Hub system using transaction /IWFND/MAINT_SERVICE. In this lesson, you will see how the UI developer finally takes the published service to generate a user interface. To do so, the developer uses SAP Web IDE. Note: Standard UI Fiori elements generate the complete UI, so that no coding is required. 260 © Copyright. All rights reserved. Lesson: Understanding the Consumption of CDS Views in SAP Fiori Fiori Elements 001 \/>, omet '-APV, I c � Ol.!t!kStli'I N n·Plot*CI from lllrr:l)l;III - wtliU)'DUl .. rrpor � - � ifil;ll - NNPf<llld tO/IISO/n _.,, ..._. ..,, KS � $,l'Ul$"8AP Cio.,.komOI R-� lla>o"°'l' SAP .�IOf�p;lg(l ·,AP '. ICE 000:.. A$ a� en SAP comml.lNl'j' SAP Fi0<10esign ilJeine$ SAP . ICE $OK 'Af'Vi5SOK T lOI' Figure 193: Landing Page in SAP WebIDE After the user logged on to SAP WebIDE, he or she can start development by creating a new project. In order to use SAP Fiori Elements, the new project should be based on a template. x BasK:.JnEorma.tioo New U5t Report Application Template Selection Sear Gil SCi!By SAP F!OII Ma51er-OotaU ll!lPIIU::.on • Noxl oil! "ti o.... rv1.... i>"""" Apr,lla1io,, t, Figure 194: Template List Report Application List Report Application is one of the templates offered by Fiori Elements. It creates a Fiori application with a list display and is based on an OData service and a CDS View. © Copyright. All rights reserved. 261 �, Unit 6: Consumption of CDS Views (Outlook) � Run �.maxnlnll .... <f' 00 Wllll<sp;!Ce a S1and�r� � G City Counuy c5l Q. se.,rc11 � Fllgl!t BOOltings (100.110) ..,_ COMe Standard· Fll,ilU03".c 0 Parme Bco1<111gn-. (uStomll<natne 00000001 11900 USD USO jl(U 0017 2123117 0017 �:i.·11 � .Jcflann EIUe:Ntt onnsiopn R�a• n;i 30 WO USO M .»11 2/;2�17 0000000. Ol!tis ne o·o.,u-. m w vsc USO AA 0017 2!.!3117 Arma Dumbactl 161 30 USO USD M,34!,,!l�.01 US'O USO AA - • Figure 195: Testing the Application The generated application is tested in SAP WebIDE by running the project in flpSandbox. UI-Specific Annotations @Abap(atalog .. sqlViewName: 'S4D430_0DFIORI' Set a Caption for the List Display @OData.publish: true @UI.headerinfo: { typeName: 'Fl'ght Booking', typeNamePlural: 'Flight Bookings'} Enable a Search Dialog @Search.searchable: true define view S4d430 OData Andl_Fiori as select from sboolk association[l] t,o scus tom as _customer Display this Column and Set the Position on customid ; ; _;customer, id { @UI.lineitem: { position: 10, importance: #HIGH} @UI. selectionField. position: 30 key carl"id, l Display this field in the selection dialog 1 } Figure 196: UI-Specific Annotations UI-specific annotations in the CDS View influence the way the UI is generated. Here are a few examples: 262 ● Annotation @UI.headerInfo: specifies a Caption for the list display. ● Annotation @Search.searchable: true enables a search dialog. © Copyright. All rights reserved. Lesson: Understanding the Consumption of CDS Views in SAP Fiori ● ● Annotation @UI.lineItem: makes this field a column in the list display. The number after addition position sets the position of the column. Annotation @UI.selectionField: adds a corresponding UI element to the selection dialog. Selection via airline {3rd selection field} Search Function Switched on Standerd G c,iy OounDy Ain,ne Sea't'll MapiF,ltff:S Flight Bookings (100,110) Sland�rd' F1win10;,ie a Header 9 Payrne Al�.r)e Coone Bool\lng aumber CU$tolner""me AA 0017 212-JJH 00000001 JCIMnn Butliltr 719.00 USD U&O AA 0017 212'Si'17 00000002 Cllm«lpn Ryan 761 JO USO USO M 0017 2.r23J17 00000003 Cllns ne O"Oul� 76130 USD USO AA 0017 �17 ll0000004 Anna Oumb;!Cih 761 30 USO USO u.u · �39.ot u so use i:«e • Column Airline is visible in the list display Figure 197: UI-Specific Annotations – The Outcome The figure illustrates the outcome of these UI-specific annotations. LESSON SUMMARY You should now be able to: ● Understand the Consumption of CDS Views in SAP Fiori © Copyright. All rights reserved. 263 Unit 6 Lesson 5 Understanding Analytics Based on CDS Views LESSON OBJECTIVES After completing this lesson, you will be able to: ● Understand Analytics with CDS Views The Query Browser A Design Studio app as Fiori content No installation Ad-Hoc Reporting Figure 198: Query Browser Overview The Query Browser is a default Design Studio that is available in the standard Fiori content. No additional installation is required as this application is shipped with the standard Fiori content. The Query Browser allows the end user ad-hoc reporting based on CDS Query views. 264 © Copyright. All rights reserved. Lesson: Understanding Analytics Based on CDS Views Figure 199: Launch Query Browser from Fiori Launchpad The Query Browser is a Fiori application. To be able to start it, you first need to start the Fiori Launchpad. The Fiori Launchpad can be started using a browser. . ' a. V,ew Detal �v ZOO_ANALYTICS_QUERY Name of the CDS View OOmoMa�'\JCS-� �1,:w,Cor1lfl(>fle,,1 � Display the Annotations from rhe CDS View Dt><J1>1J011 Anl!o<oli>n i)tli'I"""' CQl,Jmn�me 031> ... .....,[ COIUmnOt� C<>kimn Do� Trpo CARRIO S_CAAA_10 AiNnt� C>!AA co s_com,1_10 ng•i�""""'�' ........ c fLOI\TE S_OAT!:: flGli!GOI! DAIS 900><JD S_BOOK_ID Boo'*1goomboer Nl.ll�C CUSlO,,I D s_cUSTOMEFI customer Number NUMC IW,IE S_CIJSTH.•,ME Cu��rl'\ilme CWIR ClrY CITY Cc CHAA C-()UNTF;iV S_OOUmRY C<Hmlt\' Code O!AA Cl.ASS S_Cl.l\SS flglltClas. CHAA s_c� �)'f!l<flCamenq ID PRlct: CURR eounn u:ngm l5 � 15 CUFIFI OAl'S_AHEAD CUl(Y ,,ir, ,o * M<I laQ< fDC1' II �n SIIJl!II) Figure 200: View Details and Launch Query with Design Studio The View Details are displayed. The header shows the name, application component, tags, and the description. The Definition tab shows the technical details like Column Name, Data Element, Description, Data Type, and Length of all columns. On the Annotation tab, you will see additional details on access control, VDM view type, Analytical query, End user label, and the ABAP catalog view name. The CDS in-front of the ABAP catalog view name means it is a CDS view. To open this query in the Design Studio, click Open in Design Studio. © Copyright. All rights reserved. 265 Unit 6: Consumption of CDS Views (Outlook) Q Demo: Analytics - Info Sourcev Standard 0 snow !'11ter ear « 0.. F COLUMNS DIMENSIONS er, .1,lll:im Measure� Im O ... • AZ � �tCE ., AlrHne soo1u1111numtJef Cily Class C,,,noe�n Numbe1 a.stomf-t i.;l'nlii4!r ROWS Custorne-rna.me Alrl,ne -�1 .Al�•n• • FIFtlCE ,• AA ;.>7'"1.13 S 159.872 6-14 a.3 FllgMD3te AZ. PaymemcYrrency OL S67!>73'131,12 JL 1..H S 2'l9 $&<; 55S.!i-2' S 57.325076.dl OF S !2.7M 579,M so S 3W.l95.206,65 VA S l$46'1iff1,d0 export lo Excel li:ilS&MEIMd Figure 201: Ad-hoc Analysis Design Studio Template The resulting screen shows the selected data in a table and pie chart. The look and feel of this result page can be customized. The query can also be saved as a Fiori tile by clicking the Actions button on the bottom right and then select Save as Tile. In the Save as Tile pop-up, you can specify the Title and Subtitle to be displayed in the Fiori Launchpad. ' My ome Home Analysis Path Framework odeling KPI Design Query Design Revenwe By Airline Figure 202: Result - A New Tile in the Launch Pad The Design Studio Tile is saved under the My Homegroup for easy access. 266 © Copyright. All rights reserved. Lesson: Understanding Analytics Based on CDS Views Analytics-related Annotations @AbapCatalog .. sqlViewNlame: '54D430_ANIAQUERY' Prerequisite for Query Browser true l@Analytic:s.query; @VDM.viewType: #CONSUMPTION @OData.publish: true define view S4D430_.Analytics_Query as select from S4D430_An.alytics_Source { @AnalyticsDetails. query. axrs : #ROWS key carridJ key c;:onnidJ Preselect this field as ROW Filter on this field allows a range @Consumption. filter: { selection Type: #RANGE) multipleSelections; false, mandatory: false } key fldateJ Preselect this field as COLUMN (Measure) @AnalyticsDetails.query.ax.is: #COLUMNS pr i ce, currency Figure 203: Analytics-Specific Annotations Analytics-specific annotations in the CDS View influence the way the Ad-hoc is generated. Here are a few examples: ● Annotation @Analytics.query: true defines this view as a query ● Annotation @AnalyticsDetails.query.axis: preselects a field as row or column ● Annotation @Consumption.filter: allows/restricts filter settings on this field Annotation @Analytics .. query: true Annotation @VDM.viewType: #CONSUMPTION • Annotation @OData.publish: true The CDS View reads from a CDS View with Annotation @Analytics.dataCategory with value #FACT or #CUBE • J Figure 204: Prerequisites for CDS Views in Query Designer CDS Views need to fulfill some basic requirements in order to be available in the Query Browser. © Copyright. All rights reserved. 267 Unit 6: Consumption of CDS Views (Outlook) LESSON SUMMARY You should now be able to: ● 268 Understand Analytics with CDS Views © Copyright. All rights reserved. Unit 6 Lesson 6 Understanding Virtual Data Models with CDS Views LESSON OBJECTIVES After completing this lesson, you will be able to: ● Understand Virtual Data Models (VDM) Data Modeling with CDS Views r-------------------------------------------------------� i Uls - iiiiH·A ! L------------------------------------------------------� Transactional system, e.g. SAP S/4 HANA---------� I /------------------------------------------------------, +w 1 I ! Virtual Data Model I F•M : \ I ! MW@& I lr-------------------------------------------------------, +IA +Bil F&ii ,, J '- I : I Database Layer, e.g. SAP HANA : L------------------------------------------------------� Figure 205: Virtual Data Models SAP's focus is to create a Virtual Data Model (VDM) using Core Data Services (CDS views) to support (and replace all other standard ABAP-related standard) operational reporting in the context of SAP S/4HANA. SAP's Virtual Data Model has the following use cases: ● ● Any analytical content (e.g., queries, cubes exposed via generic analytical tools like Lumira, Design Studio) New transactional or analytical FIORI applications (following the SAP S/4HANA target architecture) ● Smart Business KPIs ● Fact sheets and object pages © Copyright. All rights reserved. 269 Unit 6: Consumption of CDS Views (Outlook) • Consumption views Sear en Data relii!W3l for transaclional appllealions Appllealionqiecllic \llewi; (B<OOSS� Vi:ews from various consumption domains (e.g. Anallytics, Search or ... } which consume interface views and create queni:es on top to consume interface vi·ews 'il'leiOCt.s obl,!J111°"'1 !Interface views Composite views Basic views Database tables E�ose �he public and stable VDM interface for consumers. Provide business semantics as a easii1ly consumable and reusable data model. Doman-specllic views {e.g. Ar1alyt11cs, Search or ... ) Instance Authorizations via DCls Executed via ABAP SQl Interface Suite database model .as it i1s" Figure 206: The Layers in the Virtual Data Model (VDM) The key principle of the Virtual Data Model (VDM) is to build a semantic layer on top of the existing Suite database model hiding its technical details. The above figure shows a high-level view of the VDM. Technically, all views in the VDM are defined as ABAP Core Data Services (CDS) views. The most important component in the VDM is the Interface view layer. It consists of a consistent model of reusable entity views which focus on business semantics. Interface views are subdivided into two view types: Basic interface views and the Composite interface views. In the top layer, the Consumption views are defined. Consumption views are created on top of Interface views, and they address specific application requirements. Different consumption domains (for example Analytics, Search, OData and Fiori) use interface views to consume data, or create queries to consume the data exposed by the Interface views. An important consequence of the above layered architecture of the VDM view model is that consumer views must not by-pass the Interface layer of the VDM by accessing database tables directly. For example, reports based on analytical queries (which are modeled as CDS consumption views) will select data from interface views (for instance, from composite views with the analytical data category #CUBE) and not from data base tables. 270 © Copyright. All rights reserved. Lesson: Understanding Virtual Data Models with CDS Views Consumpt on YililWi lnlerface views Composite views are built selecting from the Co�osffe vl&ws @VDM.'lliewType set to#COMPOSITE @Atial)itics.DataCategory 'ioith velue #CUBE, basic views and: exploring the associations between basic views. They can be specific to a consumption domain or reusable in many. #DIME:NSIONS, #FACT, #TEXT or #HIERARCHY @VDM-busine�Objoct (to be decided) Basic Vl&ws IC are Entitles I Te Kt Views I Hierarchy Viewsl Dirtingu.,hed b� @VDM.viewT'l'J)e set to #BASIC @Anel:,tics.DataC�tegory with value #CU81,. #DIMENSIONS. #FACT. #Tl,XT or Basic views form the low-redundancy model on top of the Suite database tables. Core entity views contain the associations to other core entity views. #HIERARCHY @VDM.b4.Jslr!e'osObJect (to be de(lde-d) \ ( } Database tables ) Figure 207: Interface Views Divided into Basic and Composite Views Basic Views are further categorized into Core Entity views, Text views, and Hierarchy views. Core Entity Views Carry the business semantics, along with all data that semantically belongs to the Core Entity. Independent from clients, Core Entity views contain the keys that represent the core entity. Core Entity views also contain the associations to all other business objects ('external relationships') and to the other directly related BO nodes if existing ('internal BO structure'). The Core Entity views are often used for Master data like SalesOrderHeader, SalesOrderItem, CostCenter, ControllingArea. Text Views Contain language-dependent texts for a specific business entity. Hierarchy Views Contain hierarchy nodes (incl. parent/child assignments) for a specific business entity. © Copyright. All rights reserved. 271 Unit 6: Consumption of CDS Views (Outlook) Data Model-Related Annotations @VD'M. view Type • Admissible Values: #BASIC. #COMPOS/TE, #CONSUMPTION. #EXTENSION • In VDM, all cos views shall be annotated ex-plicilly with a VDM view type • @VDM.prlvate • Admissible Values: #blank (=true), true or false • Only private vievvs need to be annotated explicitly • @ObjectModel.dataCategory • Admissible Values: #TEXT, #HIERARCHY • @Analytlcs.dataCategory • Admissible Values: #FACT, #CUBE, #DIMENSION ] Figure 208: Data Model-Related Annotations Dedicated annotations allow to document the layering of the VDM right in the DDL sources. They also support the classification of CDS views as “private” with the consequence that they will not be visible for certain consumers. LESSON SUMMARY You should now be able to: ● 272 Understand Virtual Data Models (VDM) © Copyright. All rights reserved.