S4D430 Building Views in Core Data Services ABAP (CDS ABAP) . . PARTICIPANT HANDBOOK INSTRUCTOR-LED TRAINING . Course Version: 20 Course Duration: 3 Day(s) e-book Duration: 18 Hours 50 Minutes Material Number: 50151959 SAP Copyrights, Trademarks and Disclaimers © 2019 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. This course may have been machine translated and may contain grammatical errors or inaccuracies. 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 Procedure Warning or Caution Hint Related or Additional Information Facilitated Discussion User interface control Example text Window title Example text © Copyright. All rights reserved. iv Contents vi Course Overview 1 Unit 1: Introduction 2 14 Lesson: Motivating CDS Views and Understanding the Background Lesson: Working with ABAP Development Tools (ADT) 19 Lesson: Analyzing and Using A CDS View 30 Unit 2: 31 38 Lesson: Defining a Simple CDS View Lesson: Creating a CDS View with Inner Join, Projection, and Selection Lesson: Using ABAP Annotations in CDS Views 42 49 Unit 3: 50 57 65 67 71 83 Unit 4: Advanced Concepts Lesson: Defining CDS Views with Input Parameters Lesson: Building CDS Views with Associations Lesson: Enhancing a CDS View Lesson: Linking a CDS View with Authorization Rules Unit 5: 133 143 More SQL Features in CDS Views Lesson: Using SQL Expressions in CDS Views Lesson: Using Built-in SQL Functions in CDS Views Lesson: Understanding Nested Views Lesson: Using Aggregations in CDS Views Lesson: Using Additional Join Types and UNION (ALL) 84 95 110 121 132 Basic SQL Features in CDS Views Database-Specific Features of ABAP CDS Lesson: Understanding CDS Table Functions Unit 6: 144 151 155 162 166 171 © Copyright. All rights reserved. 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 v Course Overview TARGET AUDIENCE This course is intended for the following audiences: © Copyright. All rights reserved. vi UNIT 1 Introduction Lesson 1 Motivating CDS Views and Understanding the Background 2 Lesson 2 Working with ABAP Development Tools (ADT) 14 Lesson 3 Analyzing and Using A CDS View 19 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. 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) © Copyright. All rights reserved. 2 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 Figure 2: ABAP's Classical Approach to SQL In principle, only the DML part of SQL is available to an ABAP program at runtime. the SQL variant that is built into the ABAP language, only covers DML aspects. Open SQL, 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 The fact that Open SQL only covers the DML part of SQL is not its only restriction. 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 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 one of the most commonly missed features by application programmers. 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 of this is 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. © Copyright. All rights reserved. 4 Lesson: Motivating CDS Views and Understanding the Background Figure 5: ABAP Dictionary Views Figure 6: Limitations of ABAP Dictionary Views Again, the main reasons for these limitations was to keep the load away from the database, and to ensure that a query would return the same results on any databases. 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 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. Figure 8: Paradigm Changes in Application Programming The basic approach of classic ABAP programming was: 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. 6 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 called, rather than "data to logic". 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, Transformation of Application Design ) 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 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 considering the need for enriching pure technical definitions with semantics. And that's one of the main reasons for SAP's Core Data Services. 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. © Copyright. All rights reserved. 8 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 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 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 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. © Copyright. All rights reserved. 10 Lesson: Motivating CDS Views and Understanding the Background 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 in selections Aggregation and grouping in the data model Nested views (View-on-View) 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 full use of features that 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. CDS-related Repository Objects 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 Also referred to as DCL Source (for Data Control Language, named after the DCL part of SQL) © Copyright. All rights reserved. 12 Lesson: Motivating CDS Views and Understanding the Background Contains the definition of authorization rules that are automatically checked when a program accesses a certain CDS View or CDS table function Metadata Extension (DDLX Source) New repository object in Rel. 7.51 Contains additional or alternative semantic information for a CDS View 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 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. © Copyright. All rights reserved. 14 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 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 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 Figure 20: Editing Repository Objects © Copyright. All rights reserved. 16 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 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 or Integrated SAP GUI Editors, you can see an example of each of the following types: 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, such as 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 Figure 22: Further Information If you are looking for a local installation of ADT, you can choose from the following sources: 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. LESSON SUMMARY You should now be able to: Work with ABAP Development Tools © Copyright. All rights reserved. 18 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 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. 19 Unit 1: Introduction 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. 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. © Copyright. All rights reserved. 20 Lesson: Analyzing and Using A CDS View Annotations 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 a 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. 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. 21 Unit 1: Introduction CDS-Related Tools in ADT 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. Display SQL Create Statement Figure 28: 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. 22 Lesson: Analyzing and Using A CDS View Active Annotations View Figure 29: 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. © Copyright. All rights reserved. 23 Unit 1: Introduction Figure 30: 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 Figure 31: 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. 24 Lesson: Analyzing and Using A CDS View 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 Figure 32: 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. © Copyright. All rights reserved. 25 Unit 1: Introduction Data Preview Figure 33: 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. Figure 34: 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 you can increase or decrease this value manually (setting Max.Rows). © Copyright. All rights reserved. 26 Lesson: Analyzing and Using A CDS View 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 Figure 35: New Open SQL Syntax in NW 7.40 As of 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: If an SQL statement uses the new syntax, it has to use it consistently. 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. 27 Unit 1: Introduction Note: CDS Views were introduced in NW 7.40 SP05. The new syntax is mandatory when using a CDS View in a SELECT statement. Figure 36: 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 importantly, 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. 28 Lesson: Analyzing and Using A CDS View One DDL Source – Two Objects to Read from Figure 37: 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. LESSON SUMMARY You should now be able to: Read a Data Definition Use CDS-related Tools in ADT Use Open SQL to Read From a CDS View © Copyright. All rights reserved. 29 UNIT 2 Basic SQL Features in CDS Views Lesson 1 Defining a Simple CDS View 31 Lesson 2 Creating a CDS View with Inner Join, Projection, and Selection 38 Lesson 3 Using ABAP Annotations in CDS Views 42 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. 30 Unit 2 Lesson 1 Defining 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 Figure 38: 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 © Copyright. All rights reserved. ABAP Repository Object … 31 Unit 2: Basic SQL Features in CDS Views Figure 39: Create New DDL Source (2) 3. From the list, choose Core Data Services Data Definitions . 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. 32 Lesson: Defining a Simple CDS View Figure 40: 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 favorite package. Data Definitions of the 2. Right-click Data Definitions and choose New Data Definition . DDL Source Templates Figure 41: 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. © Copyright. All rights reserved. 33 Unit 2: Basic SQL Features in CDS Views 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. Figure 42: DDL Source Templates During Editing To choose a template later, go to the Templates tab in the tabstrip below the editor window. 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. 34 Lesson: Defining a Simple CDS View Syntax Rules Figure 43: General DDL Syntax Rules The general syntax rules inside DDL Sources are as follows: Allowed Characters Only ASCII-characters are allowed in data definitions. Keywords Keywords must be all uppercase, all lowercase, or in lowercase with an uppercase initial letter. Mixed uppercase and lowercase is not allowed. 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. © Copyright. All rights reserved. 35 Unit 2: Basic SQL Features in CDS Views Figure 44: 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 specific to CDS Syntax and allows for improved auto-completion support. It is recommended that you use the 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. 36 Lesson: Defining a Simple CDS View Figure 45: Naming Rules and Recommendations LESSON SUMMARY You should now be able to: Create a DDL Source Understand the DDL Syntax Rules © Copyright. All rights reserved. 37 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 Figure 46: Inner Join in DDL View Definition © Copyright. All rights reserved. 38 Lesson: Creating a CDS View with Inner Join, Projection, and Selection Aliases for Tables and Fields Figure 47: 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 an association. © Copyright. All rights reserved. 39 Unit 2: Basic SQL Features in CDS Views Key Definition Figure 48: 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: 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. 40 Lesson: Creating a CDS View with Inner Join, Projection, and Selection Selections Figure 49: 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. LESSON SUMMARY You should now be able to: Define a CDS View That Reflects a Database View © Copyright. All rights reserved. 41 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 Figure 50: 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. Framework-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 activations and the ABAP runtime environment. Here, the names and values of these © Copyright. All rights reserved. 42 Lesson: Using ABAP Annotations in CDS Views 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. Figure 51: 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 ClientHandling.type Defines the client dependency of the view. The default value is #INHERITED which specifies that the view is client-specific if at least one of its data sources is client-specific. ClientHandling.algorithm Determines further how implicit client handling is performed when accessing the clientspecific view through Open SQL. © Copyright. All rights reserved. 43 Unit 2: Basic SQL Features in CDS Views AccessControl.authorizationCheck Defines the implicit access control when Open SQL is used to access the CDS view. 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 Figure 52: 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. It is recommended to use annotation @Semantics.amount.currencyCode to link every amount field to a currency code field and annotation @Semantics.quantity.unitOfMeasure to link every quantity field to a unit field. Otherwise, a user of the CDS entity will have difficulties correctly interpreting and processing the values provided in these fields. Hint: Compare this to the Currency/Quantity Fields tab that is available when editing transparent tables or structure types in the ABAP Dictionary tool. Annotations @Semantics.currencyCode and @Semantics.unitOfMeasure are optional for fields based on ABAP Dictionary types CUKY and UNIT. © Copyright. All rights reserved. 44 Lesson: Using ABAP Annotations in CDS Views Syntax Variants for Annotations Figure 53: Element Annotations after Element Instead of specifying an element annotation before the respective element it can be placed after the element. In this case, the annotation has to be introduced with "@<" instead of "@". Keep in mind that the annotation has to be inserted before the comma that separates the element from the next element Figure 54: Grouping of Annotations Annotations from the same annotation category can be grouped to make it visible that they belong together. In the example, there are four annotations from category ABAPCatalog. Three of them belong to sub-category ABAPCatalog.buffering. In the lower code example, you find a group starting with @ABAPCatalog: followed by a pair of curly brackets. Within the © Copyright. All rights reserved. 45 Unit 2: Basic SQL Features in CDS Views brackets there is a comma-separated list of annotations, without the first part (ABAPCatalog). The second entry in this list is a sub-group that starts with buffering: and which has three annotations in its comma-separated list. Figure 55: Preferences for Inserting Annotations Tip: If you prefer this syntax, you can set it as the default when inserting annotations by autocompletion. In the ADT menu, go to Window Preferences. Go to ABAP Development Editors Source Code Editors CDS Code Completion and under Insertion of CDS Annotations , choose Structured (multiple lines with all brackets). ABAP Annotations for Translatable Texts Figure 56: ABAP Annotations for Translatable Texts ABAP annotations starting with EndUserText are used to define translatable semantic texts for a CDS object. © Copyright. All rights reserved. 46 Lesson: Using ABAP Annotations in CDS Views 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 an arbitrary length. Translation of Annotations Figure 57: Translation of 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 the 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. © Copyright. All rights reserved. 47 Unit 2: Basic SQL Features in CDS Views Dynamic Access to Annotation Texts Figure 58: 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. Note: If no text is found for the language, the secondary language in AS ABAP is used. LESSON SUMMARY You should now be able to: Use ABAP Annotations in CDS Views Work with Translatable Texts in CDS © Copyright. All rights reserved. 48 UNIT 3 More SQL Features in CDS Views Lesson 1 Using SQL Expressions in CDS Views 50 Lesson 2 Using Built-in SQL Functions in CDS Views 57 Lesson 3 Understanding Nested Views 65 Lesson 4 Using Aggregations in CDS Views 67 Lesson 5 Using Additional Join Types and UNION (ALL) 71 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 and Group By in CDS Views Understand Additional Join Types Understand UNION and UNION ALL © Copyright. All rights reserved. 49 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 Figure 59: 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 Series of digits without quotes May contain a decimal point, but not before the first digit © Copyright. All rights reserved. 50 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 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 Figure 60: 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 the keyword CASE and ends with the keyword 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. 51 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. Figure 61: 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, the ELSE branch is missing, syntax check will issue a warning. © Copyright. All rights reserved. 52 Lesson: Using SQL Expressions in CDS Views Figure 62: 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 kilograms or 44 pounds will be classified as having excess luggage. First class passengers, however, are always excluded from this classification. Figure 63: Example 3: Two Nested Case Expressions The figure Example 3: Two Nested Case Expressions 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, the result after a WHEN … THEN branch could also be a case expression. © Copyright. All rights reserved. 53 Unit 3: More SQL Features in CDS Views Arithmetic Expressions Figure 64: 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 an integer type. Numeric Literals with decimals have the type: FLTP. Figure 65: Example: Arithmetic Expressions in CDS Views The figure Example: Arithmetic Expressions in CDS Views gives some examples for arithmetic expressions in CDS Views. © Copyright. All rights reserved. 54 Lesson: Using SQL Expressions in CDS Views Type Conversions Figure 66: 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. 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. In NW 7.40, the target type could only be specified as a 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. A cast with a Dictionary data element as target type can be useful, even if the technical type of the operand and the target data element are identical. In this case, only the semantic attributes of the operand are modified. You can suppress a related syntax warning by adding the addition PRESERVING TYPE. 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. 55 Unit 3: More SQL Features in CDS Views Figure 67: Example: Type Conversions With CAST The figure Example: Type Conversions With CAST gives some examples of type conversions in CDS Views. Note that literal '19891109' and data element S_CUSTOMER have the identical technical type NUMC(8). LESSON SUMMARY You should now be able to: Use SQL Expressions in CDS Views © Copyright. All rights reserved. 56 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. Figure 68: 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. Division( ) allows you to specify the precision of the result. © Copyright. All rights reserved. 57 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. Figure 69: Numeric Functions (2) String Functions ABAP CDS offers a variety of built-in functions for string processing. Some were already available in release NW 7.40, others are new in NW 7.50. © Copyright. All rights reserved. 58 Lesson: Using Built-in SQL Functions in CDS Views Figure 70: 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. Figure 71: 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. © Copyright. All rights reserved. 59 Unit 3: More SQL Features in CDS Views Figure 72: String Processing Functions (3) Even more built-in functions for string processing were added in NW 7.51. Among them the functions for translating text to upper case and to lower case are of special interest. 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 the function concat looked like this: concat(concat(arg1,' '),arg2) Figure 73: Example: String Processing in a CDS View The figure Example: String Processing in a CDS View gives some examples of string processing in CDS Views. © Copyright. All rights reserved. 60 Lesson: Using Built-in SQL Functions 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 a value of 2 because the third character in CARRID is a trailing blank 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). Figure 74: 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. © Copyright. All rights reserved. 61 Unit 3: More SQL Features in CDS Views Figure 75: 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. 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 the input parameter target_unit and to make use of the annotation Semantics.unitOfMeasure. Figure 76: Example: Currency Conversion © Copyright. All rights reserved. 62 Lesson: Using Built-in SQL Functions in CDS Views 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 in the figure Example: Currency Conversion , the value in table field PRICE is converted into US Dollars ("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. Calculations with Dates As ABAP developers, we are used to doing calculations with data objects of type D: Subtract a date field from another date field to calculate the number of days that lie between them or add an integer value to a date field to calculate the date that lies a certain number of days in the future. This is possible because ABAP automatically translates values of type D into integer values. A similar mechanism does not exist on the database level. Here, date fields are not recognizable as date fields. Normally, they are created as ordinary character fields of length 8. Using these character fields in arithmetic expressions will lead to syntax errors and type casting with CAST will lead to wrong results. Figure 77: Calculations with Dates In order to make calculations with dates, four built-in functions are available in CDS as of NW 7.50. © Copyright. All rights reserved. 63 Unit 3: More SQL Features in CDS Views Figure 78: Example: Calculations with Dates The figure Example: Calculations with Dates gives two examples: Field days_ahead returns the number of days that lie between the order date of the booking and the actual flight date. Field due_date adds 14 days to the date found in field order_date. Input value 'FAIL' causes the function to raise an exception should an error occur. With other options, you can make the function return the NULL value, the initial value ('00000000') or the unaltered input value. LESSON SUMMARY You should now be able to: Use Built-in SQL Functions in CDS Views © Copyright. All rights reserved. 64 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” . Figure 79: 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. 65 Unit 3: More SQL Features in CDS Views Advantages and Pitfalls Figure 80: Pitfalls of Nested Views Recommendations Figure 81: Recommendations for Nested Views LESSON SUMMARY You should now be able to: Define CDS Views Based on Other CDS Views © Copyright. All rights reserved. 66 Unit 3 Lesson 4 Using Aggregations in CDS Views LESSON OBJECTIVES After completing this lesson, you will be able to: Use Aggregate Functions and Group By in CDS Views Aggregate Expressions Figure 82: 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 Aggregate Functions 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: the result type of expressions MIN, MAX, and SUM is identical to the data type of operand. © Copyright. All rights reserved. 67 Unit 3: More SQL Features in CDS Views The result type of expressions COUNT and COUNT( DISTINCT …) is type INT4. The result type of expression AVG is type FLTP - unless addition AS is used inside the expression. Usually, operand is a column or field in the data source of the current CDS View. Other options for operand are: Literals Case distinctions Figure 83: Example: Aggregate Functions The figure Example: Aggregate Functions shows examples for the various aggregate functions. The second AVG( ) expression uses addition AS to change the result type from abap.fltp to abap.dec(16,2). The last two elements of the field list are examples for alternative operands. Note that without the cast expression the result type of sum( 1 ) would be abap.int1 (the type of literal 1). This would lead to an overflow as soon as the result exceeds 255. Note: Sum expressions with operands of a small value range (int1, int2, dec, curr, quan with small value for length) are likely to cause overflow errors. Wrap it with a cast expression to provide a result type of sufficient value range. © Copyright. All rights reserved. 68 Lesson: Using Aggregations in CDS Views Figure 84: Example: Aggregate Functions with GROUP BY Addition GROUP BY groups rows in the result set that have the same content in the fields listed after GROUP BY, and returns a single row for each group. 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 Problems tab 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. Restrictions in ABAP CDS In CDS, several restrictions apply for the use of aggregate functions. © Copyright. All rights reserved. 69 Unit 3: More SQL Features in CDS Views Figure 85: Important Restrictions for Aggregate Functions in CDS LESSON SUMMARY You should now be able to: Use Aggregate Functions and Group By in CDS Views © Copyright. All rights reserved. 70 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. Figure 86: Reminder: Inner Join As a reminder, the figure Reminder: Inner Join 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. © Copyright. All rights reserved. 71 Unit 3: More SQL Features in CDS Views Figure 87: Types of Outer Joins SQL standard knows three (sub)types of outer joins. Figure 88: 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. 72 Lesson: Using Additional Join Types and UNION (ALL) Note: These NULL values are set to a type-friendly initial value when the CDS view is used in Open SQL. Figure 89: Right Outer Join In a right outer join the role of left and right table are exchanged: Rows of the right table without a 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. © Copyright. All rights reserved. 73 Unit 3: More SQL Features in CDS Views Figure 90: 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 a matching row in the other table are copied to the query result. The missing values (from the other table) are filled with NULL values. 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. Figure 91: Example: Right Outer Join © Copyright. All rights reserved. 74 Lesson: Using Additional Join Types and UNION (ALL) 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 Figure 92: 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 sources: 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. © Copyright. All rights reserved. 75 Unit 3: More SQL Features in CDS Views Figure 93: Example: Cross Join Figure 94: 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 Figure 95: Nested Join Expressions – Order of Evaluation © Copyright. All rights reserved. 76 Lesson: Using Additional Join Types and UNION (ALL) 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. Figure 96: 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 that 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. © Copyright. All rights reserved. 77 Unit 3: More SQL Features in CDS Views Figure 97: Example: Same Join with Implicit Ordering The figure Example: Same Join with Implicit Ordering 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 Figure 98: UNION If you place keyword UNION 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. 78 Lesson: Using Additional Join Types and UNION (ALL) Figure 99: 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 types are taken from the elements in the first SELECT statement. If an element in the other SELECT statement has a compatible but longer type than the element in the first statement, for example char(20) instead of char(10), its content will be truncated. Caution: When implementing a UNION in CDS ABAP, make sure the data types of the elements in the element list of the first SELECT statement are long enough for the corresponding elements in the other SELECT statements. Otherwise information from the other statements could be truncated. © Copyright. All rights reserved. 79 Unit 3: More SQL Features in CDS Views Figure 100: Example: UNION The CDS view in this example reads travel agencies from table STRAVELAG and flight customers from table SCUSTOM. The two result sets are merged into one by using keyword UNION. A field with name TYPE is filled with literal 'Agency ' or 'Customer' to make the rows from the different sources distinguishable in the result set. This field is a key field of the resulting view because it is labeled with "key" in the first select. Note: The two literals don't have to be of same length. It is not necessary that the types of corresponding elements are identical. Technically, it is sufficient that they are compatible. But if the literal in the second select was shorter than the literal in the first select, it would become truncated to the length of the first literal. © Copyright. All rights reserved. 80 Lesson: Using Additional Join Types and UNION (ALL) Difference between UNION and UNION ALL Figure 101: 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. Figure 102: 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 keyword UNION ALL is used. The second CDS view reads exactly the same data but uses UNION without addition ALL. © Copyright. All rights reserved. 81 Unit 3: More SQL Features in CDS Views 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. LESSON SUMMARY You should now be able to: Understand Additional Join Types Understand UNION and UNION ALL © Copyright. All rights reserved. 82 UNIT 4 Advanced Concepts Lesson 1 Defining CDS Views with Input Parameters 84 Lesson 2 Building CDS Views with Associations 95 Lesson 3 Enhancing a CDS View 110 Lesson 4 Linking a CDS View with Authorization Rules 121 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 Metadata Extensions Understand the Concept of CDS DCL Create a DCL Source © Copyright. All rights reserved. 83 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. Figure 103: Input Parameters in CDS Views The new possibilities immediately raise 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 their WHERE clause. Finally, SQL does not know about 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, e.g. a language key or a user name. © Copyright. All rights reserved. 84 Lesson: Defining CDS Views with Input Parameters Figure 104: 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. Like annotations in the element list, annotations in the parameter list can be specified before the parameter or after the parameter. Template Define View With Parameters Figure 105: Template Define View With Parameters © Copyright. All rights reserved. 85 Unit 4: Advanced Concepts There is a dedicated template for creating a view definition with input parameter. Access to Input Parameters Figure 106: 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. Figure 107: 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. 86 Lesson: Defining CDS Views with Input Parameters Right side of a condition in an ON condition in a join. Input Parameters in Data Preview Figure 108: 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. Note: It is currently not possible to define optional input parameters for CDS views. Only entries that are compatible with the parameter type are accepted. 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. © Copyright. All rights reserved. 87 Unit 4: Advanced Concepts Input Parameters in CDS DDL Figure 109: 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 parentheses immediately after the name of the source view in the FROM clause (see the example in figure, Example: Use Input Parameters in CDS DDL). 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. 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 values for input parameters: Literal (text or number) An input parameter of your own CDS View ("forwarding" of a parameter) A session variable © Copyright. All rights reserved. 88 Lesson: Defining CDS Views with Input Parameters Input Parameters in Open SQL Figure 110: 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: Literals Host variables (of elementary type) Host expressions (with elementary result type) © Copyright. All rights reserved. 89 Unit 4: Advanced Concepts Figure 111: 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 in the figure, Restricted support in Release 7.40 ). 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. In Releases 7.50 and 7.51, querying this property results in a warning check from the syntax check. In Release 7.52, constant views_with_parameters was removed from class CL_ABAP_DBFEATURES. As a consequence, querying this property results to a syntax error from the syntax check. © Copyright. All rights reserved. 90 Lesson: Defining CDS Views with Input Parameters Default Value for Parameters in Open SQL Figure 112: Optional Parameters for CDS Views 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 the 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 in the figure, Optional Parameters for CDS Views , the system automatically supplies the parameter with the content of the related system field. © Copyright. All rights reserved. 91 Unit 4: Advanced Concepts Figure 113: 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. © Copyright. All rights reserved. 92 Lesson: Defining CDS Views with Input Parameters Session Variables Figure 114: Session Variables Another way to access ABAP environment information is by using Session Variables in CDS ABAP. Each of the four possible variables is related to a system field of the ABAP runtime. From a technical perspective, session variables indicate global variables of the current database that are set to their value when the CDS view is used in ABAP SQL. If ABAP SQL is not used to access a CDS view with session variables, the content of the variables is undefined. In general, it is preferable to use input parameters annotated with environment.systemField to access ABAP system fields, because of the improved flexibility: The calling code can provide values for these parameters when using the view outside of ABAP Open SQL, and ABAP coding can specify values that differ from the ABAP system field values. © Copyright. All rights reserved. 93 Unit 4: Advanced Concepts Figure 115: Example for Using Session Variables in ABAP CDS In the example, session variable $session.system_language is used to restrict the join to a text table: Instead of reading the currency code description in all possible languages, only the one text is read from field LTEXT that belongs to the user's logon language. LESSON SUMMARY You should now 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 © Copyright. All rights reserved. 94 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 Associations Principle 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. Figure 116: What Are Associations? Although associations and joins look different, there is no difference on the database level. Eventually, any association is translated into an ordinary join. But in the case of exposed © Copyright. All rights reserved. 95 Unit 4: Advanced Concepts associations, it depends on the way a view is consumed. 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” . Figure 117: 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 a 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). © Copyright. All rights reserved. 96 Lesson: Building CDS Views with Associations Syntax of Associations Figure 118: Technical Realization of Associations The SQL Create Statement of a CDS view definition visualizes its technical realization. The SQL Create Statement for view definition above reveals that on the database level, it is nothing more than a join definition. Figure 119: 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: © Copyright. All rights reserved. 97 Unit 4: Advanced Concepts 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 of associations begin with character "_". This corresponds to the naming rules for associations in OData. A meaningful name for the association further improves the readability of the view definition. Specifying a cardinality after keyword ASSOCIATION is optional. If the cardinality is not explicitly defined, the cardinality "0..1" is implicitly used. Note: The cardinality is used mainly to document the semantics of the data model. The cardinality is not validated at runtime but can produce syntax check warnings. Figure 120: Technical Realization of Associations The SQL Create Statement of a CDS view definition visualizes its technical realization. The SQL Create Statement for the view definition in the figure, Technical Realization of Associations reveals that on the database level, it is nothing more than a join definition. © Copyright. All rights reserved. 98 Lesson: Building CDS Views with Associations Figure 121: On-Condition with $Projection In the ON-condition of an association, it is possible to refer to an element of the element list instead of a field of the data source. To do so, the field name has to be prefixed with $projection instead of the data source or its alias name. If addition AS is used to define an alternative element name, this alternative element name has to be used instead of the original field name. In the example, alternative name carrierID is defined for field carrid of table SCARR. In the ONcondition of the association, this field is referred to as $projection.carrierID . Associations and Cardinality Figure 122: Some Rules Regarding Cardinality The list 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: © Copyright. All rights reserved. 99 Unit 4: Advanced Concepts Syntax error “Value-set associations are not allowed here” is issued if the association is used in a WHERE condition. Syntax warning “Association <…> can influence the cardinality of the resulting set” issued if the association is used in the element list. is Figure 123: 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 association is called an ad-hoc association. The benefit of associations becomes clearer when looking at exposed associations. Figure 124: Example: Exposed Association © Copyright. All rights reserved. 100 Lesson: Building CDS Views with Associations 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. 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 previous example, field c.carrid is required for exposing association _carrier. Fields c.carrid and c.connid are required for exposing association _flights. Figure 125: 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 previous example 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 this 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 an 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. © Copyright. All rights reserved. 101 Unit 4: Advanced Concepts Template Define View With Association Figure 126: Template Define View with Association There is a dedicated template for creating a view definition that contains an association to a second data source. Exposed Associations in Data Preview Figure 127: Exposed Associations in Data Preview © Copyright. All rights reserved. 102 Lesson: Building CDS Views with Associations If a CDS View definition contains exposed associations, you can evaluate these associations in Data Preview as follows: 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 Exposed Associations in Data Preview). Hint: Alternatively, you can right-click the entry and choose Follow Association . 3. Choose an association from the list of available associations. Path Expressions in CDS DDL Figure 128: 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. © Copyright. All rights reserved. 103 Unit 4: Advanced Concepts 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. Figure 129: 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. © Copyright. All rights reserved. 104 Lesson: Building CDS Views with Associations Path Expressions in Open SQL Figure 130: 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: Prefix "\" is needed for association names Component selector is "-" (in CDS DDL it is ".") Syntax of Filtered Associations Figure 131: Filtered Associations – The Principle Path expressions in CDS DDL can be extended using a filter condition. © Copyright. All rights reserved. 105 Unit 4: Advanced Concepts The filter condition becomes part of the ON - condition, when the system translates the path expression into a join on the database level. Note: Filter conditions are currently not supported in Open SQL path expressions. Figure 132: Example: Filter Condition in Path Expression In this example, table SCARR (master data for airlines) has an association to table TCURT. Table TCURT is a 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. © Copyright. All rights reserved. 106 Lesson: Building CDS Views with Associations Figure 133: 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. Cardinality in Filtered Associations Figure 134: 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. © Copyright. All rights reserved. 107 Unit 4: Advanced Concepts 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. Annotation compareFilter Figure 135: 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 the example in the figure Annotation AbapCatalog.compiler.compareFilter 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. Note: The results sets of both configurations can differ. © Copyright. All rights reserved. 108 Lesson: Building CDS Views with Associations Figure 136: Example with compareFilter: False In this example, the filter conditions in the two path expressions are identical. Annotation ABAPCatalog.compiler.compareFilter is listed with a value of false. This makes the system generate two separate joins of SCARR and TCURT to retrieve fields KTEXT and LTEXT. With a value of 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 a value of true. 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. 109 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 Understand Metadata Extensions Reminder - Append View Figure 137: 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. © Copyright. All rights reserved. 110 Lesson: Enhancing a CDS View Figure 138: 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 Figure 139: 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. 111 Unit 4: Advanced Concepts Figure 140: 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. Note: The name of the SQL view cannot be specified here. © Copyright. All rights reserved. 112 Lesson: Enhancing a CDS View Figure 141: 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. 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. 113 Unit 4: Advanced Concepts Figure 142: 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. © Copyright. All rights reserved. 114 Lesson: Enhancing a CDS View Figure 143: 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 keyword 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. 115 Unit 4: Advanced Concepts Template Extend View Figure 144: Template Extend View 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 Figure 145: 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. © Copyright. All rights reserved. 116 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. 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 Figure 146: 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 square 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. 117 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. This option can only be specified together with #PROJECTION_LIST. #UNION Extensions of the SELECT list of a CDS view with a UNION clause are allowed. This option 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 Figure 147: 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. © Copyright. All rights reserved. 118 Lesson: Enhancing a CDS View Metadata Extensions Figure 148: Example: CDS View and Metadata Extension In this example, CDS View S4d430_Metadata_Ext Target defines an element of name col_5 with a label 'No Extension'. The CDS metadata extension replaces this label with a label 'Layer CUSTOMER'. The link between the two repository objects is established through the CDS view name after keyword VIEW. To define metadata extensions for a given view it is a pre-requisite that the data definition of the CDS view contains annotation @Metadata.allowExtensions with value true . Within the metadata extension, annotation @Metadata.layer is mandatory. © Copyright. All rights reserved. 119 Unit 4: Advanced Concepts Figure 149: Metadata Extension Layers Annotation @Metadata.layer defines the priority of the metadata extension when there is more than one metadata extension pointing at the same CDS View. The #CUSTOMER layer has the highest priority. The #CORE layer has the lowest priority. LESSON SUMMARY You should now be able to: Understand the Concept of CDS View Enhancements Enhance a CDS View Understand Metadata Extensions © Copyright. All rights reserved. 120 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 Figure 150: 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. 121 Unit 4: Advanced Concepts Figure 151: 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 Figure 152: Known Problems of the Classical Approach © Copyright. All rights reserved. 122 Lesson: Linking a CDS View with Authorization Rules Figure 153: 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 only sees data for which they have display authorization, the program does a loop over 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 Figure 154: Access Control on Database – How It Works © Copyright. All rights reserved. 123 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 (keyword DEFINE ROLE …). It relates the CDS Role to one (or more) CDS Views (keyword GRANT SELECT ON …) and defines access conditions for this CDS View (keyword 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. Figure 155: Example: DLC Source The example shows the data preview for two identical CDS Views (S4d320_Acess_Cotnrol_A and S4d430_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. © Copyright. All rights reserved. 124 Lesson: Linking a CDS View with Authorization Rules Create a New DCL Source Figure 156: 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 …. Figure 157: Create New DCL Source (2) 3. From the list, choose Core Data Services © Copyright. All rights reserved. Access Control. 125 Unit 4: Advanced Concepts 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. Figure 158: Shortcut (If Package Already Contains a DCL Source) If your package already contains a DCL 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. © Copyright. All rights reserved. 126 Lesson: Linking a CDS View with Authorization Rules CDS DCL Syntax Figure 159: ABAP CDS DCL Syntax Figure 160: Naming Rules and Recommendations © Copyright. All rights reserved. 127 Unit 4: Advanced Concepts Access Conditions in DCL Sources Figure 161: 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. © Copyright. All rights reserved. 128 Lesson: Linking a CDS View with Authorization Rules Figure 162: 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. 129 Unit 4: Advanced Concepts Templates for Access Controls Figure 163: Templates for Access Controls Several templates exist for creating DCL sources. The most important are Define Role with Simple Conditions and Define Role with PFCG Aspect. Authorization-related Annotations Figure 164: Authorization-related Annotations LESSON SUMMARY You should now be able to: Understand the Concept of CDS DCL © Copyright. All rights reserved. 130 Lesson: Linking a CDS View with Authorization Rules Create a DCL Source © Copyright. All rights reserved. 131 UNIT 5 Database-Specific Features of ABAP CDS Lesson 1 Understanding CDS Table Functions 133 UNIT OBJECTIVES Understand the AMDP Framework Define CDS Table Functions Read Data From CDS Table Functions © Copyright. All rights reserved. 132 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). Figure 165: 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. © Copyright. All rights reserved. 133 Unit 5: Database-Specific Features of ABAP CDS The AMDP framework creates a stored procedure on the database and redirects (or forwards) any call of the AMDP method to this stored procedure. Figure 166: 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. 134 Lesson: Understanding CDS Table Functions Figure 167: Example: Definition of an AMDP Method This example 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. Figure 168: Prerequisites and Limitations AMDP Functions As of release 7.50, the AMDP framework supports AMDP functions alongside the existing AMDP procedures. © Copyright. All rights reserved. 135 Unit 5: Database-Specific Features of ABAP CDS Figure 169: 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. Figure 170: Example: Definition of an AMDP Function This example 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. 136 Lesson: Understanding CDS Table Functions Note: Once this functional method is implemented by a database function, you cannot call it in ABAP any more. Figure 171: 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. Calling functional methods that define AMDP functions directly in ABAP is not allowed. ABAP CDS introduced CDS table functions to make AMDP functions available as data sources of SELECT statements. © Copyright. All rights reserved. 137 Unit 5: Database-Specific Features of ABAP CDS Figure 172: The Basic Idea of CDS Table Functions This figure illustrates the basic idea of CDS table functions. A CDS table function is defined in a DDL source via keyword DEFINE TABLE FUNCTION. (Just like CDS Views are defined in DDL Sources via keyword 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. Figure 173: Example: Definition of a CDS Table Function © Copyright. All rights reserved. 138 Lesson: Understanding CDS Table Functions 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. Figure 174: 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 Define Table Function With Parameters Figure 175: Template Define Table Function with Parameters When creating a new DDL Source for a CDS Table function, you are supported by a dedicated template. © Copyright. All rights reserved. 139 Unit 5: Database-Specific Features of ABAP CDS Creating a CDS Table Function Figure 176: CDS Table Function: Recommended Sequence When developing a CDS table function, it is most important to do it in the right order. 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. 140 Lesson: Understanding CDS Table Functions CDS Table Functions in Open SQL Figure 177: 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. Figure 178: 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. © Copyright. All rights reserved. 141 Unit 5: Database-Specific Features of ABAP CDS 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. 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. 142 UNIT 6 Consumption of CDS Views (Outlook) Lesson 1 Using a CDS View as Data Source for ALV IDA 144 Lesson 2 Using CDS Views as Replacement Objects 151 Lesson 3 Generating OData Services from CDS Views 155 Lesson 4 Understanding the Consumption of CDS Views in SAP Fiori 162 Lesson 5 Understanding Analytics Based on CDS Views 166 Lesson 6 Understanding Virtual Data Models with CDS Views 171 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. 143 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) Figure 179: 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). © Copyright. All rights reserved. 144 Lesson: Using a CDS View as Data Source for ALV IDA Figure 180: Classical ALV – How It Works The figure, Classical ALV – How It Works , shows the approach to displaying data using the classical ALV. The steps shown provide an example of what the ABAP application would typically do. Figure 181: 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. 145 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. Figure 182: 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. Note: Package SALV_IDA_TEST contains sample programs using the ALV IDA. © Copyright. All rights reserved. 146 Lesson: Using a CDS View as Data Source for ALV IDA Figure 183: 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 Figure 184: 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. 147 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 comes 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 Figure 185: 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. © Copyright. All rights reserved. 148 Lesson: Using a CDS View as Data Source for ALV IDA Selections and Input Parameters Figure 186: 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 . Figure 187: Example: Providing Values for Import Parameters © Copyright. All rights reserved. 149 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: 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. 150 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 Figure 188: 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. 151 Unit 6: Consumption of CDS Views (Outlook) Figure 189: 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 Figure 190: Prerequisites and Restrictions © Copyright. All rights reserved. 152 Lesson: Using CDS Views as Replacement Objects Assigning a Replacement Object Figure 191: 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. 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. 153 Unit 6: Consumption of CDS Views (Outlook) Application Scenarios for Replacement Objects Figure 192: Important Application Scenarios for Replacement Objects LESSON SUMMARY You should now be able to: Understand Replacement Objects © Copyright. All rights reserved. 154 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. Figure 193: 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. 155 Unit 6: Consumption of CDS Views (Outlook) Key Challenges in Enterprise Computing for Business Consumers Figure 194: 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. © Copyright. All rights reserved. 156 Lesson: Generating OData Services from CDS Views The Solution: OData Figure 195: 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) 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. 157 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. Figure 196: SAP Gateway Architecture © Copyright. All rights reserved. 158 Lesson: Generating OData Services from CDS Views OData Service Development with SAP ABAP CDS Views Figure 197: 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 - 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. Second option (no mapping required) - 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. 159 Unit 6: Consumption of CDS Views (Outlook) Figure 198: 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 Figure 199: Used Code © Copyright. All rights reserved. 160 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) Figure 200: 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. 161 / 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 Figure 201: 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, they use the data.publish: true annotation to register 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. © Copyright. All rights reserved. 162 Lesson: Understanding the Consumption of CDS Views in SAP Fiori Fiori Elements Figure 202: Landing Page in SAP WebIDE After the user logged on to SAP WebIDE, they can start development by creating a new project. In order to use SAP Fiori Elements, the new project should be based on a template. Figure 203: 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. 163 Unit 6: Consumption of CDS Views (Outlook) Figure 204: Testing the Application The generated application is tested in SAP WebIDE by running the project in flpSandbox. UI-Specific Annotations Figure 205: UI-Specific Annotations UI-specific annotations in the CDS View influence the way the UI is generated. Here are a few examples: Annotation @UI.headerInfo: specifies a caption for the list display. Annotation @Search.searchable: true enables a search dialog. © Copyright. All rights reserved. 164 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. Figure 206: 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. 165 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 Figure 207: 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. © Copyright. All rights reserved. 166 Lesson: Understanding Analytics Based on CDS Views Figure 208: 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. Figure 209: 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. 167 Unit 6: Consumption of CDS Views (Outlook) Figure 210: 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 selecting Save as Tile. In the Save as Tile pop-up, you can specify the Title and Subtitle to be displayed in the Fiori Launchpad. Figure 211: Result - A New Tile in the Launch Pad The Design Studio Tile is saved under the My Homegroup for easy access. © Copyright. All rights reserved. 168 Lesson: Understanding Analytics Based on CDS Views Analytics-related Annotations Figure 212: Analytics-Specific Annotations Analytics-specific annotations in the CDS View influence the way the ad-hoc query 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 Figure 213: Prerequisites for CDS Views in Query Browser CDS Views need to fulfill some basic requirements in order to be available in the Query Browser. © Copyright. All rights reserved. 169 Unit 6: Consumption of CDS Views (Outlook) LESSON SUMMARY You should now be able to: Understand Analytics with CDS Views © Copyright. All rights reserved. 170 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 Figure 214: 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. 171 Unit 6: Consumption of CDS Views (Outlook) Figure 215: 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 database tables. © Copyright. All rights reserved. 172 Lesson: Understanding Virtual Data Models with CDS Views Figure 216: 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. 173 Unit 6: Consumption of CDS Views (Outlook) Data Model-Related Annotations Figure 217: 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: Understand Virtual Data Models (VDM) © Copyright. All rights reserved. 174