SAP HANA Developer Guide For SAP HANA Studio en
SAP HANA Developer Guide For SAP HANA Studio en
3 Getting Started. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.1 Prerequisites. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.2 SAP HANA Studio. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
The SAP HANA Development Perspective. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.3 SAP HANA XS Application Descriptors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.4 SAP HANA Projects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.5 Tutorials. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .37
Tutorial: My First SAP HANA Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Tutorial: Use the SAP HANA OData Interface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
This guide explains how to build applications using SAP HANA, including how to model data, how to write
procedures, and how to build application logic in SAP HANA Extended Application Services, classic model.
The SAP HANA Developer Guide for SAP HANA Studio explains the steps required to develop, build, and deploy
applications that run in the SAP HANA XS classic model run-time environment using the tools provided with
SAP HANA Studio. It also describes the technical structure of applications that can be deployed to the XS
classic run-time platform. The information in the guide is organized as follows:
The SAP HANA developer guides present a developer’s view of SAP HANA®.
The SAP HANA developer guides explain not only how to use the SAP HANA development tools to create
comprehensive analytical models but also how to build applications with SAP HANA 's programmatic
interfaces and integrated development environment. The information in this guide focuses on the development
of native code that runs inside SAP HANA.
Note
Access to the SAP Software Download Center is only available to SAP customers and requires logon
credentials.
Audience
Related Information
SAP HANA is an in-memory data platform that can be deployed on premise or on demand. At its core, it is an
innovative in-memory relational database management system.
SAP HANA can make full use of the capabilities of current hardware to increase application performance,
reduce cost of ownership, and enable new scenarios and applications that were not previously possible. With
SAP HANA, you can build applications that integrate the business control logic and the database layer with
unprecedented performance. As a developer, one of the key questions is how you can minimize data
movements. The more you can do directly on the data in memory next to the CPUs, the better the application
will perform. This is the key to development on the SAP HANA data platform.
SAP HANA runs on multi-core CPUs with fast communication between processor cores, and containing
terabytes of main memory. With SAP HANA, all data is available in main memory, which avoids the
performance penalty of disk I/O. Either disk or solid-state drives are still required for permanent persistency in
the event of a power failure or some other catastrophe. This does not slow down performance, however,
because the required backup operations to disk can take place asynchronously as a background task.
Columnar data storage allows highly efficient compression. If a column is sorted, often there are repeated
adjacent values. SAP HANA employs highly efficient compression methods, such as run-length encoding,
cluster coding and dictionary coding. With dictionary encoding, columns are stored as sequences of bit-coded
integers. That means that a check for equality can be executed on the integers; for example, during scans or
join operations. This is much faster than comparing, for example, string values.
Columnar storage, in many cases, eliminates the need for additional index structures. Storing data in columns
is functionally similar to having a built-in index for each column. The column scanning speed of the in-memory
column store and the compression mechanisms – especially dictionary compression – allow read operations
with very high performance. In many cases, it is not required to have additional indexes. Eliminating additional
indexes reduces complexity and eliminates the effort of defining and maintaining metadata.
With columnar data, operations on single columns, such as searching or aggregations, can be implemented as
loops over an array stored in contiguous memory locations. Such an operation has high spatial locality and can
Compressed data can be loaded into the CPU cache faster. This is because the limiting factor is the data
transport between memory and CPU cache, and so the performance gain exceeds the additional computing
time needed for decompression.
Column-based storage also allows execution of operations in parallel using multiple processor cores. In a
column store, data is already vertically partitioned. This means that operations on different columns can easily
be processed in parallel. If multiple columns need to be searched or aggregated, each of these operations can
be assigned to a different processor core. In addition, operations on one column can be parallelized by
partitioning the column into multiple sections that can be processed by different processor cores.
Traditional business applications often use materialized aggregates to increase performance. These aggregates
are computed and stored either after each write operation on the aggregated data, or at scheduled times. Read
operations read the materialized aggregates instead of computing them each time they are required.
With a scanning speed of several gigabytes per millisecond, SAP HANA makes it possible to calculate
aggregates on large amounts of data on-the-fly with high performance. This eliminates the need for
materialized aggregates in many cases, simplifying data models, and correspondingly the application logic.
Furthermore, with on-the fly aggregation, the aggregate values are always up-to-date unlike materialized
aggregates that may be updated only at scheduled times.
A running SAP HANA system consists of multiple communicating processes (services). The following shows
the main SAP HANA database services in a classical application context.
Such traditional database applications use well-defined interfaces (for example, ODBC and JDBC) to
communicate with the database management system functioning as a data source, usually over a network
connection. Often running in the context of an application server, these traditional applications use Structured
Query Language (SQL) to manage and query the data stored in the database.
The main SAP HANA database management component is known as the index server, which contains the
actual data stores and the engines for processing the data. The index server processes incoming SQL or MDX
statements in the context of authenticated sessions and transactions.
The SAP HANA database has its own scripting language named SQLScript. SQLScript embeds data-intensive
application logic into the database. Classical applications tend to offload only very limited functionality into the
database using SQL. This results in extensive copying of data from and to the database, and in programs that
slowly iterate over huge data loops and are hard to optimize and parallelize. SQLScript is based on side-effect
free functions that operate on tables using SQL queries for set processing, and is therefore parallelizable over
multiple processors.
In addition to SQLScript, SAP HANA supports a framework for the installation of specialized and optimized
functional libraries, which are tightly integrated with different data engines of the index server. Two of these
SAP HANA also supports the development of programs written in the R language.
SQL and SQLScript are implemented using a common infrastructure of built-in data engine functions that have
access to various meta definitions, such as definitions of relational tables, columns, views, and indexes, and
definitions of SQLScript procedures. This metadata is stored in one common catalog.
The database persistence layer is responsible for durability and atomicity of transactions. It ensures that the
database can be restored to the most recent committed state after a restart and that transactions are either
completely executed or completely undone.
The index server uses the preprocessor server for analyzing text data and extracting the information on which
the text search capabilities are based. The name server owns the information about the topology of SAP HANA
system. In a distributed system, the name server knows where the components are running and which data is
located on which server.
Traditional database applications use interfaces such as ODBC and JDBC with SQL to manage and query their
data. The following illustrates such applications using the common Model-View-Controller (MVC) development
architecture.
SAP HANA greatly extends the traditional database server role. SAP HANA functions as a comprehensive
platform for the development and execution of native data-intensive applications that run efficiently in SAP
HANA, taking advantage of its in-memory architecture and parallel execution capabilities.
By restructuring your application in this way, not only do you gain from the increased performance due to the
integration with the data source, you can effectively eliminate the overhead of the middle-tier between the
user-interface (the view) and the data-intensive control logic, as shown in the following figure.
These SAP HANA Extended Application Services are provided by the SAP HANA XS server, which provides
lightweight application services that are fully integrated into SAP HANA. It allows clients to access the SAP
HANA system via HTTP. Controller applications can run completely natively on SAP HANA, without the need for
an additional external application [Link] following shows the SAP HANA XS server as part of the SAP HANA
system.
In addition to exposing the data model, SAP HANA XS also hosts system services that are part of the SAP
HANA system. The search service is an example of such a system application. No data is stored in the SAP
HANA XS server itself. To read tables or views, to modify data or to execute SQLScript database procedures
and calculations, it connects to the index server (or servers, in case of a distributed system).
Note
From SPS 11, SAP HANA includes an additional run-time environment for application development: SAP
HANA extended application services (XS), advanced model. SAP HANA XS advanced model represents an
evolution of the application server architecture within SAP HANA by building upon the strengths (and
expanding the scope) of SAP HANA extended application services (XS), classic model. SAP recommends
that customers and partners who want to develop new applications use SAP HANA XS advanced model. If
you want to migrate existing XS classic applications to run in the new XS advanced run-time environment,
SAP recommends that you first check the features available with the installed version of XS advanced; if the
XS advanced features match the requirements of the XS classic application you want to migrate, then you
can start the migration process.
Related Information
The possibility to run application-specific code in SAP HANA raises the question: What kind of logic should run
where? Clearly, data-intensive and model-based calculations must be close to the data and, therefore, need to
be executed in the index server, for instance, using SQLScript or the code of the specialized functional libraries.
The presentation (view) logic runs on the client – for example, as an HTML5 application in a Web browser or on
a mobile device.
Native application-specific code, supported by SAP HANA Extended Application Services, can be used to
provide a thin layer between the clients on one side, and the views, tables and procedures in the index server on
the other side. Typical applications contain, for example, control flow logic based on request parameters,
invoke views and stored procedures in the index server, and transform the results to the response format
expected by the client.
The communication between the SAP HANA XS server and index server is optimized for high performance.
However, performance is not the only reason why the SAP HANA XS server was integrated into SAP HANA. It
also leads to simplified administration and a better development experience.
Find the information you need in the library of user and reference documentation currently available for SAP
HANA development projects.
The development environment for SAP HANA supports a wide variety of application-development scenarios.
For example, database developers need to be able to build a persistence model or design an analytic model;
professional developers want to build enterprise-ready applications; business experts with a development
background might like to build a simple server-side, line-of-business application; and application developers
need to be able to design and build a client user interface (UI) that displays the data exposed by the data model
and business logic. It is also essential to set up the development environment correctly and securely and
ensure the efficient management of the various phases of the development lifecycle.
Tip
For more information about which guides are available in the SAP HANA Platform library, use the link to the
SAP Help Portal in Related Information below. For help navigating the library, see the SAP HANA Developer
Information Map, which is available on the SAP Help Portal.
The following image provides an overview of where to find to essential information sources for anyone planning
to develop applications in SAP HANA Extended Application Services classic model.
Tip
For more information about where to find the guides and details of the individual development tasks and
scenarios that each guide describes, see Developer Information Map in Related Information below.
Related Information
Application developers can choose between the following scenarios when designing and building applications
that access an SAP HANA data model:
The following diagram shows the scope of the languages and the environment you use in the various phases of
the process of developing applications that harness the power of SAP HANA. For example, if you are developing
native SAP HANA applications you can use CDS, HDBtable, or SQLScript to create design-time representations
of objects that make up your data persistence model; you can use server-side JavaScript (XSJS) or OData
services to build the application's business logic; and you can use SAPUI5 to build client user interfaces that
are bound to the XSJS or OData services.
If you are developing non-native SAP HANA applications, you can choose between any of the languages that
can connect by means of the client interfaces that SAP HANA supports, for example, ABAP (via ADBC) or Java
(JDBC).
In SAP HANA, native applications use the technology and services provided by the integrated SAP HANA XS
platform.
The term “native application” refers to a scenario where applications are developed in the design-time
environment provided by SAP HANA extended application services (SAP HANA XS) and use the integrated
SAP HANA XS platform illustrated in the following graphic.
Note
A program that consists purely of SQLScript is also considered a native SAP HANA application.
The server-centric approach to native application development envisaged for SAP HANA assumes the following
high-level scenario:
Note
SAP recommends you use SQL rather than the Calculation Engine functions.
Database developers SQLScript, CDS, hdb* ● SAP HANA studio Database tables, views, procedures;
SAP ● SAP HANA Web- user-defined functions (UDF) and trig
based Workbench gers; analytic objects; data authoriza
tion…
Application developers: XS JavaScript, OData, ● SAP HANA studio Control-flow logic, data services, calcula
SQLScript, … ● SAP HANA Web- tion logic…
● Professional (XS JS)
● Casual/business based Workbench
UI/client developers SAPUI5, JavaScript, … ● SAP HANA studio UI shell, navigation, themes (look/feel),
● SAP HANA Web- controls, events, …
based Workbench
Related Information
The focus of the database developer is primarily on the underlying data model which the application services
expose to UI clients.
The database developer defines the data-persistence and analytic models that are used to expose data in
response to client requests via HTTP. The following table lists some of the tasks typically performed by the
database developer and indicates where to find the information that is required to perform the task.
Create tables, SQL views, sequences… Code, syntax, … SAP HANA SQLScript Reference
Create attribute, analytic, calculation Code, syntax, … SAP HANA SQLScript Reference
views
SAP HANA Developer Guide for SAP
HANA Studio
Caution
(*) For information about the capabilities available for your license and installation scenario, refer to the
Feature Scope Description for SAP HANA.
The professional application developer creates server-side applications that define the business logic required
to serve client requests, for example, for data created and exposed by the database developer. The following
table lists some of the tasks typically performed by the professional application developer and indicates where
to find the information that is required to perform the task.
Create an XSJS service: Context, examples, libraries, debug SAP HANA Developer Guide for SAP
ging, implementation, … HANA Studio (XS classic)
● Extract data from SAP HANA
● Control application response Function code, syntax… SAP HANA XS JavaScript Reference (XS
● Bind to a UI control/event classic)
Create an OData service (for example, Context, service syntax, examples, li SAP HANA Developer Guide for SAP
to bind a UI control/event to existing braries, debugging, implementation, … HANA Studio
data tables or views)
Query options, syntax… OData Reference
Developers can build client applications to display a SAP HANA data model exposed by SAP HANA XS services.
The user-interface (UI) developer designs and creates client applications which bind business logic to controls,
events, and views in the client application user interface. The UI developer can use SAPUI5 (based on HTML5)
or client-side JavaScript to build the client applications. In a UI client development scenario, a developer
performs (amongst others) the tasks listed in the following table, which also indicates where to find the
information required to perform the task.
Create an SAPUI5 application to display Context, service code/syntax, packag SAP HANA Developer Guide for SAP
SAP HANA data exposed by an XSJS/ ing, activation … HANA Studio (XS Classic)
OData service
UI controls, events… SAPUI5 Demo Kit (version 1.28)
Build the graphical user interface of an Context, tools … Developer Guide for SAP HANA Studio
SAPUI5 application using UI services (XS Classic)
(widgets)
UI controls, events… SAPUI5 Demo Kit (version 1.28)
In SAP HANA, non-native applications do use the technology and services provided by the integrated SAP
HANA XS platform; the run in an external application server.
The term “non-native application” refers to a scenario where you develop applications in an environment
outside of SAP HANA, for example, SAP NetWeaver (ABAP or Java). The non-native application logic runs in an
external application server which accesses the SAP HANA data model (for example, tables and analytic views)
by means of a standard client interface such as JDBC, ODBC, or ODBO using SQL and native SQLScript
procedures.
Technically, it is also possible for non-native front-end applications to connect to the SAP HANA database
directly via SQL or MDX, for example when SAP HANA is used as a data source for Microsoft Excel.
However, it is not recommended to use such an approach for SAP business applications.
The following figure shows how you use the client interfaces to connect your non-native SAP HANA application
to an SAP HANA data model.
Related Information
ABAP database connectivity (ADBC) provides the benefits of a native SQL connection by means of EXEC SQL.
ADBC is basically a series of CL_SQL* classes, which simplify and abstract the EXEC SQL blocks.
You can build a custom ABAP application that runs in an external application environment but connects
directly to an SAP HANA data model using the client ADBC interface. Support for external ABAP applications
includes dedicated Eclipse-based tools, external views (ABAP Dictionary objects that can be accessed like a
normal dictionary view), and ABAP managed database procedures (ABAP dictionary objects that enable you to
map procedure parameters to the ABAP parameters).
Note
It is possible to make use of native data-persistence objects in your ABAP application, for example, design-
time data-persistence objects specified using the Core Data Services (CDS) syntax.
To build an ABAP application that accesses an SAP HANA data model, you need to perform the following high-
level steps
1. Write an ABAP application in your own development environment, for example using the ABAP tools-
integration in Eclipse.
2. Connect the ABAP development environment to SAP HANA using the ADBC interface; the ABAP
environment can be either:
○ An ABAP application server
○ Your development machine
3. Run the ABAP application to connect to a SAP HANA data model.
Java Database Connectivity (JDBC) is a Java-based application programming interface (API) which includes a
set of functions that enable Java applications to access a data model in a database. The SAP HANA client
includes a dedicated JDBC interface.
You can build a custom Java application that runs in an external application environment but connects directly
to an SAP HANA data model using the client JDBC interface. To build a Java application that accesses an SAP
HANA data model, you need to perform the following high-level steps:
Related Information
Open Database Connectivity (ODBC) is a standard application programming interface (API) that provides a set
of functions that enable applications to access a data model in a database. The SAP HANA client includes a
dedicated ODBC interface.
You can build a custom .NET application (using C++, C#, Visual Basic and so on) that runs in an external
application environment but connects directly to an SAP HANA data model using the client ODBC interface. To
build an .NET application that accesses an SAP HANA data model, you need to perform the following high-level
steps:
Note
The SAP HANA data provider for Microsoft [Link] is installed as part of the SAP HANA client installation.
Related Information
OLE database for OLAP (ODBO) is a standard application programming interface (API) that enables Windows
clients to exchange data with an OLAP server. The SAP HANA client includes an ODBO driver which
applications can use to connect to the database and execute MDX statements
You can build a Windows-based client application that runs in an external application environment but
connects directly to an SAP HANA data model, for example, to run queries with multidimensional expressions
(MDX) using the native SAP HANA MDX interface. To build an MDX application that accesses a SAP HANA data
model, you need to perform the following high-level steps:
Related Information
SAP HANA includes a data provider that enables applications using Microsoft .NET to connect to the SAP
HANA database.
You can build a custom .NET application (for example, using C++, C#, or Visual Basic) that runs in an external
application environment but connects directly to an SAP HANA data model using the SAP HANA data provider
for Microsoft [Link]. The SAP HANA data provider for Microsoft [Link] is installed as part of the SAP
HANA client installation. To build a .NET application that accesses an SAP HANA data model, you need to
perform the following high-level steps:
1. Install the SAP HANA data provider for Microsoft [Link] on your development machine.
2. Write a .NET application in your development environment, for example, using Visual Studio.
3. Connect the .NET application to SAP HANA using the client interface included with the SAP HANA data
provider for Microsoft [Link].
4. Run the .NET application to connect to an SAP HANA data model.
You can use the SAP HANA data provider for Microsoft [Link] to develop Microsoft .NET applications with
Microsoft Visual Studio by including both a reference to the data provider and a line in your source code
referencing the data-provider classes.
Related Information
To understand which tools SAP HANA Extended Application Services (SAP HANA XS) provides to enable you to
start developing native applications, you need to run through the process of building a small application, for
example, in the form of a “Hello World” application.
● Prerequisites
A short list of the tools and permissions required to start working with the SAP HANA application-
development tools.
● Workspaces and projects SAP HANA projects
If you are using the SAP HANA studio, you must create a shared project, which you use to group all your
application-related artifacts and synchronize any changes with the repository workspace.
Note
If you are using the SAP HANA Web-based Development Workbench, you do not need to create a
project of a repository workspace.
Note
Access to the SAP Software Download Center is only available to SAP customers and requires logon
credentials.
Related Information
Before you start developing applications using the features and tools provided by the SAP HANA XS, bear in
mind the following prerequisites. Developers who want to build applications to run on SAP HANA XS need the
following tools, accounts, and privileges:
Note
The following can only be provided by someone who has the required authorizations in SAP HANA, for
example, an SAP HANA administrator.
● Access to a running SAP HANA development system (with SAP HANA XS)
● A valid user account in the SAP HANA database on that system
● Access to SAP HANA developer tools, for example: SAP HANA studio or the SAP HANA Web-based
Development Workbench.
Note
To provide access to the SAP HANA repository from the SAP HANA studio, the EXECUTE privilege is
required for SYS.REPOSITORY_REST, the database procedure through which the REST API is tunneled.
Note
Access to the SAP Software Download Center is only available to SAP customers and requires logon
credentials.
One of the most important features of the Eclipse-based environment is the perspective. SAP HANA provides a
number of dedicated perspectives that are aimed at the application developer. As an application developer, you
frequently use the following perspectives:
SAP HANA studio's SAP HANA Development Perspective includes a selection of programming tools that
developers can use to build applications in SAP HANA. You can customize the perspective to include your own
favorite tools, too.
The SAP HANA Development perspective is where you will do most of your programming work, for example:
Note
By default, saving a file automatically commits the saved version of the file to the Repository.
The SAP HANA Development perspective contains the following main work areas:
● Explorers/Browsers
Selected views enable you to browse your development artifacts: the objects on your workstation, and the
objects in the repository of the SAP HANA system you are working with.
● Editors
Specialized editors enable you to work with different types of development objects, for example,
application-configuration files, JavaScript source files, SQLScript files.
You can browse and perform actions on the contents of the SAP HANA Repository on a specific SAP HANA
system.
The Repositories view displays the contents of the repository on a specific SAP HANA [Link] can navigate
the package hierarchy and check out project files from the SAP HANA Repository; the checked out files are
downloaded to the workspace on your local file system, where you can work on them and modify them as
required.
The Project Explorer view is the most commonly used element of the SAP HANA Development perspective; it
shows you the development files located in the repository workspace you create on your workstation. You use
the Project Explorer view to create and modify development files. Using context-sensitive menus, you can also
commit the development files to the SAP HANA repository and activate them. Bear in mind that saving a file in
shared project commits the saved version of the file to the repository automatically.
Files with names that begin with the period (.), for example, .xsapp, are sometimes not visible in the
Project Explorer. To enable the display of all files in the Project Explorer view, use the Customize View
Available Customization option and clear all check boxes.
The Systems view is one of the basic organizational elements included with the Development perspective.
You can use the Systems view to display the contents of the SAP HANA database that is hosting your
development project artifacts. The Systems view of the SAP HANA database shows both activated objects
(objects with a runtime instance) and the design-time objects you create but have not yet activated.
● Security
Contains the roles and users defined for this system.
● Catalog
Contains the database objects that have been activated, for example, from design-time objects or from
SQL DDL statements. The objects are divided into schemas, which is a way to organize activated database
objects.
● Provisioning
Contains administrator tools for configuring smart data access, data provisioning, and remote data
sources
● Content
Contains design-time database objects, both those that have been activated and those not activated. If you
want to see other development objects, use the Repositories view.
Each application that you want to develop and deploy on SAP HANA Extended Application Services (SAP HANA
XS) required so-called “application descriptor” files. The application descriptors describe an application's
framework within SAP HANA XS.
The framework defined by the SAP HANA XS application descriptors includes the root point in the package
hierarchy where content is to be served to client requests. When defining the application framework, you also
have to specify whether the application is permitted to expose data to client requests, what (if any)
authentication method is required to access application content, and (optionally) what if any privileges are
required to perform actions on the packages and package content that are exposed.
In SAP HANA, a project groups together all the artifacts you need for a specific part of the application-
development environment.
Before you can start the application-development workflow, you must create a project, which you use to group
together all your application-related artifacts. However, a project requires a repository workspace, which
enables you to synchronize changes in local files with changes in the SAP HANA repository. You can create the
workspace before or during the project-creation step. As part of the project-creation process, you perform the
following tasks:
Note
By default, saving the file automatically commits the saved version of the file to the repository.
Note
Files checked out of the repository are not locked; conflicts resulting from concurrent changes to the
same file must be resolved manually, using the Merge tools provided in the context-sensitive Team
menu.
4. Share a project
Sharing a project establishes a link between project-specific files in your development workspace and the
SAP HANA repository. A shared project ensures that changes you make to project-related files in your
development workspace are synchronized with the SAP HANA repository and, as a result, visible to other
team members. Shared projects are available for import by other members of the application-development
team.
3.5 Tutorials
Tutorials are a good way to understand quickly what is required to write a simple native application for SAP
HANA XS.
In this section you can use the following tutorials to help you understand the basic steps you need to perform
when developing native SAP HANA XS applications:
● Hello OData
A simple application that enables you to test the SAP HANA OData interface by exposing an OData
collection for analysis and display in a client application.
● Hello World in server-side JavaScript (XSJS)
A simple application written in server-side JavaScript which displays the words “Hello World” in a Web
browser along with a string extracted from a table in the SAP HANA database.
Note
The namespace sap in the SAP HANA repository is restricted. Place the new packages and application
artifacts that you create during the tutorials in your own namespace, for example, [Link], or use the
[Link] area for testing.
Related Information
This topic describes the steps required to develop a simple application that runs natively in SAP HANA.
Context
This tutorial shows you how to use the SAP HANA studio to develop a functional SAP HANA application.
Although it is simple, the tutorial demonstrates the development process that you can apply to all types of
application-development scenarios.
The tutorial shows how to create a simple SAP HANA application. The application uses server-side JavaScript
code to retrieve data from SAP HANA by executing SQL statements in the SAP HANA database. The retrieved
data is displayed in a Web browser. During the tutorial, you use tools provided in the SAP HANA studio to
perform the following tasks:
Related Information
Application-development artifacts are stored and managed in the SAP HANA repository. To connect to an SAP
HANA repository, you must add the system to SAP HANA studio.
Prerequisites
● Access to a running SAP HANA development system (with SAP HANA XS)
● A valid user account in the SAP HANA database on that system
● Access to SAP HANA studio
Note
To provide access to the SAP HANA repository from the SAP HANA studio, the EXECUTE privilege is
required for SYS.REPOSITORY_REST, the database procedure through which the REST API is tunneled.
Context
You must add a connection to the SAP HANA system hosting the repository that stores the application-
development artifacts you will be working with.
Procedure
4. Type the details of the SAP HANA system in the following fields:
○ Host Name:
The name of the server hosting the SAP HANA database instance, for example, [Link]
If you are adding a tenant database in a multi-database system, you can specify either the fully
qualified domain name (FQDN) of the system hosting the tenant database or the virtual host name for
Tip
If you do not enter the virtual host name for the tenant database here, you must specify it explicitly
as the XS server host in the system properties. You can do this after you have finished adding the
system. In the Systems view by right-clicking the system whose properties you want to modify and
choosing Properties XS Properties .
○ Instance Number
SAP HANA instance number on that server, for example, 00
○ Description
A display name for the system you are adding. When you start working with a lot of systems, you will
need to label and recognize the systems in the SAP HANA studio. Enter Development System.
5. Select Next.
6. Enter a user name and password for the connection, and select Finish.
After adding the system, you will see the system in the Systems view.
The place where you work on development objects is called a repository workspace. The workspace is the link
between the SAP HANA repository and your local file system.
Prerequisites
● Access to a running SAP HANA development system (with SAP HANA XS)
● A valid user account in the SAP HANA database on that system
● Access to SAP HANA studio
● Access to the SAP HANA Repository
Context
After you add the SAP HANA system hosting the repository that stores your application-development files, you
must specify a repository workspace, which is the location in your file system where you save and work on the
development files.
Procedure
In the Repositories view, you see your workspace, which enables you to browse the repository of the
system tied to this workspace. The repository packages are displayed as folders.
At the same time, a folder will be added to your file system to hold all your development files.
Remove from client (keep remote changes) Remove workspace from local client system; delete all
local workspace-related files; retain changes to remote
(repository) data.
Disconnect local from remote (keep changes) Keep the workspace but remove the workspace label
from the list of workspaces displayed in the
Repositories view. The connection to the disconnected
workspace can be reestablished at any time with the
option Import Local Repository Workspaces.
You use the project to collect all the development artifacts relating to a particular part of an application in one
convenient place.
Prerequisites
● Access to a running SAP HANA development system (with SAP HANA XS)
● A valid user account in the SAP HANA database on that system
● Access to SAP HANA studio
● Access to an SAP HANA Repository workspace
Context
After you set up a development environment for the chosen SAP HANA system, you can add a project to
contain all the development objects you want to create as part of the application-development process.
Procedure
2. From the File menu in SAP HANA studio, choose New Project .
3. In the New Project dialog, under SAP HANA Application Development , select XS Project, and choose
Next.
4. Enter the following details for the new project:
○ Project name
Enter: [Link]
Since a project name must be unique within the same Eclipse workspace, a good convention is to use
the fully qualified package name as the project name.
○ Project location
You can keep this as the default SAP HANA studio (Repository) workspace. To save the project in an
alternative location from the recommended default, you must first disable the option Share project in
SAP repository. You can share the new project manually later. Sharing a project enables continuous
synchronization with the SAP HANA repository.
○ Working sets (optional)
A working set is a concept similar to favorites in a Web browser, which contain the objects you work on
most frequently.
Results
The Project Explorer view in the SAP HANA Development perspective displays the new project. The system
information in brackets [X4D (D007)...] to the right of the project node name in the Project Explorer view
indicates that the project has been shared; shared projects are regularly synchronized with the Repository
hosted on the SAP HANA system you are connected to.
If you disabled the option Share project in SAP repository when you created the project, you must share the
new project manually.
Related Information
Sharing a project establishes a link between project-specific files in your development workspace and the
repository hosted by the SAP HANA system you are connected to.
Prerequisites
● Access to a running SAP HANA development system (with SAP HANA XS)
● A valid user account in the SAP HANA database on that system
● Access to SAP HANA studio
● Access to an SAP HANA Repository workspace
● An existing SAP HANA project
Context
Sharing a project associates the project with your repository workspace and synchronizes the project with the
repository hosted on the SAP HANA system you are connected to. By default, a project is automatically shared
at the same time as it is created; the option to disable the auto-share operation is available in the project-
creation wizard.
Note
Manually sharing a project is necessary only if you disabled the option Share project in SAP repository when
you created the project or chose to explicitlyunshare the project after you created it.
Procedure
1. Start SAP HANA studio and open the SAP HANA Development perspective.
2. In the Project Explorer view, right-click the project you want to share, and choose Team Share Project
in the context-sensitive popup menu to display the Share Project dialog.
Since you only have one workspace, the wizard selects it for you automatically. If you have more than one
workspace, you must choose the workspace to host the shared project.
The dialog also shows the Current project location (the current location of your project, in the repository
workspace), and the New project location (where your project will be copied so it can be associated with
the repository workspace).
Also, since Add project folder as subpackage is checked, subpackages will be created based on the name of
your project.
3. Choose Finish.
The shared project is displayed in the Project Explorer view associated with your workspace.
4. Right-click the .project file, and select Team Commit from the context-sensitive popup menu to
add your project and its files to the repository. The .project file is now displayed with a diamond icon,
, indicating that the latest version of the file on your workstation has been committed to the SAP HANA
repository.
In addition, the Repositories view shows that a new hierarchy of packages has been created based on the
name of your project, [Link].
SAP HANA Extended Application Services (SAP HANA XS) supports server-side application programming in
JavaScript. In this step we add some simple JavaScript code that generates a page which displays the words
Hello, world!.
Prerequisites
● Access to a running SAP HANA development system (with SAP HANA XS)
● A valid user account in the SAP HANA database on that system
● Access to SAP HANA studio
● Access to a shared project in the SAP HANA Repository where you can create the artifacts required for this
tutorial.
As part of this server-side JavaScript tutorial, you create the following files:
● [Link]
This contains your server-side JavaScript code.
● .xsapp
This marks the root point in the application's package hierarchy from which content can be exposed via
HTTP. You still need to explicitly expose the content and assign access controls.
● .xsaccess
Expose your content, meaning it can be accessed via HTTP, and assign access controls, for example, to
manage who can access content and how.
Tip
If you are using SAP HANA studio to create artifacts in the SAP HANA Repository, the file-creation wizard
adds the required file extension automatically and enables direct editing of the file in the appropriate editor.
Procedure
3. In the Project Explorer view, right-click your XS project, and choose New Other in the context-
sensitive popup menu.
4. In the Select a Wizard dialog, choose SAP HANA Application Development XS JavaScript File .
5. In the New XS JavaScript File dialog, enter [Link] in File name text box.
Tip
If you are using SAP HANA studio to create artifacts in the SAP HANA Repository, the file creation
wizard adds the required file extension automatically and enables direct editing of the file in the
appropriate editor. You can also select a template to use. Templates contain sample source code to
help you.
6. Choose Finish.
7. In the [Link] file, enter the following code and save the file:
Note
By default, saving the file automatically commits the saved version of the file to the repository.
$.[Link] = "text/html";
$.[Link]( "Hello, World !");
The example code shows how to use the SAP HANA XS JavaScript API's response object to write HTML.
By typing $. you have access to the API's objects.
8. Check that the application descriptor files are present in the root package of your new XS JavaScript
application.
Note
By default, the project-creation Wizard creates the application descriptors automatically. If they are not
present, you will see a 404 error message in the Web Browser when you call the XS JavaScript service.
If you need to create the application descriptors manually, perform the following steps:
a. Add a blank file called .xsapp (no name, just a file extension) to the root package of your XS
JavaScript application.
To add an .xsapp file, right-click the project to which you want to add the new file, select New
Other SAP HANA Application Development XS Application Descriptor File from the context-
sensitive popup menu, and choose Next.
Tip
If you are using SAP HANA studio to create artifacts in the SAP HANA Repository, the file-creation
wizard adds the required file extension automatically.
b. Add a file called .xsaccess (no name, just a file extension) to the root package of your XS JavaScript
application, and copy the following code into the new .xsaccess file:
To add a .xsaccess manually, right-click the project to which you want to add the file, select New
Other SAP HANA Application Development XS Application Access File from the context-
sensitive popup menu, and choose Next.
Tip
If you are using SAP HANA studio to create artifacts in the SAP HANA Repository, the file-creation
wizard adds the required file extension automatically, provides a working template, and, if
appropriate, enables direct editing of the file.
{
"exposed" : true,
"authentication" :
[
{ "method" : "Form" }
],
"prevent_xsrf" : true
}
This code exposes the application content via HTTP, specifies form-based logon as the default
authentication method for the corresponding SAP HANA application, and helps protect your
application from cross-site request-forgery (XSRF) attacks.
Tip
You define the user-authentication method for a SAP HANA application in the application's runtime
configuration, for example, using the SAP HANA XS Administration Tool. For the purposes of this
tutorial, you do not need to change the runtime configuration.
Results
To access your JavaScript application, open a Web browser and enter the following URL, replacing
<myServer> with the name of the server hosting your SAP HANA instance, and where appropriate the path to
the server-side JavaScript source file:
[Link]
Note
For standard HTTP access, the port number is 80<SAPHANA_ID>, where <SAPHANA_ID> is two digits
representing your SAP HANA instance number. For example, if your SAP HANA instance is 00, then the
port number to use is 8000.
The final step of the data display tutorial is to extract data from the database and display it in a Web Browser.
Prerequisites
● Access to a running SAP HANA development system (with SAP HANA XS)
● A valid user account in the SAP HANA database on that system
● Access to SAP HANA studio
● Access to the shared project in the SAP HANA Repository which contains the artifacts used in this tutorial.
Context
To extract data from the database we use our JavaScript code to open a connection to the database and then
prepare and run an SQL statement. The results are added to the response which is displayed in the Web
browser. You use the following SQL statement to extract data from the database:
The SQL statement returns one row with one field called DUMMY, whose value is X.
Procedure
$.[Link] = "text/html";
var output = "Hello, World !";
var conn = $.[Link]();
Note
Saving a file in a shared project automatically commits the saved version of the file to the Repository,
To explicitly commit a file to the Repository, right-click the file (or the project containing the file) and
choose Team Commit from the context-sensitive popup menu.
6. Activate the file [Link] by right-clicking the file and choosing Team Activate .
Results
In your browser, refresh the page. If everything works as expected, you should see the following page:
The package you put together to test the SAP HANA OData interface includes all the artifacts you need to use
SAP HANA Extended Application Services (SAP HANA XS) to expose an OData collection for analysis and
display by client applications.
Prerequisites
Since the artifacts required to get a simple OData application up and running are stored in the repository, it is
assumed that you have already performed the following tasks:
Context
Tip
File extensions are important. If you are using SAP HANA studio to create artifacts in the SAP HANA
Repository, the file-creation wizard adds the required file extension automatically and, if appropriate,
enables direct editing of the file in the appropriate editor.
Procedure
1. Create a root package for your OData application, for example, helloodata and save and activate it in the
repository.
a. Click the Content directory with the alternate mouse button and choose New Package .
b. Enter the required information for the package in the dialog box and choose OK.
Note
The namespace sap is restricted. Place the new package in your own namespace, which you can create
alongside the sap namespace.
Tip
File extensions are important. If you are using SAP HANA studio to create artifacts in the SAP HANA
Repository, the file-creation wizard adds the required file extension automatically and, if appropriate,
enables direct editing of the file in the appropriate editor.
schema_name="HELLO_ODATA";
3. Create the database table that contains the data to be exposed by your OData service definition, for
example, [Link].
In the Project Explorer view, right-click the folder where you want to create the new OData service definition
file and choose New Other SAP HANA Database Development Database Table in the context-
sensitive popup menu.
File extensions are important. If you are using SAP HANA studio to create artifacts in the SAP HANA
Repository, the file-creation wizard adds the required file extension automatically and, if appropriate,
enables direct editing of the file in the appropriate editor.
Note
If the editor underlines the keywords nullable and Defaultvalue in red, you can safely ignore this.
[Link] = "HELLO_ODATA";
[Link] = COLUMNSTORE;
[Link] = [
{name = "Col1"; sqlType = VARCHAR; nullable = false; length = 20; comment
= "dummy comment";},
{name = "Col2"; sqlType = INTEGER; nullable = false;},
{name = "Col3"; sqlType = NVARCHAR; nullable = true; length = 20;
defaultValue = "Defaultvalue";},
{name = "Col4"; sqlType = DECIMAL; nullable = false; precision = 12;
scale = 3;}];
[Link] = ["Col1", "Col2"];
call
_SYS_REPO.GRANT_SCHEMA_PRIVILEGE_ON_ACTIVATED_CONTENT('select','<SCHEMANAME
>','<username>');
5. Create an application descriptor for your new OData application in your root OData package helloodata.
The application descriptor (.xsapp) is the core file that you use to define an application's availability within
SAP HANA application. The .xsapp file sets the point in the application-package structure from which
content will be served to the requesting clients.
Note
The application-descriptor file has no content and no name; it only has the extension .xsapp. File
extensions are important. If you are using SAP HANA studio to create artifacts in the SAP HANA
Repository, the file-creation wizard adds the required file extension automatically and, if appropriate,
enables direct editing of the file in the appropriate editor.
a. In the Project Explorer view, right-click the folder where you want to create the new application
descriptor and choose New Other SAP HANA Application Development XS Application
Descriptor File in the context-sensitive popup menu.
Note
Saving a file in a shared project automatically commits the saved version of the file to the
repository, To explicitly commit a file to the repository, right-click the file (or the project containing
the file) and choose Team Commit from the context-sensitive popup menu.
6. Create an application-access file for your new OData application and place it in your root OData package
helloodata.
The application-access file enables you to specify who or what is authorized to access the content exposed
by the application.
Note
The application-access file has no name; it only has the extension .xsaccess. File extensions are
important. If you are using SAP HANA studio to create artifacts in the SAP HANA Repository, the file-
creation wizard adds the required file extension automatically and, if appropriate, enables direct editing
of the file in the appropriate editor.
a. In the Project Explorer view, right-click the folder where you want to create the new application
descriptor and choose New Other SAP HANA Application Development XS Application
Access File in the context-sensitive popup menu.
b. Enter the following content in the .xsaccess file for your new OData application:
{
"exposed" : true,
"prevent_xsrf" : true
}
Note
It is highly recommended to always use the prevent_xsrf keyword to help protect your
application against attacks that use cross-site request forgery.
Tip
File extensions are important. If you are using SAP HANA studio to create artifacts in the SAP HANA
Repository, the file-creation wizard adds the required file extension automatically and, if appropriate,
enables direct editing of the file in the appropriate editor.
a. In the Project Explorer view, right-click the folder where you want to create the new application
descriptor and choose New Other SAP HANA Application Development XS OData File in
the context-sensitive popup menu.
b. Enter the following content in the [Link] OData service-definition file:
service {
"helloodata::otable";
Note
If you are using Internet Explorer, press F12 and set compatibility mode = IE10 and document mode =
Standards.
[Link]
otable
Tip
You can also run the service directly from the Project Explorer view where you activated it; right-click
the object in the Project Explorer view and chose Run As... in the context-sensitive popup menu.
In SAP HANA Extended Application Services (SAP HANA XS), the design-time artifacts that make up your
application are stored in the repository like files in a file system. You first choose a root folder for your
application-development activities, and within this folder you create additional subfolders to organize the
applications and the application content according to your own requirements.
Note
For the latest information about the availability of features for SAP HANA Extended Application Services
(SAP HANA XS) and related development tools, see 1779803 .
As part of the application-development process, you typically need to perform the tasks described in the
following list. Each of the tasks in more detail is described in its own section:
1 Check roles and permissions Before you start developing applications using the features and tools provided by
the SAP HANA XS, developers who want to build applications to run on SAP
HANA XS need to be granted access to development tools, SAP HANA systems,
database accounts, and so on.
2 Set up delivery units To create and manage delivery units, for example, using the SAP HANA
Application Lifecycle Management, you must set the identity of the vendor with
whom the delivery units are associated. To avoid conflicts with applications from
SAP or other providers, we recommend that you use the DNS name of your com
pany as the name of your root application-development folder, for example,
[Link].
3 Set up an SAP HANA project In SAP HANA, projects enable you to group together all the artifacts you need for
a specific part of the application-development environment. To create a project,
you must first create a repository workspace, a directory structure to store files
on your PC.
4 Maintain repository packages To perform the high-level tasks that typically occur during the process of main
taining repository packages, you need to be familiar with the concepts of pack
ages and package hierarchies, which you use to manage the artifacts in your ap
plications.
5 Maintain application descriptors The framework defined by the application descriptors includes the root point in
the package hierarchy where content is to be served to client requests; it also
defines if the application is permitted to expose data to client requests and what
kind of access to the data is allowed.
6 Maintain application security As part of the application-development process, you must decide how to grant
access to the applications you develop. For example, you must specify which (if
any) authentication method is used to grant access to content exposed by an ap
plication, and what content is visible.
An overview of the authorizations required to develop database artifacts for SAP HANA using the CDS syntax.
To enable application-developers to start building native applications that take advantage of the SAP HANA
Extended Application Services (SAP HANA XS), the SAP HANA administrator must ensure that developers
have access to the tools and objects that they need to perform the tasks required during the application- and
database-development process.
Before you start developing applications using the features and tools provided by the SAP HANA XS, bear in
mind the following prerequisites. Developers who want to build applications to run on SAP HANA XS need the
following tools, accounts, and privileges:
Note
The required privileges can only be granted by someone who has the necessary authorizations in SAP
HANA, for example, an SAP HANA administrator.
To develop database artifacts for use by applications running in the SAP HANA XS classic environment, bear in
mind the following prerequisites:
● Access to a running SAP HANA development system (with SAP HANA XS classic)
● A valid user account in the SAP HANA database on that system
● Access to development tools, for example, provided in:
○ SAP HANA studio
○ SAP HANA Web-based Development Workbench
● Access to the SAP HANA repository
● Access to selected run-time catalog objects
To provide access to the repository for application developers, you can use a predefined role or create your
own custom role to which you assign the privileges that the application developers need to perform the
everyday tasks associated with the application-development process.
To provide access to the repository from the SAP HANA studio, the EXECUTE privilege is required for
SYS.REPOSITORY_REST, the database procedure through with the REST API is tunneled. To enable the
activation and data preview of information views, the technical user _SYS_REPO also requires SELECT privilege
on all schemas where source tables reside.
In SAP HANA, you can use roles to assign one or more privileges to a user according to the area in which the
user works; the role defines the privileges the user is granted. For example, a role enables you to assign SQL
privileges, analytic privileges, system privileges, package privileges, and so on. To create and maintain artifacts
in the SAP HANA repository, you can assign application-development users the following roles:
Before you start using the SAP HANA Web-based Development Workbench, the SAP HANA administrator must
set up a user account for you in the database and assign the required developer roles to the new user account.
Tip
The role [Link]::Developer grants the privileges required to use all the tools included in the
SAP HANA Web-based Development Workbench. However, to enable a developer to use the debugging
features of the browser-based IDE, your administrator must also assign the role
[Link]::Debugger. In addition, the section debugger with the parameter enabled and the
value true must be added to the file [Link], for example, in the SAP HANA studio
Administration perspective.
To develop database artifacts for use by applications running in the SAP HANA XS advanced environment, bear
in mind the following prerequisites:
● Access to a running SAP HANA development system (with SAP HANA XS advanced)
Note
To provide access to tools and for application developers in XS advanced, you define a custom role to
which you add the privileges required to perform the everyday tasks associated with the application-
and database-development process. The role is then assigned to a role collection which is, in turn,
assigned to the developer.
Related Information
A delivery unit (DU) is a collection of packages that are to be transported together. You assign all the packages
belonging to your application to the same DU to ensure that they are transported consistently together within
your system landscape. Each DU has a unique identity.
Prerequisites
To maintain delivery units with the SAP HANA Application Lifecycle Management, you must ensure the
following prerequisites are met:
The identity of a delivery unit consists of two parts: a vendor name and a delivery-unit name. The combined ID
ensures that delivery units from different vendors are easy to distinguish and follows a pattern that SAP uses
for all kinds of software components.
To create and manage delivery units you first need to maintain the identity of the vendor, with whom the
delivery units are associated, and in whose namespace the packages that make up the delivery unit are stored.
As part of the vendor ID maintenance process, you must perform the following tasks:
Procedure
Related Information
In SAP HANA, the vendor ID is used primarily to define the identity of the company developing a software
component that it plans to ship for use with SAP HANA, for example, “[Link]”. To create a delivery unit, it is a
prerequisite to maintain a vendor ID in your system.
Prerequisites
To set the vendor ID, you must ensure the following prerequisites are met:
Context
Before creating your own first delivery unit, you must set the identity of the vendor in the development
system's configuration. To maintain details of the delivery-unit vendor ID, perform the following steps:
Procedure
Note
To start the SAP HANA Application Lifecycle Management, you must use the logon credentials of an
existing database user, who has the appropriate user role assigned.
Note
A delivery unit (DU) is a group of transportable packages that contain objects used for content delivery. You
can use the SAP HANA Application Lifecycle Management to create a DU for your application content or your
software component.
Prerequisites
To create a delivery unit with the SAP HANA Application Lifecycle Management, you must ensure the following
prerequisites are met:
Context
You use a DU to transport the design-time objects that are stored in the SAP HANA repository between two
systems, for example, from a development system to a consolidation system. To create a new delivery unit
using the SAP HANA application lifecycle management, perform the following steps.
Procedure
Note
The numbers you enter here refer to the application component that you are developing; the
numbers do not refer to the patch or service-pack level deployed on the SAP HANA server.
6. Choose Create.
The new delivery unit is added to the SAP HANA repository in the namespace specified by the vendor ID
and the application path.
7. Check the status bar at the bottom of the browser window for error messages. Choose the message link to
display the message text.
Results
Related Information
The delivery unit (DU) is the vehicle that SAP HANA application lifecycle management uses to ship software
components from SAP (or a partner) to a customer. The DU is also the container you use to transport
application content in your system landscape. In SAP HANA, the name of a DU must adhere to conventions and
guidelines.
If you create a delivery unit, the name of the new delivery unit must adhere to the following conventions
● A delivery-unit name must contain only capital letters (A-Z), digits (0-9), and underscores (_).
Note
The naming conventions for packages in a delivery unit differ from the naming conventions that apply to
the delivery unit itself. For example, the maximum length of a package name is not restricted to 30
characters; however, it must be less than 190 characters (including the namespace hierarchy).
Projects group together all the artifacts you need for a specific part of the application-development
environment.
Context
Before you can start the application-development workflow, you must create a project, which you use to group
together all your application-related artifacts. However, a project requires a repository workspace, which
enables you to synchronize changes in local files with changes in the repository. You can create the workspace
before or during the project-creation step. As part of the project-creation process, you perform the following
tasks:
Procedure
Note
Files checked out of the repository are not locked; conflicts resulting from concurrent changes to the
same file must be resolved manually, using the Merge tools provided in the context-sensitive Team
menu.
Related Information
A workspace is a local directory that you map to all (or part) of a package hierarchy in the SAP HANA
repository. When you check out a package from the repository, SAP HANA copies the contents of the package
hierarchy to your workspace, where you can work on the files.
Context
Before you can start work on the development of the application, you need to set up a workspace, where you
store checked-out copies of your application’s source-code files. To ensure that only the owner of data can
access the data stored in a workspace, a workspace must be created in the owner's home directory. In addition,
it is recommended that users encrypt the data on their hard drives using an encryption tool.
To create a new workspace in the SAP HANA studio, perform the following steps:
Procedure
Note
Although the packages and objects in the chosen repository are visible in the Repositories view, you
cannot open or work on the objects here. To work on objects, you must create a project and use the
Project Explorer view.
UI Icon Explanation
Yellow database icon An inactive workspace exists in the SAP HANA repository
Yellow database icon An inactive workspace has been imported to your local file system (and the contents checked
with a blue check out from the SAP HANA repository)
mark
Remove from client (keep remote changes) Remove workspace from local client system; delete all
local workspace-related files; retain changes to remote
(repository) data.
Disconnect local from remote (keep changes) Keep the workspace but remove the workspace label
from the list of workspaces displayed in the
Repositories view. The connection to the disconnected
workspace can be reestablished at any time with the
option Import Local Repository Workspaces.
The place where you work on project-related objects is called a repository workspace. A workspace is an
environment that maps a local directory to all (or part) of a package hierarchy in the SAP HANA repository.
In SAP HANA studio, the repository tools enable you to browse the entire hierarchy of design-time objects
stored in the repository. However, when you check a package out of the repository, SAP HANA copies the
contents of the package hierarchy to your workspace, where you can work on the files in your local file system.
Note
Before you can create a workspace you must maintain connection information in the SAP HANA database
user store.
To start development work with SAP HANA studio, for example, to checkout the contents of a package, you
must create a repository workspace. The workspace contains a system folder with metadata and package
folders for the repository content. The file-system folders and their subfolders reflect the package hierarchy in
the repository; the repository client ensures that changes are synchronized.
In the SAP HANA studio, the Repositories view displays the status of a workspace as follows:
Before you can start the application-development workflow, you must create a project, which you use to group
all your application-related artifacts.
Context
Projects group together all the artifacts you need for a specific part of your application-development
environment. A basic project contains folders and files. More advanced projects are used for builds, version
management, sharing, and the organization and maintenance of resources.
To create a new project in the SAP HANA studio, perform the following steps:
Procedure
4. Choose File New Project... or right-click the white space in the Project Explorer view and choose
New > Project… in the popup menu.
The type of project you create determines the details you have to provide in the New Project wizard that
appears. Choose SAP HANA Application Development XS Project .
a. Enter the following details for the new XS project:
○ Shared project
This is the default setting. Sharing a project enables continuous synchronization between your
local-file system workspace and the SAP HANA repository. If you choose not to share the project
at this point, you can share the new project manually later.
○ Project name
Enter a project name that describes what the project is about, for example: XS_JavaScript or
XS_SAPUI5. Since a project name must be unique within the same Eclipse workspace, it is
recommended to use the fully qualified package name as the project name.
○ Project location
You can save the project in the default location, which is the SAP HANA studio (Repository)
workspace. To save the project in an alternative location from the recommended default, first
disable the option Share project in SAP repository.
You can share the new project manually later. Sharing a project enables continuous
synchronization with the SAP HANA repository.
○ Working sets
A working set is a concept similar to favorites in a Web browser, which contain the objects you
work on most frequently.
○ Repository workspace and package
For a shared project, you can set the project location by selecting a repository workspace and
package.
○ Common objects
For a shared project, you can include some commonly used objects in your project. Some of these
will provide you with a basic template to begin with.
○ Access objects
For a shared project, the access objects are checked by default. However, if either an .xsaccess file
or an .xsapp file already exists in the folder you have chosen to create the new project, the
corresponding option is automatically unchecked and greyed out.
b. Click Finish to create the new project.
All the objects included are activated automatically when the project is created. The new project is
displayed in the Project Explorer view.
Note
○ If there is an error during activation of one of the project objects, none of the objects will be
automatically activated. You can manually correct the error and then manually activate the objects.
○ The contents of the project depend on the type of project you create. For example, a general
project is empty immediately after creation; a JavaScript project contains all the resource files
associated with a JavaScript project, such as libraries and build-environment artifacts.
Before you can start the application-development workflow, you must create a project, which you use to group
all your application-related artifacts.
Projects group together all the artifacts you need for a specific part of the application-development
environment. A basic project contains folders and files. More advanced projects are used for builds, version
management, sharing, and the organization and maintenance of resources.
Projects enable multiple people to work on the same files at the same time. You can use SAP HANA studio to
perform the following project-related actions in the repository:
Note
Files checked out of the repository are not locked; conflicts resulting from concurrent changes to the same
file must be resolved manually, using the Merge tools provided in the context-sensitive Team menu.
By committing project-related files to the repository and activating them, you enable team members to see the
latest changes. The commit operation detects all changes in packages that you configure SAP HANA studio
tool to track and writes the detected changes back to the repository. The repository client tools also support
synchronization with changes on the server, including conflict detection and merging of change. All workspace-
related repository actions are available as context-sensitive menu options in SAP HANA studio. For example, if
you right click a repository object at the top of the package hierarchy in the Project Explorer in SAP HANA
studio, you can commit and activate all changed objects within the selected hierarchy.
Note
If you create a new project using SAP HANA studio, you can assign the new project to an existing
workspace.
You can share and unshare projects. Sharing a project associates it with a particular package in the repository
linked to a particular workspace. The act of sharing the project sets up a link between the workspace and the
repository and enables you to track and synchronize local changes with the versions of the objects stored in the
repository. When a project is shared, it becomes available to other people with authorization to access to the
repository, for example, colleagues in an application-development team. Team members can import a shared
project and see and work on the same files as the creator of the project.
Note
In the SAP HANA studio you can create a project at any package level, which enables a fine level of control of
the artifacts that may (or may not) be exposed by sharing the project.
Before you can start working on files associated with a new project, you must share the project; sharing a
project enables you to track and synchronize local changes with the repository.
Context
When you share a project, you set up a connection to the SAP HANA repository associated with a particular
SAP HANA instance. Sharing the project enables you to ensure that changes you make to project-related files
are visible to other team members and applications. Other developers can import a shared project and work on
the same files.
Note
Use the Project Explorer view in the SAP HANA studio to check if a project is shared. In addition to the
project name, a shared project displays the SAP HANA system ID of the repository where the shared
artifacts are located, an SAP HANA user name, and the path to the repository package to which the shared
project is assigned, for example. "XSJS_myproject [SID (dbusername, '[Link].app1')].
To share a project in the SAP HANA studio, perform the following steps:
Procedure
Right-click the project you want to share and choose Team Share Project… in the pop-up menu.
5. Select the repository type.
The Share Project dialog displays a list of all available repository types; choose SAP HANA Repository and
choose Next.
6. Select the repository workspace where the project should be located.
7. Specify the package that you want to associate the shared project with.
The Share Project dialog displays the suggested location for the shared project in the New Project location
screen area. The default location is the name of the workspace with the name of the project you want to
share. Choose Browse... to locate the package you want to associate the shared project with. The selected
package is displayed in the Path to package text box.
Note
The Keep project folder option appends the name of the project you are sharing to the name of the
workspace in which you are sharing the project and creates a new package with the name of the shared
project under the workspace location displayed. Use this option only if you want to create multiple
Note
The Project Explorer view decorates the file icons to indicate the current state of the repository files, for
example: local (not yet committed), committed (inactive), and active (available for use by others).
10. Make the project available for import, for example, so that others can join it and make changes to project
content.
The project-sharing procedure creates some artifacts (for example, the .project file) that must be
committed to the repository and activated so that other team members can import the project more easily
into their workspace. The .project file is used in several dialogs to populate the list of available projects.
Note
Use the Repositories view to import projects (and checkout project content).
Related Information
Before you can start the application-development workflow, you must either create a new project and share it
(with the repository), or import a shared project from the repository into your workspace. Importing a project
enables you to track and synchronize local changes with the colleagues working on the objects in the imported
project.
Context
To import an existing project from the repository into your workspace, perform the following steps.
Note
The existence of a .project file in a package identifies the package as being associated with a project.
The SAP HANA studio checks out the content of the selected package and displays any projects it finds in
the Projects screen area.
5. Select the projects to import.
If multiple projects are available for import, select the projects you want to import.
6. Choose Finish to import the selected projects.
You can add the imported project to your Working Sets.
Note
A working set is a concept similar to favorites in a Web browser, which contain the objects you work on
most frequently.
All content delivered as part of the application you develop for SAP HANA is stored in packages in the SAP
HANA repository. The packages are arranged in a hierarchy that you define to help make the process of
maintaining the packages transparent and logical.
Context
To perform the high-level tasks that typically occur during the process of maintaining repository packages, you
need to be familiar with the concepts of packages and package hierarchies. Packages enable you to group
together the artifacts you create and maintain for your applications. You must also be aware of the privileges
the application developers require to access (and perform operations on) the packages.
Note
You can also create and delete packages in the Project Explorer, for example, by creating or deleting folders
in shared projects and committing and activating these changes. However, to maintain advanced package
As part of the process of maintaining your application packages, you typically perform the following tasks:
Procedure
Related Information
Context
The package hierarchy for a new project might include sub-packages, for example, to isolate the data model
from the business logic. Although there are no package interfaces to enforce visibility of objects across
packages, this separation of logical layers of development is still a recommended best practice.
Note
You can only assign one project per package; this is important to remember if you have a mixture of design-
time objects that need to be used in multiple projects, for example: server-side JavaScript (XSJS), SAPUI5,
and a general project (for procedures).
com
\
acme
\
hana
\
app1
\
docs
\
tutorials
● Package hierarchy
Each vendor uses a dedicated namespace, for example, [Link].
Note
Do not use the namespace sap to build your application hierarchy. The namespace sap is reserved for
use by SAP; packages created in the sap namespace are overwritten by system updates.
● Package type
Some packages contain content; other packages contain only other (sub)packages. Packages can also
contain both objects and (sub)packages.
● Package naming conventions
There are recommendations and restrictions regarding package names.
To set up a package hierarchy in the SAP HANA repository, perform the following steps:
Procedure
Related Information
A package hierarchy can include sub-packages, for example, to isolate the data model from the business logic.
You can create a package hierarchy, for example, by establishing a parent-child type relationship between
packages. The assignment of packages to delivery units is independent of the package hierarchy; packages in a
parent-child relationship can belong to different delivery units. SAP recommends that you assign to one
specific delivery unit all packages that are part of a particular project or project area.
The package hierarchy for a new project typically includes sub-packages, for example, to isolate the data model
from the business logic. Although there are no package interfaces to enforce visibility of objects across
packages, this separation of logical layers of development is still a recommended best practice.
You can only assign one project per package; this is important to remember if you have a mixture of design-
time objects that need to be used in multiple projects, for example: server-side JavaScript (XSJS), SAPUI5,
and a general project (for procedures).
The following simple example shows a package structure containing tutorials for the use of a new application:
sap
\
hana
\
app1
\
code
demos
docs
\
tutorials
manuals
help
All content delivered by SAP should be in a sub-package of "sap". Partners and customers should choose their
own root package to reflect their own name (for example, the domain name associated with the company) and
must not create packages or objects under the "sap" root structural package. This rule ensures that customer-
or partner-created content will not be overwritten by an SAP update or patch.
Note
SAP reserves the right to deliver without notification changes in packages and models below the "sap" root
structural package.
There are no system mechanisms for enforcing the package hierarchy. The "sap" root structural package is not
automatically protected. However, by default you cannot change the content of packages that did not originate
in the system. In addition, an authorization concept exists, which enables you to control who can change what
inside packages.
In SAP HANA, a package typically consists of a collection of repository objects, which can be transported
between systems. Multiple packages can be combined in a delivery unit (DU).
An SAP HANA package specifies a namespace in which the repository objects exist. Every repository object is
assigned to a package, and each package must be assigned to a specific delivery unit. In the repository, each
object is uniquely identified by a combination of the following information:
● Package name
● Object name
● Object type
Note
Multiple objects of the same type can have the same object name if they belong to different packages.
● Package hierarchy
Each vendor uses a dedicated namespace, and the package hierarchy you create enables you to store the
various elements of an application in a logical order that is easy to navigate.
● Package type
Packages can be structural or non-structural; some packages contain content; other packages contain
only other (sub)packages.
● Package naming conventions
There are recommendations and restrictions regarding package names, for example, the name's maximum
length and which characters must not be used.
● Permitted characters
Lower/upper case letters (aA-zZ), digits (0-9), hyphens (-), underscores (_), and dots (.) are permitted in
package names. Dots in a package name define a logical hierarchy. For example, "a.b.c" specifies a package
"a" that contains sub-package "b", which in turn contains sub-package "c".
● Forbidden characters
A package name must not start with either a dot (.) or a hyphen (-) and cannot contain two or more
consecutive dots (..).
● Package name length
The name of the complete package namespace hierarchy (for example, “[Link]” including dots) must
not be more than 190 characters long. In addition, on object activation, the maximum permitted length of a
generated catalog name (which includes the package path, the separating dots, and the object base name)
is restricted to 127 characters.
○ hdbtable hdbview, hdbsequence, hdbstructure, hdbprocedure objects
[Link]::myObject
○ CDS objects
[Link]::[Link]
In the SAP HANA repository, you can set package authorizations for a specific user or for a role.
Prerequisites
Context
Authorizations that are assigned to a repository package are implicitly assigned to all sub-packages, too. You
can also specify if the assigned user authorizations can be passed on to other users. To set user (or role)
authorizations for repository packages, perform the following steps:
Procedure
1. Open the Systems view in the SAP HANA studio's SAP HANA Development perspective.
2. In the Systems view, expand the Security Roles/Users node for the system hosting the repository
that contains the packages you want to grant access to.
You can also define roles via source files; roles defined in this way can be assigned to a delivery unit and
transported to other systems.
3. Double click the user (or role) to whom you want to assign authorizations.
4. Open the Package Privileges tab page.
5. Choose [+] to add one or more packages. Press and hold the Ctrl key to select multiple packages.
6. In the Select Repository Package dialog, use all or part of the package name to locate the repository
package that you want to authorize access to.
7. Select one or more repository packages that you want to authorize access to; the selected packages
appear in the Package Privileges tab.
8. Select the packages to which you want authorize access and, in the Privileges for tab, check the required
privileges, for example:
○ [Link]
Read access to the selected package and design-time objects (both native and imported)
○ REPO.EDIT_NATIVE_OBJECTS
Authorization to modify design-time objects in packages originating in the system the user is working
in
Package privileges authorize actions on individual packages in the SAP HANA repository. In the context of
repository package authorizations, there is a distinction between native packages and imported packages.
Note
To be able perform operations in all packages in the SAP HANA repository, a user must have privileges on
the root package .REPO_PACKAGE_ROOT.
A native repository package is created in the current SAP HANA system and expected to be edited in the
current system. To perform application-development tasks on native packages in the SAP HANA repository,
developers typically need the privileges listed in the following table:
An imported repository package is created in a remote SAP HANA system and imported into the current
system. To perform application-development tasks on imported packages in the SAP HANA repository,
developers need the privileges listed in the following table:
Note
It is not recommended to work on imported packages. Imported packages should only be modified in
exceptional cases, for example, to carry out emergency repairs.
Related Information
In SAP HANA, a package contains a selection of repository objects. You assemble a collection of packages into
a delivery unit, which you can use to transport the repository objects between SAP HANA systems.
Context
You can use repository packages to manage the various elements of your application development project in
the SAP HANA repository. To create a package, perform the following steps:
Procedure
1. In the SAP HANA studio, start the SAP HANA Development perspective.
2. In the Systems view, select the SAP HANA system where you want to create a new package and expand the
Content node to display the namespace hierarchy for package content.
3. Right-click the package where you want to add a new package and choose New Package... in the
context-sensitive popup menu.
SAP HANA studio displays the New Package dialog.
4. Maintain the package details.
In the New Package dialog, enter information in the following fields:
a. Enter a name for the new package.
The package Name is mandatory. Add the new name to the end of the full package path, for example,
[Link].package1.
b. Fill in the other optional information as required:
Use the Delivery Unit drop-down list to assign the new package to a delivery unit.
Choose Translation if you intend to have the package content localized. You must maintain the
translation details.
5. Create the new package.
In the New Package dialog, click OK to create a new package in the specified location.
6. Activate the new package.
In the Systems view, right-click the new package and choose Activate from the context-sensitive popup
menu.
SAP HANA enables the use of various types of package, which are intended for use in particular scenarios.
SAP HANA Application Services provide or allow the following package types:
● Structural
Package only contains sub-packages; it cannot contain repository objects.
● Non-Structural
Package contains both repository objects and subpackages.
● sap
Transportable package reserved for content delivered by SAP. Partners and customers must not use the
sap package; they must create and use their own root package to avoid conflicts with software delivered by
SAP, for example when SAP updates or overwrites the sap package structure during an update or patch
process.
● system-local
Non-transportable, structural packages (and subpackages). Content in this package (and any
subpackages) is considered system local and cannot be transported. This is similar to the concept of the
$tmp development class in SAP NetWeaver ABAP.
● [Link]
Non-transportable, structural packages for generated content, that is; content not created by manual user
interaction
● [Link]
Non-transportable, structural package reserved for objects that belong to individual users, for example,
[Link].<user_name> . To avoid compatibility issues with future functionality, do not
use the [Link] package or any of its sub-packages.
In SAP HANA development, repository packages are used to manage various elements of your application
development project. Sometimes you need to delete a package that contains repository objects from other
developers.
Prerequisites
To perform this task, your user must be assigned the REPO.WORK_IN_FOREIGN_WORKSPACE system privilege.
You use repository packages to manage the various elements of your application development project in the
SAP HANA repository. To delete a package, perform the following steps:
Procedure
1. In the SAP HANA studio, start the SAP HANA Development perspective.
2. Open the Repositories view and locate the package that you want to delete.
3. Delete the package.
1. Click the alternate mouse button on the package that you want to delete and choose Delete.
2. When prompted, choose OK.
A message box appears indicating that you are deleting a package with active and inactive objects.
3. Choose OK to delete the package.
Choose Cancel to stop the deletion of the package and objects.
Related Information
The application descriptors describe the framework in which an SAP HANA XS application runs. The
framework defined by the application descriptors includes the root point in the package hierarchy where
content is to be served to client requests, and who has access to the content.
Prerequisites
● You must be familiar with the concept of the application descriptor file (.xsapp), the application-access
file (.xsaccess), and if required, the application-privileges file (.xsprivileges).
When you develop and deploy applications in the context of SAP HANA Extended Application Services (SAP
HANA XS), you must define the application descriptors. Maintaining the application descriptors involves the
following tasks:
Procedure
Related Information
Each application that you want to develop and deploy on SAP HANA Extended Application Services (SAP HANA
XS) must have an application-descriptor file. The application descriptor is the core file that you use to describe
an application's framework within SAP HANA XS.
Prerequisites
Note
The namespace sap is restricted. Place the new package in your own namespace, for example,
[Link], which you can create alongside the sap namespace.
Context
The application descriptor is the core file that you use to indicate an application's availability within SAP HANA
XS. The application descriptor marks the point in the package hierarchy at which an application's content is
available to clients. The application-descriptor file has no contents and no name; it only has the file
extension .xsapp. The package that contains the application-descriptor file becomes the root path of the
resources exposed by the application you develop.
Note
To create an application descriptor for your new application, perform the following steps.
Procedure
1. In the SAP HANA studio, open the SAP HANA Development perspective.
2. In the Project Explorer view, right-click the folder where you want to create the new (.xsapp) file.
4. In the Select a Wizard dialog, choose SAP HANA Application Development XS Application Descriptor
File
5. Enter or select the parent folder. Note that the default file name for the XS application descriptor is .xsapp
and cannot be changed.
6. Select a template to use. Templates contain sample source code to help you get started.
Tip
Files with names that begin with the period (.), for example, .xsapp, are sometimes not visible in the
Project Explorer. To enable the display of all files in the Project Explorer view, use the Customize View
Available Customization option and clear all check boxes.
Each application that you want to develop and deploy on SAP HANA Extended Application Services (SAP HANA
XS) must have an application descriptor file. The application descriptor is the core file that you use to describe
an application's framework within SAP HANA XS.
The package that contains the application descriptor file becomes the root path of the resources exposed to
client requests by the application you develop.
Note
The application-descriptor file has no name and no content; it only has the file extension “xsapp”, for
example, .xsapp. For backward compatibility, content is allowed in the .xsapp file but ignored.
The application root is determined by the package containing the .xsapp file. For example, if the package
[Link] contains the file .xsapp, the application will be available under the URL [Link]
[Link]/. Application content is available to requests from users.
Caution
Make sure that the folder containing the .xsapp application descriptor file also contains an .xsaccess
file, which controls access to the application.
The contents of the package where the .xsapp file resides (and any subfolders) are exposed to user requests
and, as a result, potentially reachable by attackers. You can protect this content with the appropriate
authentication settings in the corresponding application-access (.xsaccess) file, which resides in the same
package. Bear in mind that by exposing Web content, you run the risk of leaking information; the leaked
information can be used in the following ways:
● Directly
Data files such as .csv files used for the initial database load can contain confidential information.
● Indirectly
To help protect your application from security-related issues, place the application descriptor (.xsapp) as
deep as possible in the package hierarchy. In addition, include only the index page in this package; all other
application data should be placed in sub-folders that are protected with individual application-access files.
Tip
Keep the application package hierarchy clean. Do not place in the same package as the .xsapp file (or sub-
package) any unnecessary content, for example, files which are not required for the application to work.
Related Information
The application-access file enables you to specify who or what is authorized to access the content exposed by
the application package and what content they are allowed to see.
Prerequisites
Note
The namespace sap is restricted. Place the new package in your own namespace, for example,
[Link], which you can create alongside the sap namespace.
Context
The application-access file is a JSON-compliant file with the file suffix .xsaccess. You can use a set of
keywords in the application-access file .xsaccess to specify if authentication is required to enable access to
package content, which data is exposed, and if rewrite rules are in place to hide target and source URLs, for
example, from users and search engines. You can also specify what, if any, level of authorization is required for
the package and whether SSL is mandatory for client connections.
The application-access file does not have a name before the dot (.); it only has the suffix .xsaccess.
Procedure
1. Create a file called .xsaccess and place it in the root package of the application to which you want to
enable access.
A basic .xsaccess file must, at the very least, contain a set of curly brackets, for example, {}. Note that
the .xsaccess file uses keyword-value pairs to set access rules; if a mandatory keyword-value pair is not
set, then the default value is assumed.
a. In the SAP HANA studio, open the SAP HANA Development perspective.
b. In the Project Explorer view, right-click the folder where you want to create the new (.xsaccess) file.
c. In the context-sensitive popup menu, choose New Other... .
d. In the Select a Wizard dialog, choose SAP HANA Application Development XS Application Access
File
e. Tip
If you are using the SAP HANA Studio to create artifacts in the SAP HANA Repository, the file
creation wizard adds the required file extension .xsaccess automatically and enables direct
editing of the file.
Enter or select the parent folder where the .xsaccess file is to be located.
Note
The default name for the core application-access file is .xsaccess and cannot be changed.
f. Select a template to use. Templates contain sample source code to help you.
g. Choose Finish.
2. Enable application access to data.
You use the expose keyword to enable or disable access to content at a package or subpackage level.
{
"exposed" : true,
"prevent_xsrf" : true
}
Note
It is highly recommended to always use the prevent_xsrf keyword to help protect your application
against attacks that use cross-site request forgery vector.
{
"authentication" : { "method" : "Form"}
}
Note
Use the SAP HANA XS Administration Tool to configure applications to use additional authentication
methods, for example, basic, logon tickets, or Single Sign On (SSO) providers such as SAML2 and
X509. You must also enable the Form-based authentication checkbox, if you want your application (or
applications) to use form-based logon as the authentication method. Any other keywords in the
authentication section of the .xsaccess file are ignored.
{
"authorization":
["[Link]::Execute",
"[Link]::Admin"
]
}
5. Save the .xsaccess file in the package with which you want to associate the rules you have defined.
Note
Saving a file in a shared project automatically commits the saved version of the file to the repository, To
explicitly commit a file to the repository, right-click the file (or the project containing the file) and
choose Team Commit from the context-sensitive popup menu.
In the Project Explorer view, right click the object you want to activate and choose Team > Activate in
the context-sensitive popup menu.
Related Information
SAP HANA XS enables you to define access to each individual application package that you want to develop
and deploy.
The application-access file enables you to specify who or what is authorized to access the content exposed by
a SAP HANA XS application package and what content they are allowed to see. For example, you use the
application-access file to specify if authentication is to be used to check access to package content and if
rewrite rules are in place that hide or expose target and source URLs.
The application-access file does not have a name; it only has the file extension .xsaccess. The content of
the .xsaccess file is formatted according to JSON rules, and the settings specified in an .xsaccess file apply
not only to the package the .xsaccess file belongs to but also any subpackages lower in the package
hierarchy. Multiple .xsaccess files are allowed, but only at different levels in the package hierarchy. You
cannot place two .xsaccess files in the same package.
Note
The settings specified in an .xsaccess file in a subpackage take precedence over any settings specified in
a .xsaccess file higher up the package hierarchy; the subpackage settings are also inherited by any
packages further down the package hierarchy. Any settings not modified by the .xsaccess in the
subpackage remain unchanged, that is: as defined in the parent package or, where applicable, the default
settings.
Using multiple .xsaccess files enables you to specify different application-access rules for individual
subpackages in the package hierarchy. Following the inheritance rule, any applications below the application
package containing the modified access settings inherit the new, modified settings.
The following example shows the composition and structure of the SAP HANA XS application access
(.xsaccess) file, which comprises a list of key-value pairs that specify how the application service responds to
client requests. For example, in this file, "exposed" : true indicates that data is available to client requests;
"force_ssl" : true specifies that standard HTTP requests are not allowed by the Web browser.
Note
Some elements can also be specified in the application's runtime configuration, for example, using the SAP
HANA XS Administration Tool. For example, you can configure applications to refuse insecure HTTP
connections, allow the use of e-tags, or enable additional authentication methods such as Single Sign On
(SSO) providers SAML2 and X509.
Example:
The Application-Access (.xsaccess) File
{
"exposed" : true, // Expose data via http
"authentication" :
{
"method": "Form"
},
Related Information
The application-access (.xsaccess) file enables you to specify whether or not to expose package content,
which authentication method is used to grant access, and what content is visible.
Example:
The Application Access (.xsaccess) File
Note
This example of the .xsaccess file is not a working model; it is used to illustrate the syntax for all possible
options.
{
"exposed" : false,
"authentication" :
{
"method": "Form"
},
"authorization":
[
"[Link]::Execute",
"[Link]::Admin"
],
"anonymous_connection" : "[Link]::AnonConn",
"default_connection" : "[Link]::sqlcc",
"cache_control" : "no-store",
"cors" :
{
"enabled" : false
},
"default_file" : "index_1.html",
"enable_etags" : false,
"force_ssl" : true,
"mime_mapping" :
[
{
"extension":"jpg", "mimetype":"image/jpeg"
}
],
"prevent_xsrf" : true,
"rewrite_rules" :
[{
"source" : "...",
"target" : "..."
}]
"headers":
{
"enabled": true,
"customHeaders": [ {"name":"X-Frame-Options","value":"<VALUE>"} ]
}
}
{
"exposed" : false,
}
The exposed keyword enables you define if content in a package (and its subpackages) is to be made available
by HTTP to client requests. Values are Boolean true or false. If no value is set for exposed, the default setting
(false) applies.
Tip
Only expose content that is absolutely necessary to enable the application to run.
Consider whether it is necessary to expose data via HTTP/S. Not exposing data via HTTP enables you to keep
your files accessible to other programs but prevent direct access to the data via URL. Since the application's
[Link] page must normally remain reachable, consider storing the [Link] file separately with a
dedicated .xsaccess file that enables access (“exposed”: true). You can keep all other content hidden, for
example, in separate package to which access is denied (“exposed”: false).
Packages without a dedicated .xsaccess file inherit the application-access settings defined in the parent
folder. If an .xsaccess file exists but the exposed keyword is not defined, the default setting false applies.
anonymous_connection
{
"anonymous_connection" : "[Link]::AnonConn",
}
The anonymous_connection keyword enables you to define the name of the .xssqlcc file that will be used
for SQL access when no user credentials are provided. SAP HANA XS enables you to define the configuration
for individual SQL connections. Each connection configuration has a unique name, for example, Registration,
AnonConn, or AdminConn, which is generated from the name of the corresponding connection-configuration
file ([Link], [Link], or [Link]) on activation in the repository.
If no value is set, the default setting is “null”.
Tip
If it is necessary to provide anonymous access to an application, design your application in such a way that all
files requiring anonymous access are placed together in the same package, which you can then protect with
the permissions defined in a dedicated .xsaccess file. Remember that the behavior of the anonymous
connection depends on the details specified in the corresponding SQL configuration file (.xssqlcc).
{
"default_connection" : "[Link]::sqlcc",
}
If the default_connection is set in the .xsaccess file, the specified SQL connection configuration (for
example, defined in sqlcc) is used for all SQL executions in this package, whether or not the requesting user is
authenticated in SAP HANA or not. The difference between the default_connection and the
anonymous_connection is that the anonymous SQL connection configuration is only used if the requesting
user is not authenticated. Like any other property of the xsaccess file, the default_connection is inherited
down the package hierarchy, for example, from package to subpackage. The default_connection can also
be overwritten, for example, by locating an xsaccess file with a different default_connection in one or
more subpackages.
Tip
If the requesting user is authenticated, the user name will be available in the connection as the
APPLICATIONUSER session variable.
The credentials to use for an SQL execution are determined according to the following order of priority:
1. The SQL connection configuration (SQLCC) specified in $.[Link](sqlcc); this applies only
in XS JavaScript (not OData, for example)
2. The value specified in default_connection (if set)
3. An authenticated user
4. The valued specified in anonymous_connection (if set)
The default_connection is intended for use with anonymous parts of the application that require the same
privileges for all users. If the anonymous part of an application is designed to behave according to the privileges
granted to authenticated users, the anonymous_connection should be used. This is particularly important if
analytic privileges are involved, for example, to restrict the amount of returned rows (not overall access to the
table). In most cases, the default_connection should be used.
authentication
{
"authentication" :
{
"method": "Form"
},
}
The authentication keyword is required in the .xsaccess file and must be set to the value "form", for
example "method" : "Form", to ensure that form-based logon works when you enable it using the SAP
HANA XS Administration Tool.
Use the SAP HANA XS Administration Tool to configure applications to use additional authentication
methods, for example, basic, logon tickets, or Single Sign On (SSO) providers such as SAML2 and X509.
You must also enable the Form-based authentication checkbox, if you want your application (or
applications) to use form-based logon as the authentication method. Any other keywords in the
authentication section of the .xsaccess file are ignored.
● Form-based authentication
Redirect the logon request to a form to fill in, for example, a Web page.
To ensure that, during the authentication process, the password is transmitted in encrypted form, it is
strongly recommended to enable SSL/HTTPS for all application connections to the XS engine, for
example, using the force_ssl keyword. If you set the force_ssl option, you must ensure that the SAP Web
Dispatcher is configured to accept and manage HTTPS requests.
Form-based authentication requires the libxsauthenticator library, which must not only be available
but also be specified in the list of trusted applications in the xsengine application container. The application
list is displayed in the SAP HANA studio's Administration Console perspective in the following location:
Administration Configuration tab [Link] application_container application_list . If it is not
displayed, ask the SAP HANA administrator to add it.
Note
If you need to troubleshoot problems with form-based logon, you can configure the generation of
useful trace information in the XSENGINE section of the database trace component using the following
entry: xsa:[Link].
authorization
{
"authorization":
[
"[Link]::Execute",
"[Link]::Admin"
],
}
The authorization keyword in the .xsaccess file enables you to specify which authorization level is
required for access to a particular application package, for example, execute or admin on the package
[Link].
Note
The authorization levels you can choose from are defined in the .xsprivileges file for the package, for
example, "execute" for basic privileges, or "admin" for administrative privileges on the specified package. If
you do not define any authorization requirements, any user can launch the application.
If you use the authorization keyword in the .xsaccess file, for example, to require “execute” privileges for
a specific application package, you must create a .xsprivileges file for the same application package (or a
parent package higher up the hierarchy, in which you define the “execute” privilege level declared in
the .xsaccess file.
{
"authorization": null
}
Bear in mind that the “authorization”:null setting applies not only to the package in which
the .xsaccess with the null setting is located but also to any subpackages further down the package
hierarchy. You can re-enable authorization in subpackage levels by creating new a .xsaccess file.
cache_control
{
"cache_control":"no-store",
}
The cache_control keyword enables you to override the cache-control header for Web content served by the
SAP HANA XS Web server. So-called cache-control directives (for example, public, private, no-store)
enable you to control the behavior of the Web browser and proxy caches, for example, whether or not to store a
page, how to store it, or where. For more information about the values you can use to set cache_control, see
the HTTP standard for cache-control directives. If no value for code_controlis set in the .xsaccess file, the
default setting is “null”.
Tip
For security reason, it is recommended to set the cache_control keyword to “no-cache, no-store”.
However, if nothing is cached or stored, there is an obvious impact on application performance.
If application performance allows, the no-cache, no-store setting is advisable for the following reasons:
{
"cors" :
{
"enabled" : false
},
}
The cors keyword enables you to provide support for cross-origin requests, for example, by allowing the
modification of the request header. Cross-origin resource sharing (CORS) permits Web pages from other
domains to make HTTP requests to your application domain, where normally such requests would
automatically be refused by the Web browser's security policy.
If CORS support is disabled ("enabled" : false), the following settings apply on the Web server:
To enable support for CORS, set the cors keyword to {“enabled”:true}, which results in the following
default corsconfiguration:
{"cors":{"enabled":true,"allowMethods":
[“GET”,”POST”,”HEAD”,”OPTIONS”],"allowOrigin": [“*”], “maxAge”:”3600”}}
The following table describes the options that are supported with the cors keyword:
{"cors":{"enabled":true, "allowMethods":<ALLOWED_METHODS>,
"allowOrigin":<ALLOWED_ORIGIN>,
“maxAge”:<MAX_AGE>, “allowHeaders”:<ALLOWED_HEADERS>,
“exposeHeaders”:<EXPOSED_HEADERS>}}
ALLOWED_METHODS A single permitted method or a comma-separated list of methods that are allowed by the
server, for example, “GET”, “POST”. If allowMethods is defined but no method is
specified, the default “GET”, “POST”, “HEAD”, “OPTIONS” (all) applies. Note
that matching is case-sensitive.
ALLOWED_ORIGIN A single host name or a comma-separated list of host names that are allowed by the
server, for example: [Link] or *.[Link]. If allowOrigin is defined but
no host is specified, the default “*” (all) applies. Note that matching is case-sensitive.
ALLOW_HEADERS A single header or a comma-separated list of request headers that are allowed by the
server. If allowHeaders is defined but no header is specified as allowed, no default
value is supplied.
MAX_AGE A single value specifying how long a preflight request should be cached for. If maxAge is
defined but no value is specified, the default time of “3600” (seconds) applies.
EXPOSE_HEADERS A single header or a comma-separated list of response headers that are allowed to be
exposed. If exposeHeaders is defined but no response header is specified for expo
sure, no default value is supplied.
default_file
{
"default_file" : "new_index.html",
}
The default_file keyword enables you to override the default setting for application access ([Link]) when
the package is accessed without providing a file in the URI. If you use the default_file but do not specify a value,
the default setting “[Link]” is assumed.
Tip
It is good practice to specify a default file name manually. Changing the default from [Link] to
something else can help make your application less vulnerable to automated hacker tools.
rewrite_rules
{
"rewrite_rules" :
[{
"source": "...",
"target": "..."
}],
}
The rewrite_rules keyword enables you hide the details of internal URL paths from external users, clients,
and search engines. Any rules specified affect the local application where the .xsaccess file resides (and any
subpackage, assuming the subpackages do not have their own .xsaccess files); it is not possible to define
global rewrite rules. URL rewrite rules are specified as a source-target pair where the source is written in the
JavaScript regex syntax and the target is a simple string where references to found groups can be inserted
using $groupnumber.
Tip
In the following example, the rule illustrated hides the filename parameter and, as a result, makes it harder to
guess that the parameter provided after /go/ will be used as a filename value. Note that it is still necessary to
validate the received input
{
"rewrite_rules" :
[{
mime_mapping
{
"mime_mapping" :
[
{
"extension":"jpg", "mimetype":"image/jpeg"
}
],
}
The mime_mapping keyword enables you to define how to map certain file suffixes to required MIME types. For
example, you can map files with the .jpg file extension to the MIME type image/jpeg.
This list you define with the mime_mapping keyword supersedes any default mapping defined by the server;
the Web browser uses the information to decide how to process the related file types.
Caution
Make sure you do not instruct the browser to execute files that are not meant to be executed, for example,
by mapping .jpg image files with the MIME type application/javascript.
The default MIME mappings remain valid for any values you do not define with the mime_mapping keyword.
Consider restricting any explicit mappings to file types where the default behavior does not work as expected
or where no default value exists, for example, for file types specific to your application.
force_ssl
{
"force_ssl" : false,
}
The force_ssl keyword enables you to refuse Web browser requests that do not use secure HTTP (SSL/
HTTPS) for client connections. If no value is set for force_ssl, the default setting (false) applies and non-
secured connections (HTTP) are allowed.
Tip
To ensure that, during the authentication process, passwords are transmitted in encrypted form, it is
strongly recommended to enable SSL/HTTPS for all application connections to the XS engine. If you set
the force_ssl option, you must ensure that the SAP Web Dispatcher is configured to accept and manage
HTTPS requests. For more information, see the SAP HANA XS section of the SAP HANA Administration
Guide.
Caution
If a runtime configuration exists for your application, the force_ssl setting in the runtime configuration
supersedes the force_ssl in the .xsaccess.
enable_etags
{
"enable_etags" : true,
}
You can allow or prevent the generation of entity tags (etags) for static Web content using the enable_etags
keyword. If no value is set, the default setting (true) applies, in which case etags are generated. Etags are used
to improve caching performance, for example, so that the same data is not resent from the server if no change
has occurred since the last time a request for the same data was made.
If etags are enabled, the browser sends with each HTTP request the etag retrieved from its cached page. If the
etag from the cached page matches the etag from the server, the server answers with the status code 304 (not
modified) and does send the full requested page. Although enabling etags has the positive side-effect of
helping to prevent cache poisoning attacks, there is no direct security risk associated with disabling etags from
the developer's perspective.
prevent_xsrf
{
"prevent_xsrf" : true,
}
You can use the prevent_xsrf keyword in the .xsaccess file to protect applications from cross-site request-
forgery (XSRF) attacks. XSRF attacks attempt to trick a user into clicking a specific hyperlink, which shows a
(usually well-known) Web site and performs some actions on the user’s behalf, for example, in a hidden iframe.
If the targeted end user is logged in and browsing using an administrator account, the XSRF attack can
compromise the entire Web application. There is no good reason why you would explicitly set this keyword to
false.
Note
It is recommended to enable the prevent_xsrf feature for all applications that are not read-only.
The prevent_xsrf keyword prevents the XSRF attacks by ensuring that checks are performed to establish
that a valid security token is available for a given Browser session. The existence of a valid security token
Note
The default setting is false, which means there is no automatic prevention of XSRF attacks. If no value is
assigned to the prevent_xsrf keyword, the default setting (false) applies.
Setting the prevent_xsrf keyword to true ensures XSRF protection only on the server side. On the client
side, to include the XSRF token in the HTTP headers, you must first fetch the token as part of a GET request, as
illustrated in the following example:
[Link]("X-CSRF-Token", "Fetch");
You can use the fetched XSRF token in subsequent POST requests, as illustrated in the following code example:
[Link]("X-CSRF-Token", xsrf_token);
headers
{
"headers":
{
"enabled": true,
"customHeaders": [ {"name":"X-Frame-Options","value":"<VALUE>"} ]
}
}
Enable support for the X-Frame-Options HTTP header field, which allows the server to instruct the client
browser whether or not to display transmitted content in frames that are part of other Web pages. You can also
enable this setting in the application's corresponding runtime configuration file, for example, using the XS
Administration Tool.
Caution
● DENY
● SAMEORIGIN
● ALLOW-FROM <URL>
You can only specify one URL with the ALLOW-FROM option, for example: "value":"ALLOW-FROM
[Link]
Note
To allow an application to use custom headers, you must enable the headers section.
Rewriting URLs enables you to hide internal URL path details from external users, clients, and search engines.
You define URL rewrite rules in the application-access file (.xsaccess) for each application or for an
application hierarchy (an application package and its subpackages).
The rewrite rules you define in the .xsaccess file apply only to the local application to which the .xsaccess
file belongs; it is not possible to define global rules to rewrite URLs. Rules are specified as a source-target pair
where the source is written in the JavaScript regex syntax, and the target is a simple string where references
to found groups can be inserted using $groupnumber.
The following examples show how to use a simple set of rewrite rules to hide internal URLs from requesting
clients and users.
The first example illustrates the package structure that exists in the repository for a given application; the
structure includes the base package apptest, the subpackages subpackage1 and subpackage2, and several
other subpackages:
sap---apptest
|---logic
| |---[Link]
| |---[Link]
|---posts
| |---2011...
|---subpackage1
| |---[Link]
|---subpackage2
| |---subsubpackage
| | |---[Link]
| |---[Link]
|---subpackage3
| |---[Link]
|---users
| |---123...
|---.xsapp
|---.xsaccess
|---[Link]
The application-access file for the package apptest (and its subpackages) includes the following rules for
rewriting URLs used in client requests:
{
"rewrite_rules": [
{
"source": "/users/(\\d+)/",
"target": "/logic/[Link]?id=$1"
},
{
"source": "/posts/(\\d+)/(\\d+)/(\\d+)/",
"target": "/logic/[Link]?year=$1&month=$2&day=$3"
}
Assuming we have the package structure and URL rewrite rules illustrated in the previous examples, the
following valid URLs would be exposed; bold URLs require authentication:
/sap/apptest/
/sap/apptest/[Link]
/sap/apptest/logic/[Link]
/sap/apptest/logic/[Link]
The application-privileges (.xsprivileges) file enables you to define the authorization levels required for
access to an application, for example, to start the application or perform administrative actions on an
application. You can assign the application privileges to the individual users who require them.
Prerequisites
Note
The namespace sap is restricted. Place the new package in your own namespace, for example,
[Link], which you can create alongside the sap namespace.
Context
The .xsprivileges file must reside in the same application package that you want to define the access
privileges for.
Note
If you use the .xsprivileges file to define application-specific privileges, you must also add a
corresponding entry to the same application's .xsaccess file, for example, using the authorization
keyword.
1. Create the application-privileges (.xsprivileges) file and place it in the application package whose
access privileges you want to define.
The application-privileges file does not have a name; it only has the file extension .xsprivileges. The
contents of the .xsprivileges file must be formatted according to JavaScript Object Notation (JSON)
rules.
Note
Multiple .xsprivileges files are allowed, but only at different levels in the package hierarchy; you
cannot place two .xsprivileges files in the same application package. The privileges defined in
a .xsprivileges file are bound to the package to which the file belongs and can only be applied to
this package and its subpackages.
a. In the SAP HANA studio and open the SAP HANA Development perspective.
b. In the Project Explorer view, right-click the folder where you want to create the new (.xsprivileges)
file.
c. In the context-sensitive popup menu, choose New Other... .
d. In the Select a Wizard dialog, choose SAP HANA Application Development XS Application
Privileges File
e. Enter or select the parent folder, where the application-privileges file is to be located.
f. Enter a name for the application-privileges file.
Tip
If you are using the SAP HANA Studio to create artifacts in the SAP HANA Repository, the file
creation wizard adds the required file extension .xsprivileges automatically and enables direct
editing of the file.
g. Select a template to use. Templates contain sample source code to help you.
h. Choose Finish.
i. Activate the new (.xsprivileges) file.
2. Define the required application privileges.
In the .xsprivileges file, you define a privilege for an application package by specifying an entry name
with an optional description. This entry name is then automatically prefixed with the package name in
which the .xsprivileges file is located to form a unique privilege name. For example,
[Link]::Execute would enable execute privileges on the package [Link]. The
privilege name is unique to the package to which it belongs and, as a result, can be used in
multiple .xsprivileges files in different packages.
Note
The .xsprivileges file lists the authorization levels defined for an application package. A
corresponding entry is required in the same application's access file .xsaccess file to define which
authorization level is assigned to which application package.
3. Specify which privileges are required for access to the application or application package.
If you use the .xsprivileges file to define application-specific privileges, you must also add a
corresponding entry to the same application's .xsaccess file, for example, using the authorization
keyword.
Note
The .xsprivileges file lists the authorization levels that are available for access to an application
package; the .xsaccess file defines which authorization level is assigned to which application
package.
a. Locate and open the XS application access file (.xsaccess) for the application for which you want to
define application privileges.
b. Specify the privileges required for access to the application or application package.
Use the authorization keyword in the .xsaccess file to specify which authorization level is required by
a user for access to a particular application package.
Note
If you enable the authorization keyword in the .xsaccess file, you must add a corresponding entry
to the .xsprivileges file, too.
{
"exposed" : true,
"authentication" :
[
{ "method" : "Form" }
],
"authorization":
[
"[Link]::Execute",
"[Link]::Admin"
]
}
call
"_SYS_REPO"."GRANT_APPLICATION_PRIVILEGE"('"[Link]::Execute"','<UserNa
me>')
To revoke the execute application privilege to a user, run the following command in the SAP HANA
studio's SQL Console:
call
"_SYS_REPO"."REVOKE_APPLICATION_PRIVILEGE"('"[Link]::Execute"','<UserN
ame>')
Related Information
In SAP HANA Extended Application Services (SAP HANA XS), the application-privileges (.xsprivileges) file
can be used to create or define the authorization privileges required for access to an SAP HANA XS application,
for example, to start the application or to perform administrative actions on an application. These privileges
can be checked by an application at runtime.
The application-privileges file has only the file extension .xsprivileges; it does not have a name and is
formatted according to JSON rules. Multiple .xsprivileges files are allowed, but only at different levels in
the package hierarchy; you cannot place two .xsprivileges files in the same application package. The
package privileges defined in a .xsprivileges file are bound to the package to which the .xsprivileges
file belongs and can only be used in this package and its subpackages.
Inside the .xsprivileges file, a privilege is defined by specifying an entry name with an optional description.
This entry name is then automatically prefixed with the package name to form the unique privilege name, for
example, [Link]::Execute.
As an application privilege is created during activation of an .xsprivileges file, the only user who has the
privilege by default is the _SYS_REPO user. To grant or revoke the privilege to (or from) other users you can use
the GRANT_APPLICATION_PRIVILEGE or REVOKE_APPLICATION_PRIVILEGE procedure in the _SYS_REPO
schema.
Note
The .xsprivileges file lists the authorization levels that are available for access to an application
package; the .xsaccess file defines which authorization level is assigned to which application package.
● [Link]::Execute
● [Link]::Admin
The privileges defined apply to the package where the .xsprivileges file is located as well as any packages
further down the package hierarchy unless an additional .xsprivileges file is present, for example, in a
subpackage. The privileges do not apply to packages that are not in the specified package path, for example,
[Link].app1.
Example:
The SAP HANA XS Application-Privileges File
The following example shows the composition and structure of a basic SAP HANA XS application-privileges file.
{
"privileges" :
[
{ "name" : "Execute", "description" : "Basic execution
privilege" },
{ "name" : "Admin", "description" : "Administration privilege" }
]
}
If the .xsprivileges file shown in the example above is located in the package [Link], you can
assign the Execute privilege for the package to a particular user by calling the
GRANT_APPLICATION_PRIVILEGE procedure, as illustrated in the following code:
call "_SYS_REPO"."GRANT_APPLICATION_PRIVILEGE"('"[Link]::Execute"',
'<user>')
As part of the application-development process, you must decide how to provide access to the applications you
develop. Application access includes security-related matters such as authentication methods and
communication protocols
In addition to the features and functions you can enable with keywords in the .xsaccess file, SAP HANA
Extended Application Services (SAP HANA XS) provides a dedicated SAP HANA XS administration tool that is
designed to help you configure and maintain the authentication mechanism used to control access to the
applications you develop. The SAP HANA XS Administration Tool enables you to configure the following runtime
elements for an application:
● Security
Choose the security level you want to set to provide access to the application. For example, you can expose
the application with/without requiring authentication (public/private) and force the application to accept
only requests that use SSL/HTTPS.
Related Information
To restrict access to the applications you develop, you must configure the application to work with particular
authentication methods and communication protocols.
Prerequisites
To perform the steps in this task, you must ensure the following prerequisites are met:
Context
You must specify whether or not to expose application content, which authentication method is used to grant
access to the exposed content, and what content is visible.
Procedure
Note
In the default configuration, the URL redirects the request to a logon screen, which requires the
credentials of an authenticated SAP HANA database user to complete the logon process. To ensure
Note
Security settings are automatically inherited by applications further down the application hierarchy.
However, you can override the inherited security settings at any application level by modifying the
settings for a particular application. Applications below the application with the modified security
settings inherit the new, modified settings.
a. Use the Public (no authentication required) option to specify if applications require user authentication
to start.
○ Disabled
This is the default setting. In disabled mode, Form-based authentication and Basic authentication
options are enabled automatically in the Authentication screen area.
○ Enabled
If you enable the Public option , no authentication is required to start an application; the
Authentication screen area is hidden, and you cannot select any authentication-method options.
b. Use the Force SSL option to specify if client requests must use secure HTTP (HTTPS).
○ Disabled
This is the default setting. With Force SSL disabled, the application returns a response to all
requests (both HTTP and HTTPS).
○ Enabled
If you enable the Force SSL option , requests from browsers using standard HTTP are refused.
Note
Enabling the Force SSL option only ensures that the selected application refuses any request
that does not use HTTPS; it does not set up the Secure Sockets Layer (SSL) protocol for you.
The SAP HANA administrator must configure the SAP Web Dispatcher to accept (and forward)
HTTPS requests in addition.
Related Information
You can set some basic security options to increase the security of the applications you develop for SAP HANA.
SAP HANA Extended Application Services (SAP HANA XS) provides a dedicated tool, the SAP HANA XS
Administration Tool, that is designed to help you configure and maintain some of the basic aspects of runtime
security relating to the applications you develop. For example, you can use the SAP HANA XS Administration
Tool to specify if the applications you develop are publicly available for anyone to start, or if the applications can
only be started by an authenticated user.
You can use the SAP HANA XS Administration Tool to set the following security-related options for the
application you develop for SAP HANA XS:
Note
If you enable the Public option in the application Security screen area, no authentication is required to
start an application; the Authentication screen area is hidden, and you cannot select any
authentication-method options.
● Force SSL
The force SSL option enables you to refuse Web browser requests that do not use secure HTTP (SSL/
HTTPS) for client connections. If no value is set for force_ssl, the default setting (false) applies and non-
secured connections (HTTP) are allowed.
Related Information
To restrict access to the applications you develop, you must configure the application to work with particular
authentication methods and communication protocols.
Prerequisites
To perform the steps in this task, you must ensure the following prerequisites are met:
Context
Before you define which authentication methods an application uses to grant access to the application content,
you must use the application security tools to define whether or not to expose application content and, if so,
which content to expose. SAP HANA XS enables you to define multiple authentication methods to verify the
credentials of users who request access to the exposed content; multiple authentication methods are
considered according to a specific order of priority. For example, if the first authentication method fails, SAP
HANA tries to authenticate the user with the next authentication method specified. To configure the
authentication method an application uses to verify user credentials, perform the following steps:
Procedure
Note
In the default configuration, the URL redirects the request to a logon screen, which requires the
credentials of an authenticated SAP HANA database user to complete the logon process. To ensure
access to all necessary features, the user who logs on should have the SAP HANA XS role
[Link]::RuntimeConfAdministrator.
Note
Security settings are automatically inherited by applications further down the application hierarchy.
However, you can override the inherited security settings at any application level by modifying the
settings for a particular application. Applications below the application with the modified security
settings inherit the new, modified settings.
a. Use the Public (no authentication required) option to specify if applications require user authentication
to start.
○ Disabled
This is the default setting. In disabled mode, Form-based authentication and Basic authentication
options are enabled automatically in the Authentication screen area.
○ Enabled
If you enable the Public option , no authentication is required to start an application; the
Authentication screen area is hidden, and you cannot select any authentication-method options.
Note
Enabling the Force SSL option only ensures that the selected application refuses any request
that does not use HTTPS; it does not set up the Secure Sockets Layer (SSL) protocol for you.
The SAP HANA administrator must configure the SAP Web Dispatcher to accept (and forward)
HTTPS requests in addition.
Note
Enabling an application-security option (for example, SAML2 or X509) only ensures that the selected
application uses the enabled authentication method when required; it does not perform any setup
operation for the authentication method itself. The SAP HANA administrator must maintain the
selected authentication infrastructure (SAML2, X509, or SAP logon tickets) in an additional step.
You can choose any selection of the following application-related authentication methods; if you enable
multiple authentication methods for your application, a priority applies depending on whether the
application logon is interactive or non-interactive:
a. Enable the SAML2 option.
The SAP HANA administrator must already have configured the authentication infrastructure, for
example, to enable the creation of SAML2 assertions to permit SSO in Web browsers.
b. Enable the X509 Authentication option
The SAP HANA administrator must already have configured the appropriate authentication
infrastructure, for example, to enable users to be authenticated by client certificates signed by a
trusted Certification Authority (CA).
c. Enable the SAP logon ticket option
The SAP HANA administrator must already have configured the appropriate authentication
infrastructure, for example, to enable users to be be authenticated by a logon ticket that is issued when
the same user logs on to an SAP system that is configured to create logon tickets (for example, the
SAP Web Application Server or Portal).
d. Enable the Form-based authentication option
If the Public security option is disabled, the Form-based authentication option is enabled by default.
e. Enable the Basic authentication option
If the Public security option is disabled, the Basic authentication option is enabled by default.
The authentication method determines whether or not authentication is required to access an application, and
if required, which authentication methods must be used.
SAP HANA Extended Application Services (SAP HANA XS) provides a dedicated tool, the SAP HANA XS
Administration Tool, that is designed to help you configure and maintain the authentication mechanism used to
control runtime access to the applications you develop. The authentication method you select for access to
your application depends on which authentication methods are supported by SAP HANA and whether or not
your system administrator has configured the authentication method in the system backend.
You can use the SAP HANA XS Administration Tool to configure applications running in SAP HANA XS to use the
following authentication mechanisms:
● SAML2
Choose this option if you have configured SAML2 assertions to enable SSO in Web browsers. SAML2 is
version 2 of the Security Assertion Markup Language (SAML), which enables Web-based authentication
including single sign-on across domains.
Note
The user who connects to the database using an external authentication provider must also have a
database user known to the database. SAP HANA maps the external identity to the identity of the
internal database user.
● SPNego
Choose this option if you want to SAP HANA XS applications to use Simple and Protected GSSAPI
Negotiation Mechanism (SPNego) for authentication by means of Kerberos for Web-based (HTTP) access.
● X509 Authentication
X.509 client certificates For secure HTTP (HTTPS) access to SAP HANA XS applications, users can be
authenticated by client certificates signed by a trusted Certification Authority (CA), which can be stored in
the SAP HANA XS trust store.
● SAP logon ticket
For HTTPS access to SAP HANA XS applications, a user can be authenticated by a logon ticket that is
issued when the same user logs on to an SAP system that is configured to create logon tickets (for
example, the SAP Web Application Server or Portal).
To configure the trust relationship between the issuer of the SAP logon ticket and SAP HANA, you must
specify the path to the SAP logon ticket trust store, which contains the trust chain for the ticket issuer. You
can use the SapLogonTicketTrustStore keyword in the [Link] file. Default values are: $SECUDIR/
[Link] or $HOME/.ssl/[Link].
SAP HANA XS does not issue SAP logon tickets; it only accepts them. Since the tickets usually reside in
a cookie, the issuer and SAP HANA XS need to be in the same domain to make sure that your browser
sends the SAP logon ticket cookie with each call to SAP HANA XS.
● Form-based authentication
This option is used if interactive logon is desired. With form-based authentication, the logon request is
redirected to a form to fill in, for example, displayed in Web page. The Form-based authentication option is
enabled by default if the Public option is disabled in the application Security screen area.
Note
You must also enable the Form-based authentication in the .xsaccess file, if you want your application
(or applications) to use form-based logon as the authentication method. Note that any other keywords
in the authentication section of the .xsaccess file are ignored.
Form-based authentication requires the libxsauthenticator library, which must not only be available
but also be specified in the list of trusted applications in the xsengine application container. The application
list is displayed in the SAP HANA studio's Administration Console perspective in the following location:
Administration Configuration tab [Link] application_container application_list . If it is not
displayed, ask the SAP HANA administrator to add it.
Tip
If you need to troubleshoot problems with form-based authentication, you can configure the
generation of useful trace information in the XSENGINE section of the database trace component using
the following entry: xsa:[Link].
● Basic authentication
Logon with a recognized database user name and password. This option is used if non-interactive logon is
desired. The Basic authentication option is enabled by default if the Public option is disabled in the
application Security screen area.
The authentication configuration enables you to define the authentication methods to use for Browser requests
either at the application level or for single packages in an application.
Note
The authentication mechanism set at the root of the application/package hierarchy is inherited by
applications further down the application hierarchy.
By default, the Public option in the application Security screen area is disabled and the Form-based
authentication and Basic authentication options are enabled automatically in the Authentication screen area.
However, you can disable both form-based and basic authentication and enable other, additional
authentication methods (for example, SAP logon tickets or X509 authentication). If multiple authentication
methods are enabled, SAP HANA XS enforces the following order of priority:
If you enable the Public option in the application Security screen area, no authentication is required to start an
application; the Authentication screen area is hidden, and you cannot select any authentication-method
options.
Related Information
An HTTP destination defines connection details for services running on specific hosts whose details you want
to define and distribute. The definition can be referenced by an application.
Context
If you want to configure an SAP HANA XS application to access data on a specific server that offers a specific
service, for example, a service that is only available outside your network, it is recommended to configure the
HTTP connection parameters in an HTTP destination file that you store locally as a design-time artifact. You
can use an HTTP destination to call an external resource directly from a server-side JavaScript application. You
can also use an HTTP destination when configuring a transport route, for example, to automate the process of
exporting a delivery unit from one system and importing it into another. To create an HTTP destination
configuration for an SAP HANA XS application, you must perform the following high-level steps.
Procedure
1. Create a package for the SAP HANA XS application that will use the HTTP destination you define.
2. Define the details of the HTTP destination.
You define the details of an HTTP destination in a configuration file and using a specific syntax. The
configuration file containing the details of the HTTP destination must have the file extension .xshttpdest
and be located in the same package as the application that uses it or one of the application's subpackages.
3. Define any extensions to the HTTP destination configuration.
You can extend a configured HTTP destination, for example, by providing additional details concerning
proxy servers and logon details. The details concerning the extensions to the HTTP destination must be
Note
Access to details of HTTP destinations in the SAP HANA XS Administration Tool requires the
credentials of an authenticated database user and one of the following SAP HANA roles:
○ HTTPDestViewer
○ HTTPDestAdministrator
Related Information
Create an HTTP destination defining connection details for services running on specific hosts. The definition
can be referenced by an application.
Prerequisites
Since the artifacts required to create a simple HTTP destination are stored in the repository, it is assumed that
you have already performed the following tasks:
An HTTP destination defines connection details for services running on specific hosts whose details you want
to define and distribute. The definition can be referenced by an application. You can also provide more (or
modified) connection details in additional files called “extensions”; values specified in extensions overwrite
values specified in the original HTTP destination configuration.
Note
HTTP destinations configurations are defined in a text file; you can use the editing tools provided with SAP
HANA studio or your favorite text editor.
Procedure
1. Create a package for the SAP HANA XS application that will use the HTTP destination you define in this
tutorial.
For example, create a package called testApp. Make sure you can write to the schema where you create
the new application.
a. Start the SAP HANA studio and open the SAP HANA Development perspective.
b. In the Systems view, right-click the node in the package hierarchy where you want to create the new
package and, in the pop-up menu that displays, choose Packages...
c. In the New Package dialog that displays, enter the details of the new package (testApp) that you want
to add and click OK.
2. Define the details of the HTTP destination.
You define the details of an HTTP destination in a configuration file that requires a specific syntax. The
configuration file containing the details of the HTTP destination must have the file
extension .xshttpdest. If you are using SAP HANA Studio to create artifacts in the SAP HANA
Repository, the file creation wizard adds the required file extension automatically and enables direct
editing of the file.
Caution
You must place the HTTP destination configuration and the XSJS application that uses it in the same
application package. An application cannot reference an HTTP destination configuration that is located
in another application package.
host = "[Link]";
port = 80;
description = "my stock-price checker";
useSSL = false;
pathPrefix = "/d/[Link]?f=a";
authType = none;
useProxy = false;
proxyHost = "";
proxyPort = 0;
timeout = 0;
Note
Saving a file in a shared project automatically commits the saved version of the file to the
repository, To explicitly commit a file to the repository, right-click the file (or the project containing
the file) and choose Team Commit from the context-sensitive popup menu.
Note
To make changes to the HTTP Destination configuration, you must use a text editor, save the changes
and reactivate the file.
Tip
Access to details of HTTP destinations in the SAP HANA XS Administration Tool requires the
credentials of an authenticated database user and the permissions granted by the following SAP
HANA roles:
○ RuntimeConfAdministrator
○ HTTPDestAdministrator
b. In the XS Artifact Administration tab, expand the nodes in the Application Objects tree to locate the
application testApp.
c. Choose [Link] to display details of the HTTP destination.
If you are using the Web-based XS Administration Tool, you can only make limited changes to the
displayed HTTP destination configuration, as follows:
○ Save
Commit to the repository any modifications made to the HTTP destination configuration in the
current session.
○ Edit
Display details of the corresponding extension to the selected HTTP destination configuration. If
no extension exists, the Edit option is not available.
○ Extend
Enables you to create an extension to the selected XS HTTP destination and associate the
extension with another (new or existing) package.
Note
This option is only available if the selected HTTP destination is provided as part of an delivery
unit, for example, as a destination template.
An HTTP destination defines connection details for services running on specific hosts whose details you want
to define and distribute. The definition can be referenced by an application.
You use the HTTP destination file to define not only the details of the host you want an application to reach by
means of HTTP but also any further details that are necessary to establish the connection, for example, any
proxy settings. If necessary, the proxy settings can also be defined in a separate, so-called "extension file". Both
the configuration file you use to define an HTTP destination and the file used to specify any extensions to the
HTTP destination are text files that must have the suffix .xshttpdest, for example,
[Link] or [Link].
Note
For security reasons, the HTTP destination configuration and the XSJS application that uses it must be in
the same application package or one of the application's subpackages. An application cannot reference an
HTTP destination configuration that is located in a different application package structure.
You configure an HTTP destination in a text file that contains the details of the connection to the HTTP
destination, using a mandatory syntax comprising a list of keyword=value pairs, for example, host =
"[Link]";. After creating and saving the HTTP destination, you must activate it in
the SAP HANA repository.
Note
Saving a file in a shared project automatically commits the saved version of the file to the repository, To
explicitly commit a file to the repository, right-click the file (or the project containing the file) and choose
Team Commit from the context-sensitive popup menu.
The following configuration file for the HTTP destination [Link] illustrates how to define an
HTTP destination that can be used to access a financial service running on an external host.
host = "[Link]";
port = 80;
description = "my stock-price checker";
useSSL = false;
pathPrefix = "/d/[Link]?f=a";
authType = none;
proxyType = none;
proxyHost = "";
proxyPort = 0;
timeout = 0;
After activating the configuration in the SAP HANA repository, you can view the details of the new HTTP
destination using the SAP HANA XS Administration Tool.
Access to details of HTTP destinations in the SAP HANA XS Administration Tool requires the credentials of
an authenticated database user and one of the following SAP HANA roles:
● HTTPDestViewer
● HTTPDestAdministrator
If you are using the Web-based XS Administration Tool, you can only make limited changes to the displayed
HTTP destination configuration, as follows:
● Save:
Commit to the repository any modifications made to the HTTP destination configuration in the current
session.
● Edit:
Display details of the corresponding extension to the selected HTTP destination configuration. If no
extension exists, the Edit option is not available.
● Extend:
Enables you to create an extension to the selected XS HTTP destination and associate the extension with
another (new or existing) package.
Note
This option is only available if the selected HTTP destination is provided as part of an delivery unit, for
example, as a destination template.
Related Information
An HTTP destination defines connection details for services running on specific hosts whose details you want
to define and distribute. Syntax rules apply to the contents of the HTTP destination configuration are checked
when you activate the configuration in the repository.
Example:
The .xshttpdest Configuration File
The following example shows all possible keyword combinations in the SAP HANA XS application-access
(.xshttpdest) file.
In the form shown below, the .xshttpdest file is not a working model; it is used to illustrate the syntax for
all possible options.
host = "[Link]";
port = 80;
//All of the following keywords are optional
description = "";
useSSL = false;
sslAuth = client;
sslHostCheck = true;
pathPrefix = "/d/[Link]?f=a";
authType = none;
samlProvider = "";
samlACS = "header";
samlAttributes = "";
samlNameId = ["email"];
proxyType = none;
proxyHost = ""; //in-line comments are allowed
proxyPort = 0;
timeout = 0;
remoteSID = "Q7E";
remoteClient = "007";
oAuthAppConfigPackage = "[Link]";
oAuthAppConfig = "abapTest";
When you are defining the HTTP destination, bear in mind the following important syntax rules:
● A semi-colon (;) is required at the end of each line in the HTTP destination configuration, including the last
line in the file.
● String values must be wrapped in quotes (""), for example:
host = "[Link]";
Note
The host and port keywords are mandatory; all other keywords are optional.
host
host = "[Link]";
The host keyword is mandatory: it enables you to specify the hostname of the HTTP destination providing the
service or data you want your SAP HANA XS application to access.
port
port = 80;
The port keyword is mandatory; it enables you to specify the port number to use for connections to the HTTP
destination hosting the service or data you want your SAP HANA XS application to access.
The optional keyword description enables you to provide a short description of the HTTP destination you want
to configure. If you do not want to provide a description, include the description but leave the entry between the
quotes empty, for example, “”.
useSSL
The optional keyword useSSL is of type Boolean and enables you to specify if the outbound connections
between SAP HANA XS and the HTTP destination is secured with the Secure Sockets Layer (SSL) protocol
(HTTPS).
Note
Setting this option does not configure SSL; if you want to use SSL to secure connections to the configured
destination, you must ensure that SAP HANA is already set up to enable secure outbound connections
using SSL.
If useSSL = true, you can set the authentication type with the keyword sslAuth. You can also use the
sslHostCheck to enable a check which ensures that the certificate used for authentication is valid (matches
the host).
sslAuth
If useSSL = true, you can use the keyword sslAuth to set the authentication type. The following values are
permitted:
● client
(Default setting). You must create a TRUST store entry in the SAP HANA XS Admin Tool's Trust manager (or
use an existing one that is known to the HTTP destination configuration) and maintain the trust
relationship with the SSL server, for example, by adding a certificate to the trust store that is used for the
authentication process.
● anonymous
A built-in key is used for SSL encryption; no TRUST store is needed.. No authentication via SSL is possible.
If useSSL = true, you can use the keyword sslHostCheck to enable a check which ensures that the
certificate used for authentication is valid (matches the host). The following values are permitted:
● true
(Default setting). The SSL certificate subject must match the host name. For example, if SSL server
certificate CN=[Link], then the host parameter must be [Link]. If there is no
match, SSL terminates.
● false
No host check is performed. Note that if the SSL server certificate is CN=[Link], and you use
“localhost” as a connection parameter (because this certificate is installed on its own server), then this
works with sslHostCheck deactivated (sslHostCheck=false).
pathPrefix
pathPrefix = "";
The optional keyword pathPrefix enables you to specify a text element to add to the start of the URL used for
connections to the service specified in the HTTP destination configuration. For example, pathPrefix = "/d/
[Link]?f=a" inserts the specified path into the URL called by the connection.
authType
The optional keyword authType enables you to specify the authentication method that must be used for
connection requests for the service located at the HTTP destination specified in the configuration, for example,
“basic”, which requires users to provide a user name and password as authentication credentials. Permitted
values for the authType are “none”, “basic”, and “AssertionTicket”. If no authentication type is specified, the
default setting “none” applies.
The AssertionTicket option is for use with XSJS applications that want to enable access to HTTP services
running on remote SAP servers using single sign-on (SSO) with SAP assertion tickets. If the AssertionTicket
option is enabled, a user with administration privileges in SAP HANA must use the parameter
saplogontickettruststore to specify the location of the trust store containing the assertion tickets.
Tip
For authType = SamlAssertion;, you must also set the subproperties samlProvider, samlACS,
samlAttributes, and samlNameId.
samlProvider
samlProvider = "";
If you set authType = SamlAssertion, you must also set the subproperty samlProvider, which enables
you to specify the entityID of the remote SAML party.
samlACS
samlACS = "header";
If you set authType = SamlAssertion, you must also set the subproperty samlACS, which enables you to
specify the way in which SAML assertions or responses are sent. The following values are supported:
samlAttributes
samlAttributes = "name1=<property>&name2=<property>";
If you set authType = SamlAssertion, you must also set the subproperty samlAttributes, which enables
you to specify additional attributes for the SAML Assertion.
If you set authType = SamlAssertion, you must also set the subproperty samlNameId, which enables you
to define a list of name-ID mappings. The following values are supported:
● email
● unspecified
For example, if you have an e-mail maintained in SAP HANA User Self Services (USS), the SAML assertion
contains your e-mail address; if you do not have a e-mail address maintained in SAP HANA USS, the mapping
is “unspecified”.
proxyType
proxytype = none;
The optional keyword proxyType enables you to specify if a proxy server must be used to resolve the host name
specified in the HTTP destination configuration file, and if so, which type of proxy. The following values are
allowed:
● none
● http
● socks
Caution
proxyType replaces and extends the functionality previously provided with the keyword useProxy. For
backward compatibility, the useProxy is still allowed but should not be used any more.
To define the proxy host and the port to connect on, use the keywords proxyHost and proxyPort
respectively.
If you want to include the proxy-related information in a separate configuration (a so-called extension to the
original HTTP destination configuration), you must set proxyType = none in the original HTTP destination
configuration. In the HTTP destination extension that references and modifies the original HTTP destination,
you can change the proxy setting to proxyType = http. You must then provide the corresponding host name
of the proxy server and a port number to use for connections.
proxyHost
proxyHost = "";
If you use the keyword useProxy = true to specify that a proxy server must be used to resolve the target
host name specified in the HTTP destination configuration, you must use the proxyHost and proxyPort
proxyHost = "[Link]"
proxyPort
proxyPort = 8080;
If you use the keyword useProxy = true to indicate that a proxy server must be used to resolve the host
name specified in the HTTP destination configuration, you must also use the proxyPort keyword (in
combination with proxyHost =) to specify the port on which the proxy server accepts connections.
timeout
timeout = -1;
The optional keyword timeout enables you to specify for how long (in milliseconds) an application tries to
connect to the remote host specified in the HTTP destination configuration, for example, timeout = 5000;
(5 seconds). By default, the timeout interval is set to -1, which means that there is no limit to the time required
to connect to the server specified in the HTTP destination configuration. In the default setting, the application
keeps trying to connect to the destination server either until the server responds, however long this takes, or
the underlying request-session timeout (300 seconds) is reached. The default setting (-1) is intended to help in
situations where the destination server is slow to respond, for example, due to high load.
remoteSID
remoteSID = "Q7E";
The optional keyword remoteSID enables you to specify the SID of a remote ABAP system. You use this
keyword in combination with the remoteClient keyword, for example, to enable an application to log on to an
ABAP system that is configured to provide SAP assertion tickets. If the XSJS application service requires
access to remote services, you can create an HTTP destination that defines the logon details required by the
remote ABAP system and specifies SSO with SAP assertion tickets as the logon authentication method.
Note
In the XS Administration Tool, the value specified in an HTTP destination configuration file with the
remoteSID keyword is displayed in the SAP SID field in the AUTHENTICATION section of the application's
runtime configuration. The SAP SID option is only available if you select SAP Assertion Ticket as the
authentication type in the application's runtime configuration.
remoteClient = "007";
The optional keyword remoteClient enables you to specify the client number to use when logging on to a
remote ABAP system. You use this keyword in combination with the remoteSID keyword, for example, to
enable an application to logon to an ABAP system that is configured to provide SAP assertion tickets. If the
XSJS application service requires access to remote services, you can create an HTTP destination that defines
the logon details required by the remote ABAP system and specifies SSO with SAP assertion tickets as the
logon authentication method.
Note
In the XS Administration Tool, the value specified in an HTTP destination configuration file with the
remoteClient keyword is displayed in the SAP Client field in the AUTHENTICATION section of the
application's runtime configuration. The SAP Client option is only available if you select SAP Assertion
Ticket as the authentication type in the application's runtime configuration.
oAuthAppConfigPackage
oAuthAppConfigPackage = "[Link]";
Use the optional keyword oAuthAppConfigPackage enables you to specify the location of the package that
contains the oAuth application configuration to be used by an HTTP destination configuration.
oAuthAppConfig
oAuthAppConfig = "abapTest";
Use the optional keyword oAuthAppConfig enables you to specify the name of the oAuth application
configuration to be used by an HTTP destination configuration. The OAuth application configuration is a file
describing the application-specific OAuth parameters that are used to enable access to a resource running on a
remote HTTP destination. The OAuth application configuration is defined in a design-time artifact with the
mandatory file suffix .xsoauthappconfig; the configuration file must be specified using the JSON format.
modifies
modifies [Link]:[Link];
The keyword modifies can only be used in an HTTP extension file and enables you to reference an existing
HTTP destination (or extension) whose settings you want to further extend or modify. The settings in an HTTP
Note
The HTTP destination extension does not have to be tied to a particular XSJS application; it can be located
in any application package or subpackage. For this reason, you must include the full package path to the
HTTP destination extension when using the modifies keyword.
Related Information
Extend an HTTP destination defining connection details for services running on specific hosts, for example, by
providing additional details. The definition and the extension details can be referenced by an application.
Prerequisites
Since the artifacts required to create an HTTP destination extension are stored in the repository, it is assumed
that you have already performed the following tasks:
Note
This tutorial shows you how to modify an HTTP destination by providing details of a proxy server that must
be used to resolve host names specified in the connection details; you must supply the name of a working
proxy server that is available in your environment.
Context
An HTTP destination defines connection details for services running on specific hosts whose details you want
to define and distribute. The definition can be referenced by an application. You can also provide more (or
Note
HTTP destinations configurations and any extensions are defined in a plain-text file; you can use the editing
tools provided with SAP HANA studio or your favorite text editor to add entries to the configuration file.
Procedure
1. Create a package for the SAP HANA XS application that will use the HTTP destination (and extension) you
define in this tutorial.
For example, create a package called testApp. Make sure you can write to the schema where you create
the new application.
a. Start the SAP HANA studio and open the SAP HANA Development perspective.
b. In the Systems view, right-click the node in the package hierarchy where you want to create the new
package and, in the pop-up menu that displays, choose Packages...
c. In the New Package dialog that displays, enter the details of the new package (testApp) that you want
to add and click OK.
2. Define the details of the new HTTP destination.
You define the details of an HTTP destination in a configuration file that requires a specific syntax. The
configuration file containing the details of the HTTP destination must have the file
extension .xshttpdest.
Caution
You must place the HTTP destination configuration in the application package that uses it. An
application cannot reference an HTTP destination configuration that is located in another application
package.
host = "[Link]";
port = 80;
description = "my stock-price checker";
useSSL = false;
pathPrefix = "/d/[Link]?f=a";
authType = none;
proxyType = none;
proxyHost = "";
proxyPort = 0;
timeout = 0;
Note
Saving a file in a shared project automatically commits the saved version of the file to the
repository, To explicitly commit a file to the repository, right-click the file (or the project containing
the file) and choose Team Commit from the context-sensitive popup menu.
Note
To make changes to the HTTP Destination configuration, you must use a text editor, save the changes
and reactivate the file.
Note
Access to details of HTTP destinations in the SAP HANA XS Administration Tool requires the
credentials of an authenticated database user and the permissions granted by the following SAP
HANA roles:
○ RuntimeConfAdministrator
○ HTTPDestAdministrator
c. In the XS Artifact Administration tab, expand the nodes in the Application Objects tree to locate the
application testApp.
d. Choose [Link] to display details of the HTTP destination .
4. Define the details of the extension to the HTTP destination you created in the previous steps.
Like the HTTP destination itself, you define an extension to an HTTP destination in a configuration file that
requires a specific syntax. The configuration file containing the details of the HTTP destination must have
the file suffix .xshttpdest.
Caution
You must place the HTTP destination configuration (and any extensions to the configuration) in the
application package that uses them. An application cannot reference an HTTP destination
configuration (or an extension) that is located in another application package.
modifies testApp:[Link];
proxyType = http;
proxyHost = "[Link]";
proxyPort = 8080;
Note
Replace the value in proxyHost with the name of the host providing the proxy service.
To make changes to the HTTP Destination configuration (or any extension), you must use a text editor,
save the changes and reactivate the file.
Note
In the default configuration, the URL redirects the request to a logon screen, which requires the
credentials of an authenticated SAP HANA database user to complete the logon process.
c. In the XS Artifact Administration tab, expand the nodes in the Application Objects tree to locate the
application testApp.
d. Choose [Link] to display details of the HTTP destination extension.
Related Information
An HTTP destination defines connection details for services running on specific hosts whose details you want
to define and distribute. An extension to an HTTP destination provides additional information or modifies
values set in the original configuration.
You can use one or more extension to an HTTP destination configuration; the extensions include additions to
the original settings or modifications to the values set in the original configuration. For example, you could
include basic configuration settings in an HTTP destination and provide details of any required proxy settings in
a separate, so-called “extension”.
You define an extension to an HTTP destination configuration in a text file that contains the details of the
modifications you want to apply to the connection details for the original HTTP destination. The HTTP
destination extension uses a mandatory syntax comprising a list of keyword=value pairs, for example, host =
"[Link]";. The same syntax rules apply for the basic HTTP destination
configuration and any extensions. Both files must also have the file suffix .xshttpdest, for example,
[Link] or [Link] creating and saving the HTTP
destination extension, you must activate it in the SAP HANA repository.
The HTTP destination extension does not have to be tied to a particular XSJS application; it can be located
in any application package or subpackage. For this reason, you must include the full package path to the
HTTP destination extension.
The following configuration file for the HTTP destination [Link] illustrates how to modify
the proxy settings specified in the HTTP destination [Link], located in the application package
[Link].
modifies [Link]:[Link];
proxyType = http;
proxyHost = "[Link]";
proxyPort = 8080;
Note
For backward compatibility, the keyword userProxy still works; however, it has been replaced with the
keyword proxyType, which takes the values: [none | http | socks].
After activation, you can view the details of the new HTTP destination extension using the SAP HANA XS
Administration tool.
Note
Access to details of HTTP destinations in the SAP HANA XS Administration Tool requires the credentials of
an authenticated database user and one of the following SAP HANA roles:
● HTTPDestViewer
● HTTPDestAdministrator
Create the files required to enable a service that uses OAuth to authorize access to a resource running on a
remote HTTP destination.
Prerequisites
Since the artifacts required to create an XS OAuth configuration package are stored in the SAP HANA
repository, it is assumed that you have the following:
Context
An OAuth configuration package is a collection of configuration files that define the details of how an
application uses OAuth to enable logon to a resource running on a remote HTTP destination.
An HTTP destination defines connection details for services running on specific hosts whose details you want
to define and distribute. Additional syntax rules apply to the contents of the HTTP destination configuration are
checked when you activate the configuration in the repository.
Tip
You connect the OAuth configuration to the HTTP destination configuration in the HTTP destination's
runtime configuration. Access to the runtime configuration tools requires the permissions included in an
administrator role.
Procedure
You need to create the base configuration for your OAuth application in a design-time file with the
mandatory file-extension .xsoauthappconfig. The application configuration is stored in the SAP HANA
repository and must be activated to create the corresponding catalog objects.
a. Create the design-time file that contains your OAuth application configuration, for example,
[Link]
b. Define the details of the new OAuth application configuration, as follows:
Note
You create the client configuration for your OAuth application in a design-time file with the mandatory file-
extension .xsoauthclientconfig. You can either use an existing client configuration from the package
[Link] or create your own client configuration.
The application configuration is stored in the SAP HANA repository and must be activated to create the
corresponding catalog objects.
a. Create the design-time file that contains your OAuth client configuration, for example,
[Link]
b. Define the details of the new OAuth client configuration, as follows:
{
"clientFlavor" :
"[Link]:abap_ac",
"clientID" : "<OAuth ClientId registered at ABAP>",
"clientAuthType" : "basic",
"authorizationEndpointURL" : "/sap/bc/sec/oauth2/authorize",
"tokenEndpointURL" : "/sap/bc/sec/oauth2/token",
"revocationEndpointURL" : "/sap/bc/sec/oauth2/revoke",
"redirectURL" : "<External_XS_HOST>:<PORT>/sap/hana/xs/
oAuth/lib/runtime/[Link]",
"flow" : "authCode",
"scopeReq" : "maxScopes",
"description" : "OAuth Client for SAP Application Server
ABAP - Authorization Code Flow"
}
Tip
You do not have to create the OAuth client flavor from scratch; SAP HANA provides some example
OAuth client flavors which you can use. The example OAuth client flavors are located in the following
package: [Link].
The following example shows the required format and syntax for the contents of
the .xsoauthclientflavor artifact.
The example below is not complete; it is intended for illustration purposes only.
{ "parameters":[
{ "flavorStep":"1Aut", "paramLocation":"uri", "paramName":"client_id",
"paramValue":"client_id", "valueType":"eval",
"paramMandatory":"true" },
{ "flavorStep":"2Gra", "paramLocation":"head", "paramName":"Authorization",
"paramValue":"Basic Authentication", "valueType":"sec",
"paramMandatory":"true" },
{ "flavorStep":"3Prc", "paramLocation":"head", "paramName":"Bearer",
"paramValue":"access_token", "valueType":"sec",
"paramMandatory":"true" },
{ "flavorStep":"4Ref", "paramLocation":"head", "paramName":"Authorization",
"paramValue":"Basic Authentication", "valueType":"sec",
"paramMandatory":"true" },
{ "flavorStep":"5Rev", "paramLocation":"para", "paramName":"token",
"paramValue":"access_token", "valueType":"sec",
"paramMandatory":"true" },
] }
Note
Access to details of HTTP destinations in the SAP HANA XS Administration Tool requires the
credentials of an authenticated database user and one of the following SAP HANA roles:
○ RuntimeConfAdministrator
○ HTTPDestAdministrator
○ oAuthAdmin
Note
The values displayed here must also be present in the HTTP destination configuration to which the
OAuth configuration applies.
oAuthAppConfigPackage = "[Link]";
oAuthAppConfig = "abapTest";
f. Navigate to the OAuth client configuration and set the client secret.
g. Choose Save to update the run-time configuration for the HTTP destination.
Related Information
The format and syntax required in a design-time artifact describing an OAuth application configuration.
The OAuth application configuration is a file describing the application-specific OAuth parameters that are
used to enable access to a resource running on a remote HTTP destination. The OAuth application
configuration is defined in a design-time artifact with the mandatory file suffix .xsoauthappconfig; the
configuration file must be specified using the JSON format.
Note
The following code example is not a working example; it is provided for illustration purposes, only.
{
"clientConfig":"[Link]:abap_ac",
"description":"ABAP test application for OAuth",
"mandatoryScopes":["OAUTH2_TEST_SCOPE1", "OAUTH2_TEST_SCOPE2"],
"optionalScopes":["OAUTH2_TEST_SCOPE3", "OAUTH2_TEST_SCOPE4"],
"modifies":"[Link]:abapTest"
}
Use the clientConfig keyword to specify the fully qualified name of the associated xsoauthclientconfig
artifact, using the format <[Link]>:<XSOauthClientConfigObjectName>.
"clientConfig":"[Link]:abap_ac",
Note
It is mandatory to specify the name and location of the package containing the associated OAuth client
configuration.
description
Use the description keyword to provide an optional short description of the contents of the OAuth
application configuration.
mandatoryScopes
Use the mandatoryScopes keyword to specify one or more (in an array) of strings describing the mandatory
permissions requested by the client.
"mandatoryScopes":["OAUTH2_TEST_SCOPE1", "OAUTH2_TEST_SCOPE2"],
optionalScopes
Use the optionalScopes keyword to specify one or more (in an array) of strings describing the optional
permissions to be used by the client.
"optionalScopes":["OAUTH2_TEST_SCOPE3", "OAUTH2_TEST_SCOPE4"],
modifies
Use the modifies keyword to indicate that the current XS OAuth application configuration (for example,
[Link] is based on (and extends) another SAP HANA XS OAuth application
configuration (for example, [Link]). You must specify the fully qualified name of the
"modifies":"[Link]:[Link]",
Related Information
The format and syntax required in a design-time artifact describing the OAuth client configuration.
The OAuth client configuration is a file describing details of the client parameters for an application which uses
the services provided by a corresponding OAuth application that enables access to a resource running on a
remote HTTP destination. The OAuth client configuration is defined in a design-time artifact with the
mandatory file suffix .xsoauthclientconfig; the configuration file must be specified using the JSON
format. The following code example shows the contents of a typical OAuth client configuration.
Note
The following code example is not a working example; it is provided for illustration purposes, only.
{
"clientFlavor":"[Link]:abap_ac",
"clientID":"<The OAuth ClientId you registered at ABAP>",
"clientAuthType":"basic",
"authorizationEndpointURL":"/sap/bc/sec/oauth2/authorize",
"tokenEndpointURL":"/sap/bc/sec/oauth2/token",
"revocationEndpointURL":"/sap/bc/sec/oauth2/revoke",
"flow":"authCode",
"description":"OAuth Client for ABAP server",
"samlIssuer":"" ,
"redirectURL":"<HOST>:<PORT>/sap/hana/xs/oAuth/lib/runtime/[Link]",
"scopeReq":"maxScopes",
"shared":"true",
"modifies":"[Link]:abap_ac"
}
In this example, the OAuth client configuration is located in the package [Link]; change the
path specified in clientFlavor to suit your own requirements. You will also have to change the value
specified for clientID and redirectURL.
Tip
SAP HANA provides some example OAuth client configurations which you can use; you can find them in the
following package: [Link]
Use the clientFlavor keyword to specify the fully qualified name of the associated XS OAuth client flavor
configuration artifact, for example, [Link]; you must use the format
<[Link]>:<ObjectName> (no file extension is required).
"clientFlavor":"[Link]:abap_ac",
Note
It is mandatory to specify the name and location of the package containing the associated OAuth client
flavor configuration.
clientID
Use the clientID keyword to define a string that specifies the customer's ID, which is used to identify the
client with the server. The clientID must be changed to suit your requirements. Typically, the client ID is
obtained by registering with a specific service provider.
Note
clientAuthType
Use the clientAuthType keyword to define a number that specifies the client authentication type, for
example, “cert” or “basic”.
"clientAuthType" : "basic",
Note
Use the authorizationEndpointURL keyword to specify a string that defines the authorization endpoint.
The authorization endpoint is the endpoint on the authorization server where the resource owner logs on and
grants authorization to the client application.
"authorizationEndpointURL" : "/sap/bc/sec/oauth2/authorize",
Note
tokenEndpointURL
Use the tokenEndpointURL keyword to to specify a string that defines the token endpoint. The token
endpoint is the endpoint on the authorization server where the client application exchanges the authorization
code, the client ID, and the client secret for an access token.
"tokenEndpointURL" : "/sap/bc/sec/oauth2/token",
Note
revocationEndpointURL
Use the revocationEndpointURL keyword to to specify a string that defines the token endpoint. The token
endpoint is the endpoint on the authorization server where the client application exchanges the authorization
code, the client ID, and the client secret for an access token.
"revocationEndpointURL" : "/sap/bc/sec/oauth2/revoke",
Note
flow
Use the flow keyword to specify a number that defines the authorization flow used during the authentication
exchange, for example, saml2Bearer or authCode.
"flow" :"saml2Bearer",
● saml2Bearer
● authCode
description
Use the optional description keyword to provide a short description of the OAuth client configuration.
"description": "OAuth Client for SAP App Server ABAP - Authorization Code Flow"
samlIssuer
Use the optional samlIssuer keyword to specify a string that defines the SAML issuer ID. The SAML issuer ID
describes the issuer of the SAML token. The SAML bearer extension enables the validation of SAML tokens as
part of granting the OAuth access token.
Note
You set this parameter only if the parameter flow is set to saml2Bearer, for example,
"flow" :"saml2Bearer".
"samlIssuer" : "" ,
redirectURL
Use the redirectURL keyword to specify a string that defines the redirection endpoint. The redirection
endpoint is the endpoint in the client application where the resource owner is redirected to, after having
granted authorization at the authorization endpoint. The redirectURL must be changed to suit your
requirements.
"redirectURL" : "<HOST>:<PORT>/sap/hana/xs/oAuth/lib/runtime/[Link]",
Note
Use the scopeReq keyword to specify whether the maximum available scope from all applications using this
client configuration is always requested or the scope set is specified iteratively.
"scopeReq" : "maxScopes",
● maxScopes
● iterativeScopes
Note
shared
Use the shared keyword to specify a number that defines whether the if the XS OAuth client configuration can
be shared between applications.
"shared" : "false",
● true (shared)
● false (not shared)
Note
modifies
Use the modifies keyword to indicate that the current XS OAuth client configuration, for example,
abap_ac1.xsoauthclientconfig, is based on (and extends) another SAP HANA XS OAuth client
configuration (for example, abap_ac.xsoauthclientconfig). You must specify the fully qualified name of
the associated OAuth client configuration artifact (<fileName>.xsoauthclientconfig), using the format
<[Link]>:<ArtifactName>.xsoauthclientconfig.
"modifies":"[Link]:abap_ac.xsoauthcli
entconfig",
The format and syntax required in a design-time artifact that describes the OAuth client flavors.
The OAuth client flavor file provides details of the OAuth protocol for a client application that uses the services
provided by a corresponding OAuth application. The OAuth client flavor steps are defined in a design-time
artifact with the mandatory file suffix .xsoauthclientflavor; the configuration file must be specified using
the JSON format.
Note
The following example of an OAuth client flavor configuration is incomplete; it is intended for illustration
purposes only.
{ "parameters":[
{ "flavorStep":"1Aut", "paramLocation":"uri", "paramName":"client_id",
"paramValue":"client_id", "valueType":"eval",
"paramMandatory":"true" },
{ "flavorStep":"1Aut", "paramLocation":"uri", "paramName":"redirect_uri",
"paramValue":"redirect_uri", "valueType":"eval",
"paramMandatory":"true" },
{ "flavorStep":"1Aut", "paramLocation":"uri", "paramName":"scope",
"paramValue":"scope", "valueType":"eval",
"paramMandatory":"true" },
{ "flavorStep":"1Aut", "paramLocation":"uri", "paramName":"response_type",
"paramValue":"code", "valueType":"litr",
"paramMandatory":"true" },
{ "flavorStep":"1Aut", "paramLocation":"uri", "paramName":"state",
"paramValue":"state", "valueType":"eval",
"paramMandatory":"true" },
{ "flavorStep":"2Gra", "paramLocation":"head", "paramName":"Authorization",
"paramValue":"Basic Authentication", "valueType":"sec",
"paramMandatory":"true" },
{ "flavorStep":"2Gra", "paramLocation":"head", "paramName":"Content-Type",
"paramValue":"application/x-www-form-urlencoded", "valueType":"litr",
"paramMandatory":"true" },
{ "flavorStep":"2Gra", "paramLocation":"para", "paramName":"code",
"paramValue":"code", "valueType":"eval",
"paramMandatory":"true" },
{ "flavorStep":"2Gra", "paramLocation":"para", "paramName":"grant_type",
"paramValue":"authorization_code", "valueType":"litr",
"paramMandatory":"true" },
{ "flavorStep":"2Gra", "paramLocation":"para", "paramName":"client_id",
"paramValue":"client_id", "valueType":"eval",
"paramMandatory":"true" },
{ "flavorStep":"2Gra", "paramLocation":"para", "paramName":"redirect_uri",
"paramValue":"redirect_uri", "valueType":"eval",
"paramMandatory":"true" },
{ "flavorStep":"3Prc", "paramLocation":"head", "paramName":"Bearer ",
"paramValue":"access_token", "valueType":"sec",
"paramMandatory":"true" },
It is not necessary to create your own OAuth client flavor from scratch; SAP HANA provides some OAuth client
flavors for a selection of OAuth server scenarios, which you can use without modification.
Tip
However, you do need to modify the OAuth client flavor artifact for the following scenarios:
● Modifications are required (or have already been made) to the API of an available OAuth server.
● A connection is required to a new OAuth server not covered by the scenarios included in the SAP HANA
configuration templates.
parameters
Use the parameters keyword to define a list of parameter-values pairs, for example,
"paramLocation":"uri" that support the specification defined in the OAuth client configuration file
<filename>.oxauthclientconfig.
flavorStep
Use the flavorStep keyword to specify a step in the procedure used by the client flavor, as illustrated in the
following example
"flavorStep":"saml",
● IAut
● 2Gra
● 3Prc
● 4Ref
paramLocation
Use the paramLocation keyword to specify the location of the parameter defined, as shown in the following
example:
"paramLocation":"uri",
● uri
Universal resource indicator
● head
In the request header
● para
In the request body
paramName
Use the paramName keyword to specify the name of the parameter defined in “paramLocation”, as shown in
the following example:
"paramName":"token",
The parameter name depends on the local setup of your client configuration.
paramValue
Use the paramValue keyword to specify a value for the parameter name specified in “paramName”.
"paramValue":"access_token",
The parameter name depends on the local setup of your client configuration.
valueType
Use the valueType keyword to specify the type of value expected by the parameter defined in “paramValue”.
"valueType":"sec",
● litr
Literal value
● eval
The value is evaluated by the OAuth client runtime
● sec
The value is evaluated by the OAuth client runtime in a secure way
paramMandatory
"paramMandatory":"true",
● true
Required
● false
Not Required
Related Information
The design-time building blocks of an SAP HANA applications are called development objects (or artifacts),
and many have a mandatory file extension, for example, .hdbtable (design-time table definition), .hdbview
(design-time SQL-view definition), or .hdbrole (design-time role definition).
Some of the development objects you encounter when creating an application, such as projects and packages,
are designed to help you structure your application. Other objects such as schemas, table definitions, or
analytical and attribute views, help you organize your data. Design-time definitions of procedures and server-
side JavaScript code are the core objects of an SAP HANA application; these, too, have mandatory file
extensions, for example, .hdbprocedure or .xsjs. Other types of development objects help you control the
access to runtime objects.
When you activate an application artifact, the file extension (for example, .hdbdd, .xsjs, or
hdbprocedure, ...) is used to determine which runtime plug-in to call during the activation process. The plug-
The file extensions associated with application artifacts are used in other contexts, too. For example, in SAP
HANA studio, a context-sensitive menu is displayed when you click an artifact with the alternate mouse button;
the options displayed in the menu is determined, amongst other things, according to the file extension.
Related Information
The design-time building blocks of your SAP HANA applications have a mandatory file extension, for
example, .hdbtable (design-time table definition) or .hdbview (design-time SQL-view definition).
In SAP HANA, application artifacts have a mandatory file extension, which is used to determine the Repository
tools required to parse the contents of the design-time artifact on activation. The following tables list the most
commonly used building blocks of an SAP HANA application; the information provided shows any mandatory
file extension and, if appropriate, indicates where to find more information concerning the context in which the
object can be used.
.aflpmml Procedure A file used by the application function modeler to store details of
a procedure defined using application functions in the Predictive
Analysis Library * (PAL) or Business Function Library * (BFL). Us
ing the AFM also generates a .diagram and a .aflmodel file.
.analyticview Analytic view A file containing a design-time definition of an analytic view; the
view can be referenced in an OData service definition.
.attributeview Attribute view A file containing a design-time definition of an attribute view; the
view can be referenced in an OData service definition.
.hdbscalarfunction Scalar user-defined func A file containing a design-time definition of a a scalar user-de
tion fined function (UDF), which is a custom function that can be
called in the SELECT and WHERE clauses of an SQL statement.
.hdbtablefunction Table user-defined func A file containing a design-time definition of a table user-defined
tion function (UDF), which is a custom function that can be called in
the FROM–clause of an SQL statement.
.hdbtextbundle Resource Bundle A file for defining translatable UI texts for an application. Used in
SAP UI5 applications.
.hdbti Table Import definition A table-import configuration that specifies which .csv file is im
ported into which table in the SAP HANA system.
.hdbview SQL View A design-time definition of a database view, which is a virtual ta
ble based on an SQL query.
.proceduretemplate Procedure template A design-time artifact containing a base script with predefined
placeholders for objects such as tables, views and columns.
.searchruleset Search Rule Set * A file that defines a set of rules for use with fuzzy searches. The
rules help decide what is a valid match in a search.
.xsaccess Application Access File An application-specific configuration file that defines permis
sions for a native SAP HANA application, for example, to manage
access to the application and running objects in the package.
.xshttpdest HTTP destination config- A file that defines details for connections to a remote destination
uration by HTTP (or HTTPS)
.xsjob Scheduled XS job A JSON-compliant file used to define recurring tasks that run in
the background (independent of any HTTP request/response
process); a scheduled job can either execute a JavaScript func
tion or call a SQLScript procedure.
.xsjs Server-Side JavaScript A file containing JavaScript code that can run in SAP HANA Ex
Code tended Application Services and be accessed via URL
.xsjslib Server-Side JavaScript A file containing JavaScript code that can run in SAP HANA Ex
Library tended Application Services but cannot be accessed via URL.
The code can be imported into an .xsjs code file.
.xsoauthappconfig OAuth application con A file describing high-level details of an application that enables
figuration file logon to a service running on a remote HTTP destination using
OAuth
.xsoauthclientconfi OAuth client configura- A file containing detailed information about a client application
g tion file that uses OAuth as the authentication mechanism for logon to a
remote HTTP destination
.xsoauthclientflavo OAuth client flavor file The corresponding OAuth flavors file for the OAuth client configu-
r ration
.xsodata OData Descriptor A design-time object that defines an OData service that exposes
SAP HANA data from a specified end point.
.xsprivileges Application Privilege A file that defines a privilege that can be assigned to an SAP
HANA Extended Application Services application, for example,
the right to start or administer the application.
.xssecurestore Application secure store The design-time file that creates an application-specific secure
store; the store is used by the application to store data safely and
securely in name-value form.
.xssqlcc SQL Connection Config- A file that enables execution of SQL statements from inside
uration server-side JavaScript code with credentials that are different to
those of the requesting user
.xswidget Widget A file that defines a standalone SAP HANA application for the
purpose of integration into an application site
.xsxmla XMLA Descriptor A design time object that defines an XMLA service that exposes
SAP HANA data
Caution
(*) For information about the capabilities available for your license and installation scenario, refer to the
Feature Scope Description for SAP HANA.
Package A container in the repository for development objects. Packages are represented by
folders.
Attribute, Analytic and A view created with modeling tools and designed to model a busi Created with the Systems
Calculation View ness use case. view.
Decision Table A table used to model business rules, for example, to manage
data validation and quality.
Analytic Privilege A set of rules that allows users to seeing a subset of data in a ta
ble or view.
The SAP HANA Development perspective in SAP HANA studio provides context-sensitive access to a variety of
useful developer tools.
In SAP HANA studio's SAP HANA Development perspective, the view you are using determines what tools are
available and the action that can be performed on the displayed objects. For example, in the Project Explorer
view, the application developer can use the alternate mouse button to display a context-sensitive menu that
provides access to Repository activation features, debugging configuration tools, and so on.
The following table lists a selection of the most frequently used tools and features that are available in the
context-sensitive menu for artifacts in the Project Explorer view of the SAP HANA Development perspective.
Team Commit Copy the most recent version of the design-time artifact from the
local file system to the Repository. Note that every local saved
change is immediately committed to the user’s corresponding in
active workspace in the SAP HANA Repository.
Remove from Client Undo a check-out operation without the risk of deleting content in
the SAP HANA Repository
Synchronize Synchronize changes made to local file version with the version of
the file in the repository
Debug as... Name/ID Debug the code in the selected design-time artifact using an exist
ing debug configuration.
Debug configuration... Debug the code in the selected design-time artifact using an new
debug configuration that you define now, for example: XS Java
Script, SAP HANA stored procedure...
Run as... HTML/XS Service/... Test the selected Repository artifact in a Web browser directly
from the Project Explorer view using the services provided by the
currently connected SAP HANA server; the artifact's file extension
is used to determine how to display the content.
Run configuration... Run the selected Repository artifact in a Web browser using a new
runtime configuration, for example, for SAP HANA XS JavaScript
artifacts, on a specific SAP HANA instance, and with defined user
logon credentials.
The following table lists additional tools and features that are available in the context-sensitive menu for
artifacts in the Repositories view of the SAP HANA Development perspective.
Inactive testing Test repository objects that have not yet been activated, for example: XSJS, XSOData,
XSJSlib, ....
Note
The SAP HANA server must be running in developer_mode, and you must set a cli
ent-side cookie named sapXsDevWorkspace to the name of your Repository work
space.
Compare with active version Display the differences between two versions of the same repository artifact or two differ-
ent artifacts. You can select and compare multiple artifacts ( CTRL and click the alternate
mouse button). You can also compare an individual repository artifact with the version of
the artifact that is currently active in the repository or a version from the artifact's revision-
history list .
Get Where-Used List Look for any references to the currently selected artifact and display the results in the
Search view. The search includes both inactive artifacts (in your Repository workspace)
and activated artifacts in the Repository. The Get Where-Used List option is available in
both the Project Explorer and the Repositories view.
Share Project Connect the local (client) project folders with SAP HANA repository and synchronizes the
contents between client and server. This option is only available with an unshared project
artifact.
Unshare Project Cancel any synchronization between the local file system and the SAP HANA repository;
the Unshare action does not delete any files, unless you specifically enable the delete op
tion. The Unshare option is only available with an already shared project artifact.
Move Moves selected SAP HANA artifacts or an entire package within or across projects in the
same Repository workspace. All SAP HANA artifacts referencing the moved artifacts are
updated too. You must manually activate all the moved and referencing artifacts. You can
move the following SAP HANA artifacts:
● Attribute View
● Analytical View
● Calculation View
● Analytic Privilege
Paste Special Clones one or more packages and all their artifacts and copies them to a target package.
While copying, this feature detects if the target contains any other artifacts from a previous
Paste Special operation. If any other cloned artifacts exist, you can update references to
the existing cloned artifacts. You must manually activate the cloned artifacts. You can paste
the following artifacts:
● Attribute View
● Analytical View
● Calculation View
● Analytic Privilege
Repositories View
The following table lists the most frequently used tools and features that are available in the context-sensitive
menu for artifacts in the Repositories view of the SAP HANA Development perspective.
Note
The items displayed in the Team popup menu are context-sensitive; the options available in the menu
depend on the type of repository object selected.
Tool/Feature Description
Add package This option is only available when you select another package.
Activate Generate a catalog object based on the corresponding design-time definition in the Reposi
tory for the selected artifact
Activate All... Generate a catalog object based on the corresponding design-time definition in the Reposi
tory for all currently inactive artifacts; you can choose to include/exclude individual artifacts
from the displayed list. Inactive artifacts are local copies of Repository artifacts saved in
your workspace.
Check out Copy package content from the Repository to the local workspace folder. Synchronize the
repository with the local workspace (refresh)
Delivery Unit management (Package only): Start the lifecycle-management tools and display details of the correspond
ing delivery unit (DU) if available.
Edit package (Package only): Display and edit details of the selected package, for example: the delivery
unit the package is assigned to, the package type, and the person responsible for the pack
age's creation and maintenance.
Get Where-Used List Display any references to the currently selected artifact in the Search view. The search in
cludes both inactive artifacts (in your Repository workspace) and activated artifacts in the
SAP HANA Repository. The Get Where-Used List option is available in both the Project
Explorer and the Repositories view.
Product management (Package only): Start the lifecycle-management tools and display details of the correspond
ing product, if available.
Remove from client Remove the selected file(s) from the local file system; the repository version remains un
touched.
Refresh Synchronize the contents of the selected repository package with the local workspace ( F5 )
Reset to Replace the selected file with the base version or the currently active version
Caution
When you choose base version, you restore the original version of the object you are
currently editing. When you choose active version, the version that you are currently ed
iting becomes the new active version.
Show in history view Display the complete list of revisions available for the selected item; the details displayed
include the version number, the date created, and the file owner. Right-click an entry in the
history list to display further menu options, for example, to compare two versions of the file.
Moves Moves selected SAP HANA artifacts or an entire package within or across projects in the
same Repository workspace. All SAP HANA artifacts referencing the moved artifacts are up
dated too. You must manually activate all the moved and referencing artifacts. You can move
the following SAP HANA artifacts:
● Attribute View
● Analytical View
● Calculation View
● Analytic Privilege
Paste Special Clones one or more packages and all their artifacts and copies them to a target package.
While copying, this feature detects if the target contains any other artifacts from a previous
Paste Special operation. If any other cloned artifacts exist, you can update references to the
existing cloned artifacts. You must manually activate the cloned artifacts. You can paste the
following artifacts:
● Attribute View
● Analytical View
● Calculation View
● Analytic Privilege
The persistence model defines the schema, tables, sequences, and views that specify what data to make
accessible for consumption by XS applications and how.
In SAP HANA Extended Application Services (SAP HANA XS), the persistence model is mapped to the
consumption model that is exposed to client applications and users so that data can be analyzed and displayed
in the appropriate form in the client application interface. The way you design and develop the database
objects required for your data model depends on whether you are developing applications that run in the SAP
HANA XS classic or XS advanced run-time environment.
SAP HANA XS classic model enables you to create database schema, tables, views, and sequences as design-
time files in the SAP HANA repository. Repository files can be read by applications that you develop. When
implementing the data persistence model in XS classic, you can use either the Core Data Services (CDS)
syntax or HDBtable syntax (or both). “HDBtable syntax” is a collective term; it includes the different
configuration schema for each of the various design-time data artifacts, for example: schema (.hdbschema),
sequence (.hdbsequence), table (.hdbtable), and view (.hdbview).
All repository files including your view definition can be transported (along with tables, schema, and
sequences) to other SAP HANA systems, for example, in a delivery unit. A delivery unit is the medium SAP
HANA provides to enable you to assemble all your application-related repository artifacts together into an
archive that can be easily exported to other systems.
Note
You can also set up data-provisioning rules and save them as design-time objects so that they can be
included in the delivery unit that you transport between systems.
The rules you define for a data-provisioning scenario enable you to import data from comma-separated values
(CSV) files directly into SAP HANA tables using the SAP HANA XS table-import feature. The complete data-
import configuration can be included in a delivery unit and transported between SAP HANA systems for reuse.
As part of the process of setting up the basic persistence model for SAP HANA XS, you create the following
artifacts in the XS classic repository:
Association .hdbdd -
Note
(*) To create a schema, a synonym, or a sequence, you must use the appropriate HDBTable syntax, for
example, .hdbschema, .hdbsynonym, or .hdbsequence. In a CDS document, you can include references
to both CDS and HDBTable artifacts.
On activation of a repository artifact, the file suffix (for example, .hdbdd or .hdb[table|view]) is used to
determine which run-time plug-in to call during the activation process. When you activate a design-time artifact
in the SAP HANA Repository, the plug-in corresponding to the artifact's file suffix reads the contents of
repository artifact selected for activation (for example, a table, a view, or a complete CDS document that
contains multiple artifact definitions), interprets the artifact definitions in the file, and creates the appropriate
corresponding run-time objects in the catalog.
For the XS advanced run time, you develop multi-target applications (MTA), which contain modules, for
example: a database module, a module for your business logic ([Link]), and a UI module for your client
interface (HTML5). The modules enable you to group together in logical subpackages the artifacts that you
need for the various elements of your multi-target application. You can deploy the whole package or the
individual subpackages.
As part of the process of defining the database persistence model for your XS advanced application, you use
the database module to store database design-time artifacts such as tables and views, which you define using
Core Data Services (CDS). However, you can also create procedures and functions, for example, using
SQLScript, which can be used to insert data into (and remove data from) tables or views.
Note
In general, CDS works in XS advanced (HDI) in the same way that it does in the SAP HANA XS classic
Repository. For XS advanced, however, there are some incompatible changes and additions, for example, in
the definition and use of name spaces, the use of annotations, the definition of entities (tables) and
structure types. For more information, see CDS Documents in XS Advanced in the list of Related Links
below.
Tip
You can also define the analytic model, for example, the calculation views and analytic privileges that
are to be used to analyze the underlying data model and specify who (or what) is allowed access.
Related Information
Core data services (CDS) is an infrastructure that can be used to define and consume semantically rich data
models in SAP HANA.
The model described in CDS enables you to use the Data Definition Language to define the artifacts that make
up the data-persistence model. You can save the data-persistence object definition as a CDS artifact, that is; a
design-time object that you manage in the SAP HANA repository and activate when necessary. Using a data
definition language (DDL), a query language (QL), and an expression language (EL), CDS enables write
operations, transaction semantics, and more.
You can use the CDS specification to create a CDS document which defines the following artifacts and
elements:
● Entities (tables)
● Views
● User-defined data types (including structured types)
● Contexts
● Associations
● Annotations
Note
To create a schema, a synonym, or a sequence, you must use the appropriate .hdbtable artifact, for
example, .hdbschema, .hdbsynonym, or .hdbsequence. You can reference these artifacts in a CDS
document.
CDS artifacts are design-time definitions that are used to generate the corresponding run-time objects, when
the CDS document that contains the artifact definitions is activated in the SAP HANA repository. In CDS, the
objects can be referenced using the name of the design-time artifact in the repository; in SQL, only the name of
the catalog object can be used. The CDS document containing the design-time definitions that you create
using the CDS-compliant syntax must have the file extension .hdbdd, for example, [Link].
Related Information
The SAP Web IDE for SAP HANA provides editing tools specially designed to help you create and modify CDS
documents.
SAP Web IDE for SAP HANA includes dedicated editors that you can use to define data-persistence objects in
CDS documents using the DDL-compliant Core Data Services syntax. SAP HANA XS advanced model
recognizes the .hdbcds file extension required for CDS object definitions and, at deployment time, calls the
appropriate plug-in to parse the content defined in the CDS document and create the corresponding run-time
object in the catalog. If you right-click a file with the .hdbcds extension in the Project Explorer view of your
application project, SAP Web IDE for SAP HANA provides the following choice of editors in the context-sensitive
menu.
SAP Web IDE for SAP HANA includes a dedicated editor that you can use to define data-persistence objects
using the CDS syntax. SAP HANA recognizes the .hdbcds file extension required for CDS object definitions
and calls the appropriate repository plug-in. If you double-click a file with the .hdbcds extension in the Project
Explorer view, SAP Web IDE for SAP HANA automatically displays the selected file in the CDS text editor.
● Syntax highlights
The CDS DDL editor supports syntax highlighting, for example, for keywords and any assigned values. To
customize the colors and fonts used in the CDS text editor, choose Tools Preferences Code Editor
Editor Appearance and select a theme and font size.
Note
The CDS DDL editor automatically inserts the keyword namespace into any new DDL source file that
you create using the New CDS Artifact dialog.
● Keyword completion
The editor displays a list of DDL suggestions that could be used to complete the keyword you start to enter.
To change the settings, choose Tools Code Completion in the toolbar menu.
The CDS graphical editor provides graphical modeling tools that help you to design and create database
models using standard CDS artifacts with minimal or no coding at all. You can use the CDS graphical editor to
create CDS artifacts such as entities, contexts, associations, structured types, and so on.
The built-in tools provided with the CDS Graphical Editor enable you to perform the following operations:
● Create CDS files (with the extension .hdbcds) using a file-creation wizard.
● Create standard CDS artifacts, for example: entities, contexts, associations (to internal and external
entities), structured types, scalar types, ...
● Define technical configuration properties for entities, for example: indexes, partitions, and table groupings.
● Generate the relevant CDS source code in the text editor for the corresponding database model.
● Open in the CDS graphical editor data models that were created using the CDS text editor.
Tip
The built-in tools included with the CDS Graphical Editor are context-sensitive; right-click an element
displayed in the CDS Graphical editor to display the tool options that are available.
Related Information
The CDS text editor displays the source code of your CDS documents in a dedicated text-based editor.
SAP HANA studio includes a dedicated editor that you can use to define data-persistence objects using the
CDS syntax. SAP HANA studio recognizes the .hdbdd file extension required for CDS object definitions and
calls the appropriate repository plugin. If you double-click a file with the .hdbdd extension in the Project
Explorer view, SAP HANA studio automatically displays the selected file in the CDS editor.
● Syntax highlights
Note
The CDS DDL editor automatically inserts the mandatory keyword namespace into any new DDL
source file that you create using the New DDL Source File dialog. The following values are assumed:
○ namespace = <repository package name>
● Keyword completion
The editor displays a list of DDL suggestions that could be used to complete the keyword you start to enter.
You can insert any of the suggestions using the SPACE + TAB keys.
● Code validity
You can check the validity of the syntax in your DDL source file before activating the changes in the SAP
HANA repository. Right-click the file containing the syntax to check and use the Team Check option
in the context menu.
Note
● Comments
Text that appears after a double forward slash (//) or between a forward slash and an asterisk (/*...*/)
is interpreted as a comment and highlighted in the CDS editor (for example, //this is a comment).
Tip
The Project Explorer view associates the .hdbdd file extension with the DDL icon. You can use this icon to
determine which files contain CDS-compliant DDL code.
A CDS document is a design-time source file that contains definitions of the objects you want to create in the
SAP HANA catalog.
Prerequisites
Context
CDS documents are design-time source files that contain DDL code that describes a persistence model
according to rules defined in Core Data Services. CDS documents have the file suffix .hdbdd. Activating the
CDS document creates the corresponding catalog objects in the specified schema. To create a CDS document
in the repository, perform the following steps:
Procedure
a. Right-click the folder where you want to save the CDS document and choose New Other...
Database Development DDL Source File in the context-sensitive popup menu.
b. Enter the name of the CDS document in the File Name box, for example, MyModel.
Tip
File extensions are important. If you are using SAP HANA studio to create artifacts in the SAP
HANA Repository, the file-creation wizard adds the required file extension automatically (for
example, [Link]) and, if appropriate, enables direct editing of the new file in the
corresponding editor.
c. Choose Finish to save the changes and commit the new CDS document to the repository.
The file-creation wizard creates a basic CDS document with the following elements:
○ Namespace
The name of the repository package in which you created the new CDS document, for example,
[Link]
○ Top-level element
The name of the top-level element in a CDS document must match the name of the CDS
document itself; this is the name you enter when using the file-creation wizard to create the new
CDS document, for example, MyModel, MyContext, or MyEntity. In this example, the top-level
element is a context.
namespace [Link];
context MyModel {
Open the CDS document you created in the previous step, for example, [Link], and add the
CDS-definition code to the file. The CDS code describes the CDS artifacts you want to add, for example:
entity definitions, type definitions, view definitions and so on:
Note
The following code examples are provided for illustration purposes only.
Note
If the schema you specify does not exist, you cannot activate the new CDS document.
namespace [Link];
@Schema: 'SAP_HANA_CDS'
context MyModel {
};
namespace [Link];
@Schema: 'SAP_HANA_CDS'
context MyModel {
type BusinessKey : String(10);
type SString : String(40);
type <[...]>
<[...]>
};
namespace [Link];
@Schema: 'SAP_HANA_CDS'
context MyModel {
type BusinessKey : String(10);
type SString : String(40);
type <[...]>
context MasterData {
<[...]>
};
context Sales {
<[...]>
};
context Purchases {
<[...]>
};
namespace [Link];
@Schema: 'SAP_HANA_CDS'
context MyModel {
type BusinessKey : String(10);
type SString : String(40);
type <[...]>
context MasterData {
@[Link] : #COLUMN
Entity Addresses {
key AddressId: BusinessKey;
City: SString;
PostalCode: BusinessKey;
<[...]>
};
@[Link] : #COLUMN
Entity BusinessPartner {
key PartnerId: BusinessKey;
PartnerRole: String(3);
<[...]>
};
};
context Sales {
<[...]>
};
context Purchases {
<[...]>
};
};
Note
Saving a file in a shared project automatically commits the saved version of the file to the repository.
You do not need to explicitly commit it again.
Note
If you cannot activate the new CDS document, check that the specified schema already exists and
that there are no illegal characters in the name space, for example, the hyphen (-).
8. Ensure access to the schema where the new CDS catalog objects are created.
After activation in the repository, a schema object is only visible in the catalog to the _SYS_REPO user. To
enable other users, for example the schema owner, to view the newly created schema and the objects it
contains, you must grant the user the required SELECT privilege for the schema object.
If you already have the appropriate SELECT privilege for the schema, you do not need to perform this
step.
a. In the SAP HANA studio Systems view, right-click the SAP HANA system hosting the repository where
the schema was activated and choose SQL Console in the context-sensitive popup menu.
b. In the SQL console, execute the statement illustrated in the following example, where <SCHEMANAME>
is the name of the newly activated schema, and <username> is the database user ID of the schema
owner:
call
_SYS_REPO.GRANT_SCHEMA_PRIVILEGE_ON_ACTIVATED_CONTENT('select','<SCHEMANAME
>','<username>');
9. Check that a catalog objects has been successfully created for each of the artifacts defined in the CDS
document.
When a CDS document is activated, the activation process generates a corresponding catalog object
where appropriate for the artifacts defined in the document; the location in the catalog is determined by
the type of object generated.
Note
Non-generated catalog objects include: scalar types, structured types, and annotations.
Related Information
CDS documents are design-time source files that contain DDL code that describes a persistence model
according to rules defined in Core Data Services.
CDS documents have the file suffix .hdbdd. Each CDS document must contain the following basic elements:
Note
If you use the file-creation wizard to create a new CDS document, the name space is inserted
automatically; the inserted name space reflects the repository location you select to create the new
CDS document.
● A schema definition
The schema you specify is used to store the catalog objects that are defined in the CDS document, for
example: entities, structured types, and views. The objects are generated in the catalog when the CDS
document is activated in the SAP HANA repository.
● CDS artifact definitions
The objects that make up your persistence model, for example: contexts, entities, structured types, and
views
Each CDS document must contain one top-level artifact, for example: a context, a type, an entity, or a view. The
name of the top-level artifact in the CDS document must match the file name of the CDS document, without
the suffix. For example, if the top-level artifact is a context named MyModel, the name of the CDS document
must be [Link].
Note
On activation of a repository file in, the file suffix, for example, .hdbdd, is used to determine which runtime
plug-in to call during the activation process. The plug-in reads the repository file selected for activation, in
this case a CDS-compliant document, parses the object descriptions in the file, and creates the appropriate
runtime objects in the catalog.
If you want to define multiple CDS artifacts within a single CDS document (for example, multiple types,
structured types, and entities), the top-level artifact must be a context. A CDS document can contain multiple
contexts and any number and type of artifacts. A context can also contain nested sub-contexts, each of which
can also contain any number and type of artifacts.
When a CDS document is activated, the activation process generates a corresponding catalog object for each
of the artifacts defined in the document; the location in the catalog is determined by the type of object
generated. The following table shows the catalog location for objects generated by the activation of common
CDS artifacts.
The following example shows the basic structure of a single CDS document that resides in the package
[Link] in the SAP HANA repository. the CDS document defines the following CDS
artifacts:
● Types:
○ BusinessKey and SString
● Entities:
○ Addresses, BusinessPartners, Header, and Item
● Contexts:
○ MyModel, which contains the nested contexts: MasterData, Sales, and Purchases
● External references
The using keyword enables you to refer to artifacts defined in separate CDS documents, for example,
[Link]. You can also assign an alias to the reference, for example, AS <alias>.
● Annotations
Built-in annotations, for example, @Catalog, @Schema, and @nokey, are important elements of the CDS
syntax used to define CDS-compliant catalog objects. You can define your own custom annotations, too.
Note
The following code snippet is incomplete [...]; it is intended for illustration purposes only.
Sample Code
namespace [Link];
using [Link]::MyModelB.MyContextB1 as ic;
@Schema: 'SAP_HANA_CDS'
context MyModel {
type BusinessKey : String(10);
type SString : String(40);
type <[...]>
context MasterData {
@[Link] : #COLUMN
Entity Addresses {
key AddressId: BusinessKey;
City: SString;
PostalCode: BusinessKey;
<[...]>
};
@[Link] : #COLUMN
Entity BusinessPartner {
key PartnerId: BusinessKey;
PartnerRole: String(3);
<[...]>
};
};
context Sales {
@[Link] : #COLUMN
Entity Header {
key SalesOrderId: BusinessKey;
<[...]>
};
@[Link] : #COLUMN
Related Information
You can define an artifact in one CDS document by referring to an artifact that is defined in another CDS
document.
The CDS syntax enables you to define a CDS artifact in one document by basing it on an “external” artifact - an
artifact that is defined in a separate CDS document. Each external artifact must be explicitly declared in the
source CDS document with the using keyword, which specifies the location of the external artifact, its name,
and where appropriate its CDS context.
Tip
The using declarations must be located in the header of the CDS document between the namespace
declaration and the beginning of the top-level artifact, for example, the context.
The external artifact can be either a single object (for example, a type, an entity, or a view) or a context. You can
also include an optional alias in the using declaration, for example, ContextA.ContextA1 as ic. The alias
(ic) can then be used in subsequent type definitions in the source CDS document.
//Filename = Pack1/Distributed/[Link]
namespace [Link];
using [Link]::ContextA.T1;
using [Link]::[Link] as ic;
using [Link]::[Link].T3 as ict3;
using [Link]::[Link].T3.a as a; // error, is not an
artifact
context ContextB {
type T10 {
a : T1; // Integer
b : ic.T2; // String(20)
c : ic.T3; // structured
d : type of ic.T3.b; // String(88)
The CDS document [Link] shown above uses external artifacts (data types T1 and T3) that are
defined in the “target” CDS document [Link] shown below. Two using declarations are present in
the CDS document [Link]; one with no alias and one with an explicitly specified alias (ic). The first
using declaration introduces the scalar type [Link]::ContextA.T1. The second using
declaration introduces the context [Link]::[Link] and makes it accessible by
means of the explicitly specified alias ic.
Note
If no explicit alias is specified, the last part of the fully qualified name is assumed as the alias, for example
T1.
The using keyword is the only way to refer to an externally defined artifact in CDS. In the example above, the
type x would cause an activation error; you cannot refer to an externally defined CDS artifact directly by using
its fully qualified name in an artifact definition.
//Filename = Pack1/Distributed/[Link]
namespace [Link];
context ContextA {
type T1 : Integer;
context ContextAI {
type T2 : String(20);
type T3 {
a : Integer;
b : String(88);
};
};
};
Note
Whether you use a single or multiple CDS documents to define your data-persistence model, each CDS
document must contain only one top-level artifact, and the name of the top-level artifact must correspond
to the name of the CDS document. For example, if the top-level artifact in a CDS document is ContextA,
then the CDS document itself must be named [Link].
Rules and restrictions apply to the names of CDS documents and the package in which the CDS document
resides.
The rules that apply for naming CDS documents are the same as the rules for naming the packages in which
the CDS document is located. When specifying the name of a package or a CDS document (or referencing the
name of an existing CDS object, for example, within a CDS document), bear in mind the following rules:
Caution
Although it is possible to use quotation marks (“”) to wrap a name that includes forbidden characters, as a
general rule, it is recommended to follow the naming conventions for CDS documents specified here in
order to avoid problems during activation in the repository.
Related Information
The namespace is the path to the package in the SAP HANA Repository that contains CDS artifacts such as
entities, contexts, and views.
In a CDS document, the first statement must declare the namespace that contains the CDS elements which
the document defines, for example: a context, a type, an entity, or a view. The namespace must match the
package name where the CDS elements specified in the CDS document are located. If the package path
specified in a namespace declaration does not already exist in the SAP HANA Repository, the activation
process for the elements specified in the CDS document fails.
It is possible to enclose in quotation marks (“”) individual parts of the namespace identifier, for example,
"Pack1".pack2. Quotes enable the use of characters that are not allowed in regular CDS identifiers; in CDS, a
quoted identifier can include all characters except the dot (.) and the double colon (::). If you need to use a
reserved keyword as an identifier, you must enclose it in quotes, for example, “Entity”. However, it is
recommended to avoid the use of reserved keywords as identifiers.
Note
You can also use quotation marks (“”) to wrap the names of CDS artifacts (entities, views) and elements
(columns...).
The following code snippet applies to artifacts created in the Repository package /Pack1/pack2/ and shows
some examples of valid namespace declarations, including namespaces that use quotation marks (“”).
Note
namespace Pack1.pack2;
namespace "Pack1".pack2;
namespace Pack1."pack2";
namespace "Pack1"."pack2";
The following code snippet applies to artifacts created in the Repository package /Pack1/pack2/ and shows
some examples of invalid namespace declarations.
The examples of namespace declarations in the code snippet above are invalid for the following reasons:
● pack1.pack2;
pack1 is spelled incorrectly; the namespace element requires a capital P to match the corresponding
location in the Repository, for example, Pack1.
● "Pack1.pack2";
You cannot quote the entire namespace path; only individual elements of the namespace path can be
quoted, for example, "Pack1".pack2; or Pack1."pack2";.
● [Link];
The namespace declaration must not include the names of elements specified in the CDS document itself,
for example, MyDataModel.
Related Information
The following example illustrates how to assign two simple entities to a context using the CDS-
compliant .hdbdd syntax; you store the context-definition file with a specific name and the file
extension .hdbdd, for example, [Link].
Note
If you are using a CDS document to define a CDS context, the name of the CDS document must match the
name of the context defined in the CDS document, for example, with the “context” keyword.
In the example below, you must save the context definition “Books” in the CDS document [Link]. In
addition, the name space declared in a CDS document must match the repository package in which the object
the document defines is located.
The following code example illustrates how to use the CDS syntax to define multiple design-time entities in a
context named Books.
namespace [Link].myapp1;
@Schema : 'MYSCHEMA'
context Books {
@[Link]: #COLUMN
@[Link] : [ { name : 'MYINDEX1', unique : true, order : #DESC,
elementNames : ['ISBN'] } ]
entity Book {
key AuthorID : String(10);
key BookTitle : String(100);
ISBN : Integer not null;
Publisher : String(100);
};
@[Link]: #COLUMN
@[Link] : [ { name: 'MYINDEX2', unique: true, order: #DESC,
elementNames: ['AuthorNationality'] } ]
entity Author {
key AuthorName : String(100);
AuthorNationality : String(20);
AuthorBirthday : String(100);
AuthorAddress : String(100);
};
};
Activation of the file [Link] containing the context and entity definitions creates the catalog objects
“Book” and “Author”.
The namespace specified at the start of the file, for example, [Link].myapp1 corresponds to the
location of the entity definition file ([Link]) in the application-package hierarchy .
Nested Contexts
The following code example shows you how to define a nested context called InnerCtx in the parent context
MyContext. The example also shows the syntax required when making a reference to a user-defined data type
in the nested context, for example, (field6 : type of [Link].b;).
The type of keyword is only required if referencing an element in an entity or in a structured type; types in
another context can be referenced directly, without the type of keyword. The nesting depth for CDS contexts
is restricted by the limits imposed on the length of the database identifier for the name of the corresponding
SAP HANA database artifact (for example, table, view, or type); this is currently limited to 126 characters
(including delimiters).
Note
The context itself does not have a corresponding artifact in the SAP HANA catalog; the context only
influences the names of SAP HANA catalog artifacts that are generated from the artifacts defined in a given
CDS context, for example, a table or a structured type.
namespace [Link].myapp1;
@Schema: 'MySchema'
context MyContext {
// Nested contexts
context InnerCtx {
Entity MyEntity {
…
};
Type CtxType {
a : Integer;
b : String(59);
};
};
type MyType1 {
field1 : Integer;
field2 : String(40);
field3 : Decimal(22,11);
field4 : Binary(11);
};
type MyType2 {
field1 : String(50);
field2 : MyType1;
};
type MyType3 {
field1 : UTCTimestamp;
field2 : MyType2;
};
The sequence of definitions inside a block of CDS code (for example, entity or context) does not matter for
the scope rules; a binding of an artifact type and name is valid within the confines of the smallest block of code
containing the definition, except in inner code blocks where a binding for the same identifier remains valid. This
rules means that the definition of nameX in an inner block of code hides any definitions of nameX in outer code
blocks.
Note
An identifier may be used before its definition without the need for forward declarations.
context OuterCtx
{
type MyType1 : Integer;
type MyType2 : LocalDate;
context InnerCtx
{
type Use1 : MyType1; // is a String(20)
type Use2 : MyType2; // is a LocalDate
type MyType1 : String(20);
};
type invalidUse : Use1; // invalid: Use1 is not
// visible outside of InnerCtx
type validUse : InnerCtx.Use1; // ok
};
No two artifacts (including namespaces) can be defined whose absolute names are the same or are different
only in case (for example, MyArtifact and myartifact), even if their artifact type is different (entity and
view). When searching for artifacts, CDS makes no assumptions which artifact kinds can be expected at certain
source positions; it simply searches for the artifact with the given name and performs a final check of the
artifact type.
The following example demonstrates how name resolution works with multiple nested contexts, Inside context
NameB, the local definition of NameA shadows the definition of the context NameA in the surrounding scope. This
means that the definition of the identifier NameA is resolved to Integer, which does not have a sub-
component T1. The result is an error, and the compiler does not continue the search for a “better” definition of
NameA in the scope of an outer (parent) context.
context OuterCtx
{
context NameA
{
type T1 : Integer;
Related Information
CDS supports built-in annotations, for example, @Catalog, @Schema, and @nokey, which are important
elements of the CDS documents used to define CDS-compliant catalog objects. However, you can define your
own custom annotations, too.
Example
namespace mycompany.myapp1;
@Schema : 'MYSCHEMA'
context Books {
@[Link]: #COLUMN
@[Link]: [ { name : 'MYINDEX1', unique : true, order : #DESC,
elementNames : ['ISBN'] } ]
entity BOOK {
key Author : String(100);
key BookTitle : String(100);
ISBN : Integer not null;
Publisher : String(100);
};
@[Link] : #COLUMN
@nokey
entity MyKeylessEntity
{
element1 : Integer;
element2 : UTCTimestamp;
@[Link]: { enabled: true }
element3 : String(7);
};
@GenerateTableType : false
Type MyType1 {
field1 : Integer;
field2 : Integer;
field3 : Integer;
};
};
The following list indicates the annotations you can use in a CDS document:
● @Catalog
● @nokey
● @Schema
● @GenerateTableType
● @SearchIndex
● @WithStructuredPrivilegeCheck
@Catalog
The @Catalog annotation supports the following parameters, each of which is described in detail in a dedicated
section below:
● @[Link]
Specify the type and scope of index to be created for the CDS entity, for example: name, order, unique/
non-unique
● @[Link]
Specify the table type for the CDS entity, for example, column, row, global temporary.
You use the @[Link] annotation to define an index for a CDS entity. The @[Link] annotation used
in the following code example ensures that an index called Index1 is created for the entity MyEntity1 along
with the index fields fint and futcshrt. The order for the index is ascending (#ASC) and the index is unique.
namespace [Link].myapp1;
@[Link] : #COLUMN
@Schema: 'MYSCHEMA'
@[Link]:[ { name:'Index1', unique:true, order:#ASC, elementNames:['fint',
'futcshrt' ] } ]
entity MyEntity1 {
key fint:Integer;
fstr :String(5000);
fstr15 :String(51);
fbin :Binary(4000);
fbin15 :Binary(51);
fint32 :Integer64;
fdec53 :Decimal(5,3);
fdecf :DecimalFloat;
fbinf :BinaryFloat;
futcshrt:UTCDateTime not null;
flstr :LargeString;
flbin :LargeBinary;
};
You can define the following values for the @[Link] annotation:
You use the @[Link] annotation to define the type of CDS entity you want to create. The
@[Link] annotation determines the storage engine in which the underlying table is created.
namespace [Link].myapp1;
@Schema: 'MYSCHEMA'
context MyContext1 {
@[Link] : #COLUMN
entity MyEntity1 {
key ID : Integer;
name : String(30);
};
@[Link] : #ROW
entity MyEntity2 {
key ID : Integer;
name : String(30);
};
@[Link] : #GLOBAL_TEMPORARY
entity MyEntity3 {
ID : Integer;
name : String(30);
};
};
You can define the following values for the @[Link] annotation:
● #COLUMN
Create a column-based table. If the majority of table access is through a large number of tuples, with only a
few selected attributes, use COLUMN-based storage for your table type.
● #ROW
Create a row-based table. If the majority of table access involves selecting a few records, with all attributes
selected, use ROW-based storage for your table type.
● #GLOBAL_TEMPORARY
Set the scope of the created table. Data in a global temporary table is session-specific; only the owner
session of the global temporary table is allowed to insert/read/truncate the data. A global temporary table
Note
The SAP HANA database uses a combination of table types to enable storage and interpretation in both
ROW and COLUMN forms. If no table type is specified in the CDS entity definition, the default value
#COLUMN is applied to the table created on activation of the design-time entity definition.
@nokey
An entity usually has one or more key elements, which are flagged in the CDS entity definition with the key
keyword. The key elements become the primary key of the generated SAP HANA table and are automatically
flagged as “not null”. Structured elements can be part of the key, too. In this case, all table fields resulting from
the flattening of this structured field are part of the primary key.
Note
However, you can also define an entity that has no key elements. If you want to define an entity without a key,
use the @nokey annotation. In the following code example, the @nokey annotation ensures that the entity
MyKeylessEntity defined in the CDS document creates a column-based table where no key element is
defined.
namespace [Link].myapp1;
@Schema: 'MYSCHEMA'
@[Link] : #COLUMN
@nokey
entity MyKeylessEntity
{
element1 : Integer;
element2 : UTCTimestamp;
element3 : String(7);
};
@Schema
The @Schema annotation is only allowed as a top-level definition in a CDS document. In the following code
example @Schema ensures that the schema MYSCHEMA is used to contain the entity MyEntity1, a column-
based table.
namespace [Link].myapp1;
@Schema: 'MYSCHEMA'
@[Link] : #COLUMN
entity MyEntity1 {
key ID : Integer;
name : String(30);
};
If the schema specified with the @Schema annotation does not already exist, an activation error is
displayed and the entity-creation process fails.
The schema name must adhere to the SAP HANA rules for database identifiers. In addition, a schema name
must not start with the letters SAP*; the SAP* namespace is reserved for schemas used by SAP products and
applications.
@GenerateTableType
For each structured type defined in a CDS document, an SAP HANA table type is generated, whose name is
built by concatenating the elements of the CDS document containing the structured-type definition and
separating the elements by a dot delimiter (.). The new SAP HANA table types are generated in the schema
that is specified in the schema annotation of the respective top-level artifact in the CDS document containing
the structured types.
Note
Table types are only generated for direct structure definitions; no table types are generated for derived
types that are based on structured types.
If you want to use the structured types inside a CDS document without generating table types in the catalog,
use the annotation @GenerateTableType : false.
@SearchIndex
The annotation @SearchIndex enables you to define which of the columns should be indexed for search
capabilities, for example, {enabled : true}. To extend the index search definition, you can use the
properties text or fuzzy to specify if the index should support text-based or fuzzy search, as illustrated in the
following example:
entity MyEntity100
{
element1 : Integer;
@[Link]: { enabled: true }
element2 : LargeString;
@[Link]: { enabled: true }
element3 : String(7);
};
Tip
For more information about setting up search features and using the search capability, see the SAP HANA
Search Developer Guide .
The annotation @WithStructuredPrivilegeCheck enables you to control access to data (for example, in a
view) by means of privileges defined with the Data Control Language (DCL), as illustrated in the following
example:
@WithStructuredPrivilegeCheck
view MyView as select from Foo {
<select_list>
} <where_groupBy_Having_OrderBy>;
Related Information
The built-in core annotations that SAP HANA provides, for example, @Schema, @Catalog, or @nokey, are
located in the namespace [Link]; the same namespace is used to store all the primitive types, for example,
[Link]::integer and [Link]::SMALLINT.
However, the CDS syntax also enables you to define your own annotations, which you can use in addition to the
existing “core” annotations. The rules for defining a custom annotation in CDS are very similar way the rules
that govern the definition of a user-defined type. In CDS, an annotation can be defined either inside a CDS
context or as the single, top-level artifact in a CDS document. The custom annotation you define can then be
assigned to other artifacts in a CDS document, in the same way as the core annotations, as illustrated in the
following example:
@[Link] : #ROW
@MyAnnotation : 'foo'
entity MyEntity {
key Author : String(100);
key BookTitle : String(100);
ISBN : Integer not null;
Publisher : String(100);
}
● Scalar annotations
● Structured annotations
● Annotation arrays
In annotation definitions, you can use both the enumeration type and the Boolean type, as illustrated in the
following example.
type Color : String(10) enum { red = 'rot'; green = 'grün'; blue = 'blau'; };
annotation MyAnnotation_3 : Color;
annotation MyAnnotation_4 : Boolean;
Structured Annotations
annotation MyAnnotation_5 {
a : Integer;
b : String(20);
c : Color;
d : Boolean;
};
The following example shows how to nest annotations in an anonymous annotation structure.
annotation MyAnnotation_7 {
a : Integer;
b : String(20);
c : Color;
d : Boolean;
s {
a1 : Integer;
b1 : String(20);
c1 : Color;
d1 : Boolean;
};
};
Array Annotations
When you have defined an annotation, the user-defined annotation can be used to annotate other definitions. It
is possible to use the following types of user-defined annotations in a CDS document:
Scalar annotations [page 185] For use with simple integer or string annotations and enumeration or
Boolean types
Structured annotations [page 186] For use where you need to create a simple annotation structure or nest
an annotation in an anonymous annotation structure
Annotation arrays [page 186] For use where you need to assign the same annotation several times to
the same object.
Scalar Annotations
@MyAnnotation_1 : 18
type MyType1 : Integer;
@MyAnnotation_2 : 'sun'
@MyAnnotation_1 : 77
type MyType2 : Integer;
@MyAnnotation_2 : 'sun'
@MyAnnotation_2 : 'moon' // error: assigning the same annotation twice is not
allowed.
type MyType3 : Integer;
Note
It is not allowed to assign an annotation to the same object more than once. If several values of the same
type are to be annotated to a single object, use an array-like annotation.
For annotations that have enumeration type, the enum values can be addressed either by means of their fully
qualified name, or by means of the shortcut notation (using the hash (#) sign. It is not allowed to use a literal
value, even if it matches a literal of the enum definition.
@MyAnnotation_3 : #red
type MyType4 : Integer;
@MyAnnotation_3 : [Link]
type MyType5 : Integer;
@MyAnnotation_3 : 'rot' // error: no literals allowed, use enum symbols
type MyType6 : Integer;
For Boolean annotations, only the values “true” or “false” are allowed, and a shortcut notation is available
for the value “true”, as illustrated in the following examples:
@MyAnnotation_4 : true
type MyType7 : Integer;
@MyAnnotation_4 // same as explicitly assigning the value “true”
Structured Annotations
Structured annotations can be assigned either as a complete unit or, alternatively, one element at a time. The
following example show how to assign a whole structured annotation:
The following example shows how to assign the same structured annotation element by element.
Note
@MyAnnotation_5.a : 12
@MyAnnotation_5.b : 'Jupiter'
@MyAnnotation_5.c : #blue
@MyAnnotation_5.d : false
type MyType12 : Integer;
@MyAnnotation_5.c : #green
type MyType13 : Integer;
@MyAnnotation_5.c : #blue
@MyAnnotation_5.d // shortcut notation for Boolean (true)
type MyType14 : Integer;
It is not permitted to assign the same annotation element more than once; assigning the same annotation
element more than once in a structured annotation causes an activation error.
Array-like Annotations
Although it is not allowed to assign the same annotation several times to the same object, you can achieve the
same effect with an array-like annotation, as illustrated in the following example:
@MyAnnotation_8 : [1,3,5,7]
type MyType30 : Integer;
@MyAnnotation_9 : ['Earth', 'Moon']
type MyType31 : Integer;
@MyAnnotation_10 : [{ a: 52, b: 'Mercury'}, { a: 53, b: 'Venus'}]
type MyType32 : Integer;
The Core Data Services (CDS) syntax enables you to insert comments into object definitions.
Example:
Comment Formats in CDS Object Definitions
namespace [Link].myapp1;
/**
* multi-line comment,
* for doxygen-style,
* comments and annotations
*/
type Type1 {
element Fstr: String( 5000 ); // end-of-line comment
Flstr: LargeString;
/*inline comment*/ Fbin: Binary( 4000 );
element Flbin: LargeBinary;
Fint: Integer;
element Fint64: Integer64;
Ffixdec: Decimal( 34, 34 /* another inline comment */);
element Fdec: DecimalFloat;
Fflt: BinaryFloat;
//complete line comment element Flocdat: LocalDate; LocalDate
temporarily switched off
//complete line comment Floctim: LocalTime;
element Futcdatim: UTCDateTime;
Futctstmp: UTCTimestamp;
};
Overview
You can use the forward slash (/) and the asterisk (*) characters to add comments and general information to
CDS object-definition files. The following types of comment are allowed:
● In-line comment
● End-of-line comment
● Complete-line comment
● Multi-line comment
The in-line comment enables you to insert a comment into the middle of a line of code in a CDS document. To
indicate the start of the in-line comment, insert a forward-slash (/) followed by an asterisk (*) before the
comment text. To signal the end of the in-line comment, insert an asterisk followed by a forward-slash
character (*/) after the comment text, as illustrated by the following example:.
End-of-Line Comment
The end-of-line comment enables you to insert a comment at the end of a line of code in a CDS document. To
indicate the start of the end-of-line comment, insert two forward slashes (//) before the comment text, as
illustrated by the following example:.
Complete-Line Comment
The complete-line comment enables you to tell the parser to ignore the contents of an entire line of CDS code.
The comment out a complete line, insert two backslashes (//) at the start of the line, as illustrated in the
following example:
Multi-Line Comments
The multi-line comment enables you to insert comment text that extends over multiple lines of a CDS
document. To indicate the start of the multi-line comment, insert a forward-slash (/) followed by an asterisk (*)
at the start of the group of lines you want to use for an extended comment (for example, /*). To signal the end
of the multi-line comment, insert an asterisk followed by a forward-slash character (*/). Each line between the
start and end of the multi-line comment must start with an asterisk (*), as illustrated in the following example:
/*
* multiline,
* doxygen-style
* comments and annotations
*/
The entity is the core artifact for persistence-model definition using the CDS syntax. You create a database
entity as a design-time file in the SAP HANA repository.
Prerequisites
Context
In the SAP HANA database, as in other relational databases, a CDS entity is a table with a set of data elements
that are organized using columns and rows. SAP HANA Extended Application Services (SAP HANA XS) enables
you to use the CDS syntax to create a database entity as a design-time file in the repository. Activating the CDS
entity creates the corresponding table in the specified schema. To create a CDS entity-definition file in the
repository, perform the following steps:
Procedure
a. Right-click the folder where you want to save the entity-definition file and choose New Other...
Database Development DDL Source File in the context-sensitive popup menu.
Tip
File extensions are important. If you are using SAP HANA studio to create artifacts in the SAP
HANA Repository, the file-creation wizard adds the required file extension automatically (for
example, [Link]) and, if appropriate, enables direct editing of the new file in the
corresponding editor.
c. Choose Finish to save the changes and commit the new entity-definition file in the repository.
5. Define the structure of the CDS entity.
If the new entity-definition file is not automatically displayed by the file-creation wizard, in the Project
Explorer view double-click the entity-definition file you created in the previous step, for example,
[Link], and add the catalog- and entity-definition code to the file:
Note
The following code example is provided for illustration purposes only. If the schema you specify does
not exist, you cannot activate the new CDS entity.
namespace [Link].myapp1;
@Schema : 'MYSCHEMA'
@[Link] : #COLUMN
@[Link] : [ { name : 'MYINDEX1', unique : true, order :#DESC,
elementNames : ['ISBN'] } ]
entity MyEntity {
key Author : String(100);
key BookTitle : String(100);
ISBN : Integer not null;
Publisher : String(100);
};
Note
Saving a file in a shared project automatically commits the saved version of the file to the repository.
You do not need to explicitly commit it again.
Note
If you cannot activate the new CDS artifact, check that the specified schema already exists and
that there are no illegal characters in the name space, for example, the hyphen (-).
8. Ensure access to the schema where the new CDS catalog objects are created.
After activation in the repository, a schema object is only visible in the catalog to the _SYS_REPO user. To
enable other users, for example the schema owner, to view the newly created schema and the objects it
contains, you must grant the user the required SELECT privilege for the appropriate schema object.
Note
If you already have the appropriate SELECT privilege, you do not need to perform this step.
call
_SYS_REPO.GRANT_SCHEMA_PRIVILEGE_ON_ACTIVATED_CONTENT('select','<SCHEMANAME
>','<username>');
Tip
Alternatively, to open the table-definition view of the SAP HANA catalog tools, press F3 when the
CDS entity is in focus in the CDS editor.
Related Information
A CDS entity has a specified number of columns, defined at the time of entity creation, but can have any
number of rows. Database entities also typically have meta-data associated with them; the meta-data might
include constraints on the entity or on the values within particular columns. SAP HANA Extended Application
Services (SAP HANA XS) enables you to create a database entity as a design-time file in the repository. All
repository files including your entity definition can be transported to other SAP HANA systems, for example, in
a delivery unit. You can define the entity using CDS-compliant DDL.
Note
A delivery unit is the medium SAP HANA provides to enable you to assemble all your application-related
repository artifacts together into an archive that can be easily exported to other systems.
namespace [Link].myapp1;
@Schema : 'MYSCHEMA'
@[Link] : #COLUMN
@[Link] : [ { name : 'MYINDEX1', unique : true, order :#DESC,
elementNames : ['ISBN'] } ]
entity MyTable {
key Author : String(100);
key BookTitle : String(100);
ISBN : Integer not null;
Publisher : String(100);
};
If you want to create a CDS-compliant database entity definition as a repository file, you must create the entity
as a flat file and save the file containing the DDL entity dimensions with the suffix .hdbdd, for example,
[Link]. The new file is located in the package hierarchy you establish in the SAP HANA repository.
The file location corresponds to the namespace specified at the start of the file, for example,
[Link].myapp1 or [Link].app2. You can activate the repository files at any point in time to create
the corresponding runtime object for the defined table.
Note
On activation of a repository file, the file suffix, for example, .hdbdd, is used to determine which runtime
plug-in to call during the activation process. The plug-in reads the repository file selected for activation, in
this case a CDS-compliant entity, parses the object descriptions in the file, and creates the appropriate
runtime objects.
When a CDS document is activated, the activation process generates a corresponding catalog object for each
of the artifacts defined in the document; the location in the catalog is determined by the type of object
generated. For example, the corresponding database table for a CDS entity definition is generated in the
following catalog location:
You can expand the definition of an entity element beyond the element's name and type by using element
modifiers. For example, you can specify if an entity element is the primary key or part of the primary key. The
following entity element modifiers are available:
● key
Defines if the specified element is the primary key or part of the primary key for the specified entity.
Note
Structured elements can be part of the key, too. In this case, all table fields resulting from the flattening
of this structured field are part of the primary key.
entity MyEntity {
key MyKey : Integer;
key MyKey2 : Integer null; // illegal combination
key MyKey3 : Integer default 2;
elem2 : String(20) default 'John Doe';
elem3 : String(20) default 'John Doe' null;
elem4 : String default 'Jane Doe' not null;
};
Spatial Data
CDS entities support the use of spatial data types such as hana.ST_POINT or hana.ST_GEOMETRY to store
geo-spatial coordinates. Spatial data is data that describes the position, shape, and orientation of objects in a
defined space; the data is represented as two-dimensional geometries in the form of points, line strings, and
polygons.
Related Information
Element modifiers enable you to expand the definition of an entity element beyond the element's name and
type. For example, you can specify if an entity element is the primary key or part of the primary key.
Example
entity MyEntity {
key MyKey : Integer;
elem2 : String(20) default 'John Doe';
elem3 : String(20) default 'John Doe' null;
elem4 : String default 'Jane Doe' not null;
};
entity MyEntity1 {
key
You can expand the definition of an entity element beyond the element's name and type by using element
modifiers. For example, you can specify if an entity element is the primary key or part of the primary key. The
following entity element modifiers are available:
● key
Defines if the element is the primary key or part of the primary key for the specified entity. You cannot use
the key modifier in the following cases:
○ In combination with a null modifier. The key element is non null by default because NULL cannot
be used in the key element.
Note
Structured elements can be part of the key, too. In this case, all table fields resulting from the flattening
of this structured field are part of the primary key.
null
null defines if the entity element can (null) or cannot (not null) have the value NULL. If neither null nor
not null is specified for the element, the default value null applies (except for the key element), which
means the element can have the value NULL. If you use the null modifier, note the following points:
Caution
The keywords nullable and not nullable are no longer valid; they have been replaced for SPS07 with
the keywords null and not null, respectively. The keywords null and not null must appear at the
end of the entity element definition, for example, field2 : Integer null;.
● The not null modifier can only be added if the following is true:
entity WithNullAndNotNull
{
key id : Integer;
field1 : Integer;
field2 : Integer null; // same as field1, null is default
field3 : Integer not null;
};
default
default <literal_value>
For each scalar element of an entity, a default value can be specified. The default element identifier defines
the default value for the element in the event that no value is provided during an INSERT operation.
Note
The syntax for the literals is defined in the primitive data-type specification.
entity WithDefaults
{
key id : Integer;
field1 : Integer default -42;
field2 : Integer64 default 9223372036854775807;
field3 : Decimal(5, 3) default 12.345;
field4 : BinaryFloat default 123.456e-1;
field5 : LocalDate default date'2013-04-29';
field6 : LocalTime default time'[Link]';
field7 : UTCDateTime default timestamp'2013-05-01 [Link]';
field8 : UTCTimestamp default timestamp'2013-05-01 [Link]';
field9 : Binary(32) default x'0102030405060708090a0b0c0d0e0[...]';
field10 : String(10) default 'foo';
};
entity MyEntity1 {
key id : Integer;
a : integer;
b : integer;
c : integer generated always as a+b;
The SAP HANA SQL clause generated always as <expression> is available for use in CDS entity
definitions; it specifies the expression to use to generate the column value at run time. An element that is
defined with generated always as <expression> corresponds to a field in the database table that is
present in the persistence and has a value that is computed as specified in the expression, for example, “a+b”.
Restriction
For use in XS advanced only; it is not possible to use generated calculated elements in XS classic. Please
also note that the generated always as <expression> clause is only for use with column-based
tables.
“Generated” fields and “calculated” field differ in the following way. Generated fields are physically present in
the database table; values are computed on INSERT and need not be computed on SELECT. Calculated fields
are not actually stored in the database table; they are computed when the element is “selected”. Since the
value of the generated field is computed on INSERT, the expression used to generate the value must not
contain any non-deterministic functions, for example: current_timestamp, current_user,
current_schema, and so on.
entity MyEntity2 {
autoId : Integer generated always as identity ( start with 10 increment by
2 );
name : String(100);
};
The SAP HANA SQL clause generated as identity is available for use in CDS entity definitions; it enables
you to specify an identity column. An element that is defined with generated as identity corresponds to
a field in the database table that is present in the persistence and has a value that is computed as specified in
the sequence options defined in the identity expression, for example, ( start with 10 increment by
2 ).
In the example illustrated here, the name of the generated column is autoID, the first value in the column is
“10”; the identity expression ( start with 10 increment by 2 ) ensures that subsequent values in
the column are incremented by 2, for example: 12, 14, and so on.
Restriction
For use in XS advanced only; it is not possible to define an element with IDENTITY in XS classic. Please also
note that the generated always as identity clause is only for use with column-based tables.
You can use either always or by default in the clause generated as identity, as illustrated in the
examples in this section. If always is specified, then values are always generated; if by default is specified,
then values are generated by default.
entity MyEntity2 {
autoId : Integer generated by default as identity ( start with 10 increment
by 2 );
name : String(100);
Restriction
CDS does not support the use of reset queries, for example, RESET BY <subquery>.
The following table shows the migration strategy that is used for modifications to any given column; the
information shows which actions are performed and what strategy is used to preserve content. During the
migration, a comparison is performed on the column type, the generation kind, and the expression, if available.
From an end-user perspective, the result of a column modification is either a preserved or new value. The aim
of any modification to an entity (table) is to cause as little loss as possible.
Technically, columns are either dropped and added or a completely new “shadow” table is created into which
the existing content is copied. The shadow table will then replace the original table.
generated by de
Before column/ Af generated always as generated always as fault as identity
ter row Plain As <expr> <expr> identity <expr> <expr>
Related Information
The entity is the core design-time artifact for persistence model definition using the CDS syntax.
Example
Note
This example is not a working example; it is intended for illustration purposes only.
namespace Pack1."pack-age2";
@Schema: 'MySchema'
context MyContext {
entity MyEntity1
{
key id : Integer;
name : String(80);
};
@Catalog:
{ tableType : #COLUMN,
index : [
{ name:'Index1', order:#DESC, unique:true, elementNames:['x', 'y'] },
{ name:'Index2', order:#DESC, unique:false, elementNames:['x', 'a'] }
]
}
Note
For series data, you can use either equidistant or equidistant piecewise, but not both at the same
time. The example above is for illustration purposes only.
Overview
Entity definitions resemble the definition of structured types, but with the following additional features:
On activation in the SAP HANA repository, each entity definition in CDS generates a database table. The name
of the generated table is built according to the same rules as for table types, for example,
Pack1.Pack2::[Link].
Note
The CDS name is restricted by the limits imposed on the length of the database identifier for the name of
the corresponding SAP HANA database artifact (for example, table, view, or type); this is currently limited
to 126 characters (including delimiters).
Key Definition
type MyStruc2
{
field1 : Integer;
field2 : String(20);
};
entity MyEntity2
{
key id : Integer;
name : String(80);
key str : MyStruc2;
};
Usually an entity must have a key; you use the keyword key to mark the respective elements. The key elements
become the primary key of the generated SAP HANA table and are automatically flagged as not null. Key
elements are also used for managed associations. Structured elements can be part of the key, too. In this case,
all table fields resulting from the flattening of this structured element are part of the primary key.
Note
Index Definition
@Catalog:
{ tableType : #COLUMN,
index : [
{ name:'Index1', order:#DESC, unique:true, elementNames:['field1',
'field2'] },
{ name:'Index2', order:#ASC, unique:false, elementNames:['field1',
'field7'] }
]
}
● name : '<IndexName>'
The name of the index to be generated for the specified entity, for example, name:'myIndex'
● order
Create a table index sorted in ascending or descending order. The order keywords #ASC and #DESC can be
only used in the BTREE index (for the maintenance of sorted data) and can be specified only once for each
index.
○ order : #ASC
Creates an index for the CDS entity and sorts the index fields in ascending logical order, for example: 1,
2, 3...
○ order : #DESC
Creates a index for the CDS entity and sorts the index fields in descending logical order, for example:
3, 2, 1...
● unique
Creates a unique index for the CDS entity. In a unique index, two rows of data in a table cannot have
identical key values.
○ unique : true
Creates a unique index for the CDS entity. The uniqueness is checked and, if necessary, enforced each
time a key is added to (or changed in) the index and, in addition, each time a row is added to the table.
○ unique : false
Creates a non-unique index for the CDS entity. A non-unique index is intended primarily to improve
query performance, for example, by maintaining a sorted order of values for data that is queried
frequently.
● elementNames : ['<name1>', '<name2>' ]
The names of the fields to use in the index; the elements are specified for the entity definition, for example,
elementNames:['field1', 'field2' ]
Table-Type Definition
namespace [Link].myapp1;
@Schema: 'MYSCHEMA'
context MyContext1 {
@[Link] : #COLUMN
entity MyEntity1 {
key ID : Integer;
name : String(30);
};
@[Link] : #ROW
entity MyEntity2 {
key ID : Integer;
name : String(30);
};
@[Link] : #GLOBAL_TEMPORARY
entity MyEntity3 {
ID : Integer;
name : String(30);
};
@[Link] : #GLOBAL_TEMPORARY_COLUMN
entity MyTempEntity {
a : Integer;
You use the @[Link] or @Catalog: { tableType: #<TYPE> } annotation to define the type
of CDS entity you want to create, for example: column- or row-based or global temporary. The
@[Link] annotation determines the storage engine in which the underlying table is created. The
following table lists and explains the permitted values for the @[Link] annotation:
#ROW Create a row-based table. If the majority of table access involves selecting a few re
cords, with all attributes selected, use ROW-based storage for your table type.
#GLOBAL_TEMPORARY Set the scope of the created table. Data in a global temporary table is session-spe
cific; only the owner session of the global temporary table is allowed to insert/read/
truncate the data. A global temporary table exists for the duration of the session,
and data from the global temporary table is automatically dropped when the ses
sion is terminated. Note that a temporary table cannot be changed when the table
is in use by an open session, and a global temporary table can only be dropped if
the table does not have any records.
#GLOBAL_TEMPORARY_COLUMN Set the scope of the table column. Global temporary column tables cannot have ei
ther a key or an index.
Note
The SAP HANA database uses a combination of table types to enable storage and interpretation in both
ROW and COLUMN forms. If no table type is specified in the CDS entity definition, the default value
#COLUMN is applied to the table created on activation of the design-time entity definition.
Calculated Fields
The definition of an entity can contain calculated fields, as illustrated in type “z” the following example:
Sample Code
entity MyCalcField {
a : Integer;
b : Integer;
c : Integer = a + b;
s : String(10);
t : String(10) = upper(s);
x : Decimal(20,10);
y : Decimal(20,10);
z : Decimal(20,10) = power(ln(x)*sin(y), a);
};
● The definition of a calculated field must not contain other calculated fields, associations, aggregations, or
subqueries.
● A calculated field cannot be key.
● No index can be defined on a calculated field.
● A calculated field cannot be used as foreign key for a managed association.
Note
In SAP HANA tables, you can define columns with the additional configuration “GENERATED ALWAYS AS”.
These columns are physically present in the table, and all the values are stored. Although these columns
behave for the most part like ordinary columns, their value is computed upon insertion rather than
specified in the INSERT statement. This is in contrast to calculated field, for which no values are actually
stored; the values are computed upon SELECT.
technical configuration
The definition of an entity can contain a section called technical configuration, which you use to define
the elements listed in the following table:
● Storage type
● Indexes
● Full text indexes
Note
The syntax in the technical configuration section is as close as possible to the corresponding clauses in the
SAP HANA SQL Create Table statement. Each clause in the technical configuration must end with a
semicolon.
Storage type
In the technical configuration for an entity, you can use the store keyword to specify the storage type (“row”
or “column”) for the generated table, as illustrated in the following example. If no store type is specified, a
“column” store table is generated by default.
Sample Code
entity MyEntity {
key id : Integer;
a : Integer;
b : Integer;
t : String(100);
s {
u : String(100);
};
} technical configuration {
row store;
Restriction
It is not possible to use both the @[Link] annotation and the technical configuration (for
example, row store) at the same time to define the storage type for an entity.
Indexes
In the technical configuration for an entity, you can use the index and unique index keywords to specify the
index type for the generated table. For example: “asc” (ascending) or “desc” (descending) describes the index
order, and unique specifies that the index is unique, where no two rows of data in the indexed entity can have
identical key values.
Sample Code
entity MyEntity {
key id : Integer;
a : Integer;
b : Integer;
t : String(100);
s {
u : String(100);
};
} technical configuration {
index MyIndex1 on (a, b) asc;
unique index MyIndex2 on (c, s) desc;
};
Restriction
It is not possible to use both the @[Link] annotation and the technical configuration (for
example, index) at the same time to define the index type for an entity.
Sample Code
entity MyEntity {
key id : Integer;
a : Integer;
b : Integer;
t : String(100);
s {
u : String(100);
};
} technical configuration {
row store;
index MyIndex1 on (a, b) asc;
unique index MyIndex2 on (a, b) asc;
fulltext index MYFTI1 on (t)
LANGUAGE COLUMN t
LANGUAGE DETECTION ('de', 'en')
MIME TYPE COLUMN s.u
FUZZY SEARCH INDEX off
The <fulltext_parameter_list> is identical to the standard SAP HANA SQL syntax for CREATE
FULLTEXT INDEX. A fuzzy search index in the technical configuration section of an entity definition
corresponds to the @SearchIndex annotation in XS classic and the statement "FUZZY SEARCH INDEX ON"
for a table column in SAP HANA SQL. It is not possible to specify both a full-text index and a fuzzy search index
for the same element.
Restriction
It is not possible to use both the @SearchIndex annotation and the technical configuration (for example,
fulltext index) at the same time.
Spatial Types *
The following example shows how to use the spatial type ST_POINT in a CDS entity definition. In the example
entity Person, each person has a home address and a business address, each of which is accessible via the
corresponding associations. In the Address entity, the geo-spatial coordinates for each person are stored in
element loc using the spatial type ST_POINT (*).
Sample Code
context SpatialData {
entity Person {
key id : Integer;
name : String(100);
homeAddress : Association[1] to Address;
officeAddress : Association[1] to Address;
};
entity Address {
key id : Integer;
street_number : Integer;
street_name : String(100);
zip : String(10);
city : String(100);
loc : hana.ST_POINT(4326);
};
view CommuteDistance as select from Person {
name,
[Link].ST_Distance([Link]) as distance
};
};
CDS enables you to create a table to store series data by defining an entity that includes a series () clause
as an table option and then defining the appropriate parameters and options.
Note
The period for series must be unique and should not be affected by any shift in timestamps.
Sample Code
context SeriesData {
entity MySeriesEntity1 {
key setId : Integer;
t : UTCTimestamp;
value : Decimal(10,4);
series (
series key (setId)
period for series (t)
equidistant increment by interval 0.1 second
);
};
entity MySeriesEntity2 {
key setId : Integer;
t : UTCTimestamp;
value : Decimal(10,4);
series (
series key (setId)
period for series (t)
equidistant piecewise
);
};
};
CDS also supports the creation of a series table called equidistant piecewise using Formula-Encoded
Timestamps (FET). This enables support for data that is not loaded in an order that ensures good
compression. There is no a-priori restriction on the timestamps that are stored, but the data is expected to be
well approximated as piecewise linear with some jitter. The timestamps do not have a single slope/offset
throughout the table; rather, they can change within and among series in the table.
Restriction
The equidistant piecewise specification can only be used in CDS; it cannot be used to create a table
with the SQL command CREATE TABLE.
When a series table is defined as equidistant piecewise, the following restrictions apply:
1. The period includes one column (instant); there is no support for interval periods.
2. There is no support for missing elements. These could logically be defined if the period includes an
interval start and end. Missing elements then occur when we have adjacent rows where the end of the
interval does not equal the start of the interval.
3. The type of the period column must map to the one of the following types: DATE, SECONDDATE, or
TIMESTAMP.
(*) For information about the capabilities available for your license and installation scenario, refer to the
Feature Scope Description for SAP HANA.
Related Information
Migrate a design-time representation of a table from the .hdbtable syntax to the CDS-compliant .hdbdd
syntax while retaining the underlying catalog table and its content.
Prerequisites
Context
In this procedure you replace a design-time representation of a database table that was defined using the
hdbtable syntax with a CDS document that describes the same table (entity) with the CDS-compliant hdbdd
syntax. To migrate an hdbtable artifact to CDS, you must delete the inactive version of the hdbtable object
and create a new hdbdd artifact with the same name and structure.
You must define the target CDS entity manually. The name of the entity and the names of the elements can be
reused from the hdbtable definition. The same applies for the element modifiers, for example, NULL/NOT
NULL, and the default values.
In CDS, there is no way to reproduce the column-comments defined in an hdbtable artifact. You can use
source code comments, for example, '/* */' or '//', however, the comments do not appear in the
catalog table after activation of the new CDS artifact.
Procedure
1. Use CDS syntax to create a duplicate of the table you originally defined using the hdbtable syntax.
Note
The new CDS document must have the same name as the original hdbtable artifact, for example,
[Link] and [Link].
The following code shows a simple table [Link] that is defined using the hdbtable syntax.
This is the “source” table for the migration. When you have recreated this table in CDS using the .hdbdd
syntax, you can delete the artifact [Link].
[Link] = "MYSCHEMA";
[Link] = COLUMNSTORE;
[Link] = [
{name = "firstname"; sqlType = NVARCHAR; nullable = false; length = 20;},
{name = "lastname"; sqlType = NVARCHAR; nullable = true; length = 20;
defaultValue = "doe";},
{name = "age"; sqlType = INTEGER; nullable = false;},
{name = "salary"; sqlType = DECIMAL; nullable = false; precision = 7;
scale = 2;}
];
The following code shows the same simple table recreated with the CDS-compliant hdbdd syntax. The new
design-time artifact is called [Link] and is the “target” for the migration operation. Note that
all column names remain the same.
namespace [Link];
@Schema:'MYSCHEMA'
@[Link]:#COLUMN
@nokey
entity Employee {
firstname : String(20) not null;
lastname : String(20) default 'doe';
age : Integer not null;
salary : Decimal(7,2) not null;
};
2. Activate the source (hdbtable) and target (CDS) artifacts of the migration operation.
To replace the old hdbtable artifact with the new hdbdd (CDS) artifact, you must activate both artifacts
(the deleted hdbtable artifact and the new new CDS document) together in a single activation operation,
for example, by performing the activation operation on the folder that contains the two objects. If you do
not activate both artifacts together in one single activation operation, data stored in the table will be lost
since the table is deleted and recreated during the migration process.
In SAP HANA studio, choose the Team Activate all... option to list all inactive objects and select
the objects you want to activate. In the SAP HANA Web-based Workbench, the default setting is
Activate on save, however you can change this behavior to Save only.
Related Information
It is possible to migrate your SAP HANA hdbtable definition to a Core Data Services (CDS) entity that has
equally named but differently typed elements. When recreating the new CDS document, you cannot choose an
arbitrary data type; you must follow the guidelines for valid data-type mappings in the SAP HANA SQL data-
type conversion documentation. Since the SAP HANA SQL documentation does not cover CDS data types you
must map the target type names to CDS types manually.
Note
Remember that most of the data-type conversions depend on the data that is present in the catalog table
on the target system.
If you are planning to migrate SAP HANA (hdbtable) tables to CDS entities, bear in mind the following
important points:
Related Information
Mapping table for SAP HANA (hdbtable) and Core Data Services (CDS) types.
Although CDS defines its own system of data types, the list of types is roughly equivalent to the data types
available in SAP HANA (hdbtable); the difference between CDS data types and SAP HANA data types is
mostly in the type names. The following table lists the SAP HANA (hdbtable) data types and indicates what
the equivalent type is in CDS.
NVARCHAR String
SHORTTEXT String
NCLOB LargeString
TEXT LargeString
VARBINARY Binary
BLOB LargeBinary
INTEGER Integer
INT Integer
BIGINT Integer64
DECIMAL(p,s) Decimal(p,s)
DECIMAL DecimalFloat
DOUBLE BinaryFloat
DAYDATE LocalDate
DATE LocalDate
SECONDTIME LocalTime
TIME LocalTime
SECONDDATE UTCDateTime
LONGDATE UTCTimestamp
TIMESTAMP UTCTimestamp
ALPHANUM [Link]
SMALLINT [Link]
TINYINT [Link]
SMALLDECIMAL [Link]
REAL [Link]
VARCHAR [Link]
CLOB [Link]
BINARY [Link]
ST_POINT hana.ST_POINT
ST_GEOMETRY hana.ST_GEOMETRY
Related Information
A structured type is a data type comprising a list of attributes, each of which has its own data type. You create a
user-defined structured type as a design-time file in the SAP HANA repository.
Prerequisites
Context
SAP HANA Extended Application Services (SAP HANA XS) enables you to use the CDS syntax to create a user-
defined structured type as a design-time file in the repository. Repository files are transportable. Activating the
CDS document creates the corresponding types in the specified schema. To create a CDS document that
defines one or more structured types and save the document in the repository, perform the following steps:
Procedure
Tip
File extensions are important. If you are using SAP HANA studio to create artifacts in the SAP
HANA Repository, the file-creation wizard adds the required file extension automatically (for
example, [Link]) and, if appropriate, enables direct editing of the new file in the
corresponding editor.
c. Choose Finish to save the changes and commit the new the user-defined structured type in the
repository.
5. Define the user-defined structured type in CDS.
If the new user-defined structured type is not automatically displayed by the file-creation wizard, in the
Project Explorer view double-click the user-defined structured type you created in the previous step, for
example, [Link], and add the definition code for the user-defined structured type to
the file:
The following code example is provided for illustration purposes only. If the schema you specify does
not exist, you cannot activate the new CDS document and the structured types are not created.
namespace Package1.Package2;
@Schema: 'MYSCHEMA'
type MyStructuredType
{
aNumber : Integer;
someText : String(80);
otherText : String(80);
};
6. Save the definition file for the CDS user-defined structured type.
Note
Saving a file in a shared project automatically commits the saved version of the file to the repository.
You do not need to explicitly commit the file again.
On activation, the data types appear in the Systems view of the SAP HANA Development perspective under
<SID> Catalog SchemaName Procedures Table Types .
8. Ensure access to the schema where the new CDS catalog objects are created.
After activation in the repository, a schema object is only visible in the catalog to the _SYS_REPO user. To
enable other users, for example the schema owner, to view the newly created schema and the objects it
contains, you must grant the user the required SELECT privilege for the schema object.
Note
If you already have the appropriate SELECT privilege, you do not need to perform this step.
a. In the SAP HANA studio Systems view, right-click the SAP HANA system hosting the repository where
the schema was activated and choose SQL Console in the context-sensitive popup menu.
b. In the SQL console, execute the statement illustrated in the following example, where <SCHEMANAME>
is the name of the newly activated schema, and <username> is the database user ID of the schema
owner:
call
_SYS_REPO.GRANT_SCHEMA_PRIVILEGE_ON_ACTIVATED_CONTENT('select','<SCHEMANAME
>','<username>');
Related Information
User-defined data types reference existing structured types (for example, user-defined) or the individual types
(for example, field, type, or context) used in another data-type definition.
You can use the type keyword to define a new data type in CDS-compliant DDL syntax. You can define the data
type in the following ways:
In the following example, the element definition field2 : MyType1; specifies a new element field2 that is
based on the specification in the user-defined data type MyType1.
Note
If you are using a CDS document to define a single CDS-compliant user-defined data type, the name of the
CDS document must match the name of the top-level data type defined in the CDS document, for example,
with the type keyword.
In the following example, you must save the data-type definition “MyType1” in the CDS document
[Link]. In addition, the name space declared in a CDS document must match the repository
package in which the object the document defines is located.
namespace [Link].myapp1;
@Schema: 'MYSCHEMA' // user-defined structured data types
type MyType1 {
field1 : Integer;
field2 : String(40);
field3 : Decimal(22,11);
field4 : Binary(11);
};
In the following example, you must save the data-type definition “MyType2” in the CDS document
[Link]; the document contains a using directive pointing to the data-type “MyType1” defined in CDS
document [Link].
namespace [Link].myapp1;
using [Link].myapp1::MyType1;
@Schema: 'MYSCHEMA' // user-defined structured data types
type MyType2 {
field1 : String(50);
field2 : MyType1;
};
In the following example, you must save the data-type definition “MyType3” in the CDS document
[Link]; the document contains a using directive pointing to the data-type “MyType2” defined in CDS
document [Link].
namespace [Link].myapp1;
using [Link].myapp1::MyType2;
The following code example shows how to use the type of keyword to define an element using the definition
specified in another user-defined data-type field. For example, field4 : type of field3; indicates that,
like field3, field4 is a LocalDate data type.
namespace [Link].myapp1;
using [Link].myapp1::MyType1;
@Schema: 'MYSCHEMA' // Simple user-defined data types
entity MyEntity1 {
key id : Integer;
field1 : MyType3;
field2 : String(24);
field3 : LocalDate;
field4 : type of field3;
field5 : type of MyType1.field2;
field6 : type of [Link].b; // context reference
};
● Define a new element (field4) using the definition specified in another user-defined element field3:
field4 : type of field3;
● Define a new element field5 using the definition specified in a field (field2) that belongs to another
user-defined data type (MyType1):
field5 : type of MyType1.field2;
● Define a new element (field6) using an existing field (b) that belongs to a data type (CtxType) in another
context (InnerCtx):
field6 : type of [Link].b;
The following code example shows you how to define nested contexts ([Link]) and refer to
data types defined by a user in the specified context.
namespace [Link].myapp1;
@Schema: 'MYSCHEMA'
context MyContext {
// Nested contexts
context InnerCtx {
Entity MyEntity {
…
};
Type CtxType {
a : Integer;
b : String(59);
};
};
type MyType1 {
field1 : Integer;
field2 : String(40);
field3 : Decimal(22,11);
field4 : Binary(11);
};
type MyType2 {
field1 : String(50);
field2 : MyType1;
};
type MyType3 {
Restrictions
CDS name resolution does not distinguish between CDS elements and CDS types. If you define a CDS
element based on a CDS data type that has the same name as the new CDS element, CDS displays an error
message and the activation of the CDS document fails.
Caution
In an CDS document, you cannot define a CDS element using a CDS type of the same name; you must
specify the context where the target type is defined, for example, [Link].
The following example defines an association between a CDS element and a CDS data type both of which are
named doobidoo. The result is an error when resolving the names in the CDS document; CDS expects a type
named doobidoo but finds an CDS entity element with the same name that is not a type.
context MyContext2 {
type doobidoo : Integer;
entity MyEntity {
key id : Integer;
doobidoo : doobidoo; // error: type expected; doobidoo is not a type
};
};
The following example works, since the explicit reference to the context where the type definition is located
([Link]) enables CDS to resolve the definition target.
context MyContext {
type doobidoo : Integer;
entity MyEntity {
key id : Integer;
doobidoo : [Link]; // OK
};
};
Note
To prevent name clashes between artifacts that are types and those that have a type assigned to them,
make sure you keep to strict naming conventions. For example, use an uppercase first letter for MyEntity,
MyView and MyType; use a lowercase first letter for elements myElement.
A structured type is a data type comprising a list of attributes, each of which has its own data type. The
attributes of the structured type can be defined manually in the structured type itself and reused either by
another structured type or an entity.
SAP HANA Extended Application Services (SAP HANA XS) enables you to create a database structured type as
a design-time file in the repository. All repository files including your structured-type definition can be
transported to other SAP HANA systems, for example, in a delivery unit. You can define the structured type
using CDS-compliant DDL.
Note
A delivery unit is the medium SAP HANA provides to enable you to assemble all your application-related
repository artifacts together into an archive that can be easily exported to other systems.
When a CDS document is activated, the activation process generates a corresponding catalog object for each
of the artifacts defined in the document; the location in the catalog is determined by the type of object
generated. For example, the corresponding table type for a CDS type definition is generated in the following
catalog location:
In a structured user-defined type, you can define original types (aNumber in the following example) or
reference existing types defined elsewhere in the same type definition or another, separate type definition
(MyString80). If you define multiple types in a single CDS document, for example, in a parent context, each
structure-type definition must be separated by a semi-colon (;).
namespace Package1.Package2;
@Schema: 'MySchema'
type MyString80: String(80);
A using directive is required to resolve the reference to the data type specified in otherText :
MyString80;, as illustrated in the following example:
namespace Package1.Package2;
Note
If you are using a CDS document to specify a single CDS-compliant data type, the name of the CDS
document ([Link]) must match the name of the top-level data type defined in the CDS
document, for example, with the type keyword.
Since user-defined types can make use of other user-defined types, you can build nested structured types, as
illustrated in the following example:
namespace Package1.Package2;
using Package1.Package2::MyString80;
using Package1.Package2::MyStruct;
@Schema: 'MYSCHEMA'
context NestedStructs {
type MyNestedStruct
{
name : MyString80;
nested : MyStruct; // defined in a separate type
};
type MyDeepNestedStruct
{
text : LargeString;
nested : MyNestedStruct;
};
type MyOtherInt : type of [Link]; // => Integer
type MyOtherStruct : type of [Link]; // => MyStruct
};
You can also define a type based on an existing type that is already defined in another user-defined structured
type, for example, by using the type of keyword, as illustrated in the following example:
For each structured type, a SAP HANA table type is generated, whose name is built by concatenating the
following elements of the CDS document containing the structured-type definition and separating the
elements by a dot delimiter (.):
The new SAP HANA table types are generated in the schema that is specified in the schema annotation of the
respective top-level artifact in the CDS document containing the structured types.
Note
To view the newly created objects, you must have the required SELECT privilege for the schema object in
which the objects are generated.
The columns of the table type are built by flattening the elements of the type. Elements with structured types
are mapped to one column per nested element, with the column names built by concatenating the element
names and separating the names by dots ".".
Tip
If you want to use the structured types inside a CDS document without generating table types in the
catalog, use the annotation @GenerateTableType : false.
Table types are only generated for direct structure definitions; in the following example, this would include:
MyStruct, MyNestedStruct, and MyDeepNestedStruct. No table types are generated for derived types
that are based on structured types; in the following example, the derived types include: MyS, MyOtherInt,
MyOtherStruct.
Example
namespace Pack1."pack-age2";
@Schema: 'MySchema'
context MyModel
{
type MyInteger : Integer;
type MyString80 : String(80);
type MyDecimal : Decimal(10,2);
type MyStruct
{
aNumber : Integer;
someText : String(80);
otherText : MyString80; // defined in example above
};
type MyS : MyStruct;
type MyOtherInt : type of [Link];
type MyOtherStruct : type of [Link];
type MyNestedStruct
{
name : MyString80;
nested : MyS;
};
type MyDeepNestedStruct
Related Information
A structured type is a data type comprising a list of attributes, each of which has its own data type. The
attributes of the structured type can be defined manually in the structured type itself and reused either by
another structured type or an entity.
Example
namespace examples;
@Schema: 'MYSCHEMA'
context StructuredTypes {
type MyOtherInt : type of [Link]; // => Integer
type MyOtherStruct : type of [Link]; // => MyStruct
@GenerateTableType: false
type EmptyStruct { };
type MyStruct
{
aNumber : Integer;
aText : String(80);
anotherText : MyString80; // defined in a separate type
};
entity E {
a : Integer;
s : EmptyStruct;
};
type MyString80 : String(80);
type MyS : MyStruct;
type MyNestedStruct
{
name : MyString80;
nested : MyS;
};
type MyDeepNestedStruct
{
text : LargeString;
nested : MyNestedStruct;
type
In a structured user-defined type, you can define original types (aNumber in the following example) or
reference existing types defined elsewhere in the same type definition or another, separate type definition, for
example, MyString80 in the following code snippet. If you define multiple types in a single CDS document,
each structure definition must be separated by a semi-colon (;).
type MyStruct
{
aNumber : Integer;
aText : String(80);
anotherText : MyString80; // defined in a separate type
};
You can define structured types that do not contain any elements, for example, using the keywords type
EmptyStruct { };. In the example, below the generated table for entity “E” contains only one column: “a”.
Tip
It is not possible to generate an SAP HANA table type for an empty structured type. This means you must
disable the generation of the table type in the Repository, for example, with the @GenerateTableType
annotation.
@GenerateTableType : false
type EmptyStruct { };
entity E {
a : Integer;
s : EmptyStruct;
};
type of
You can define a type based on an existing type that is already defined in another user-defined structured type,
for example, by using the type of keyword, as illustrated in the following example:
Context StructuredTypes
{
type MyOtherInt : type of [Link]; // => Integer
type MyOtherStruct : type of [Link]; // => MyStruct
};
Related Information
In the Data Definition Language (DDL), primitive (or core) data types are the basic building blocks that you use
to define entities or structure types with DDL.
When you are specifying a design-time table (entity) or a view definition using the CDS syntax, you use data
types such as String, Binary, or Integer to specify the type of content in the entity columns. CDS supports the
use of the following primitive data types:
The following table lists all currently supported simple DDL primitive data types. Additional information
provided in this table includes the SQL syntax required as well as the equivalent SQL and EDM names for the
listed types.
String (n) Variable-length Unicode string with a 'text with “quote”' NVARCHAR String
specified maximum length of
n=1-1333 characters (5000 for SAP
HANA specific objects). Default =
maximum length. String length (n) is
mandatory.
Binary(n) Variable length byte string with user- x'01Cafe', X'01Cafe' VARBINARY Binary
defined length limit of up to 4000
bytes. Binary length (n) is mandatory.
Integer64 Signed 64-bit integer with a value 13, -1234567 BIGINT Int64
range of -2^63 to 2^63-1. De
fault=NULL.
Decimal( p, s ) Decimal number with fixed precision 12.345, -9.876 DECIMAL( p, s ) Decimal
(p) in range of 1 to 34 and fixed scale
(s) in range of 0 to p. Values for preci
sion and scale are mandatory.
BinaryFloat Binary floating-point number (IEEE 1.2, -3.4, 5.6e+7 DOUBLE Double
754), 8 bytes (roughly 16 decimal dig
its precision); range is roughly
±2.2207e-308 through ±1.7977e+308
LocalDate Local date with values ranging from date'1234-12-31' DATE DateTimeOffset
0001-01-01 through 9999-12-31
Combines date
and time; with
time zone must
be converted to
offset
LocalTime Time values (with seconds precision) time'[Link]', time'12:15' TIME Time
and values ranging from [Link]
For duration/
through [Link]
period of time
(==xsd:dura
tion). Use Date
TimeOffset if
there is a date,
too.
UTCDateTime UTC date and time (with seconds pre timestamp'2011-12-31 SECONDDATE DateTimeOffset
cision) and values ranging from [Link]'
Values ending
0001-01-01 [Link] through
9999-12-31 [Link] with “Z” for
UTC. Values be
fore
1753-01-01T00:
00:00 are not
supported;
transmitted as
NULL.
UTCTimestamp UTC date and time (with a precision of timestamp'2011-12-31 TIMESTAMP DateTimeOffset
0.1 microseconds) and values ranging [Link].7654321'
With Precision =
from 0001-01-01 [Link] through
9999-12-31 [Link].9999999, and a “7”
special initial value
Boolean Represents the concept of binary-val true, false, unknown (null) BOOLEAN Boolean
ued logic
The following table lists all the native SAP HANA primitive data types that CDS supports. The information
provided in this table also includes the SQL syntax required (where appropriate) as well as the equivalent SQL
and EDM names for the listed types.
* In CDS, the name of SAP HANA data types are prefixed with the word “hana”, for example,
[Link], or [Link], or [Link].
The following example shows the native SAP HANA data types that CDS supports; the code example also
illustrates the mandatory syntax.
Note
Support for the geo-spatial types ST_POINT and ST_GEOMETRY is limited: these types can only be used for
the definition of elements in types and entities. It is not possible to define a CDS view that selects an
element based on a geo-spatial type from a CDS entity.
@nokey
entity SomeTypes {
a : [Link](10);
b : [Link];
c : [Link];
d : [Link];
e : [Link];
h : [Link](10);
i : [Link];
Related Information
Associations define relationships between entities. You create associations in a CDS entity definition, which is a
design-time file in the SAP HANA repository.
Prerequisites
Context
SAP HANA Extended Application Services (SAP HANA XS) enables you to use the CDS syntax to create
associations between entities. The associations are defined as part of the entity definition, which are design-
time files in the repository. Repository files are transportable. Activating the CDS entity creates the
corresponding catalog objects in the specified schema. To create an association between CDS entities,
perform the following steps:
Procedure
a. Right-click the folder where you want to save the entity-definition file and choose New Other...
Database Development DDL Source File in the context-sensitive popup menu.
b. Enter the name of the CDS document in the File Name box, for example, MyModel1.
Tip
File extensions are important. If you are using SAP HANA studio to create artifacts in the SAP
HANA Repository, the file-creation wizard adds the required file extension automatically (for
example, [Link]) and, if appropriate, enables direct editing of the new file in the
corresponding editor.
c. Choose Finish to save the changes and commit the new CDS file in the repository.
5. Define the underlying CDS entities and structured types.
If the new CDS file is not automatically displayed by the file-creation wizard, in the Project Explorer view
double-click the CDS file you created in the previous step, for example, [Link], and add the
code for the entity definitions and structured types to the file:
Note
The following code example is provided for illustration purposes only. If the schema you specify does
not exist, you cannot activate the new CDS entity.
context MyEntity1 {
type StreetAddress {
name : String(80);
number : Integer;
};
type CountryAddress {
name : String(80);
code : String(3);
};
entity Address {
key id : Integer;
street : StreetAddress;
zipCode : Integer;
city : String(80);
country : CountryAddress;
type : String(10); // home, office
};
};
In the same entity-definition file you edited in the previous step, for example, [Link], add the
code for the one-to-one association between the entity Person and the entity Address:
This example does not specify cardinality or foreign keys, so the cardinality is set to the default 0..1, and
the target entity's primary key (the element id) is used as foreign key.
entity Person
{
key id : Integer;
address1 : Association to Address;
addressId : Integer;
};
In the same entity-definition file you edited in the previous step, for example, [Link], add the
code for the one-to-many association between the entity Address and the entity Person. The code should
look something like the following example:
entity Address {
key id : Integer;
street : StreetAddress;
zipCode : Integer;
city : String(80);
country : CountryAddress;
type : String(10); // home, office
inhabitants : Association[*] to Person on [Link] = id;
};
Note
Saving a file in a shared project automatically commits the saved version of the file to the repository, To
explicitly commit a file to the repository, right-click the file (or the project containing the file) and
choose Team Commit from the context-sensitive popup menu.
Note
If you cannot activate the new CDS artifact, check that the specified schema already exists and
that there are no illegal characters in the name space, for example, the hyphen (-).
Related Information
Associations are specified by adding an element to a source entity with an association type that points to a
target entity, complemented by optional information defining cardinality and which keys to use.
Note
SAP HANA Extended Application Services (SAP HANA XS) enables you to use associations in CDS entities or
CDS views. The syntax for simple associations in a CDS document is illustrated in the following example:
namespace samples;
@Schema: 'MYSCHEMA' // XS classic *only*
context SimpleAssociations {
type StreetAddress {
name : String(80);
number : Integer;
};
type CountryAddress {
name : String(80);
code : String(3);
};
entity Address {
key id : Integer;
street : StreetAddress;
zipCode : Integer;
city : String(80);
country : CountryAddress;
type : String(10); // home, office
};
entity Person
{
key id : Integer;
// address1,2,3 are to-one associations
address1 : Association to Address;
address2 : Association to Address { id };
address3 : Association[1] to Address { zipCode, street, country };
// address4,5,6 are to-many associations
address4 : Association[0..*] to Address { zipCode };
address5 : Association[*] to Address { [Link] };
address6 : Association[*] to Address { [Link] AS streetName,
[Link] AS countryName };
};
};
Cardinality in Associations
When using an association to define a relationship between entities in a CDS document, you use the
cardinality to specify the type of relation, for example, one-to-one (to-one) or one-to-many (to-n); the
relationship is with respect to both the source and the target of the association.
The target cardinality is stated in the form of [ min .. max ], where max=* denotes infinity. If no cardinality
is specified, the default cardinality setting [ 0..1 ] is assumed. It is possible to specify the maximum
Tip
The information concerning the maximum cardinality is only used as a hint for optimizing the execution of
the resulting JOIN.
namespace samples;
@Schema: 'MYSCHEMA' // XS classic *only*
context AssociationCardinality {
entity Associations {
// To-one associations
assoc1 : Association[0..1] to target; // has no or one target instance
assoc2 : Association to target; // as assoc1, uses the default
[0..1]
assoc3 : Association[1] to target; // as assoc1; the default for
min is 0
assoc4 : Association[1..1] to target; // association has one target
instance
// To-many associations
assoc5 : Association[0..*] to target{id1};
assoc6 : Association[] to target{id1}; // as assoc4, [] is short
for [0..*]
assoc7 : Association[2..7] to target{id1}; // any numbers are
possible; user provides
assoc8 : Association[1, 0..*] to target{id1}; // additional info. about
source cardinality
};
// Required to make the example above work
entity target {
key id1 : Integer;
key id2 : Integer;
};
};
You use the to keyword in a CDS view definition to specify the target entity in an association, for example, the
name of an entity defined in a CDS document. A qualified entity name is expected that refers to an existing
entity. A target entity specification is mandatory; a default value is not assumed if no target entity is specified
in an association relationship.
The entity Address specified as the target entity of an association could be expressed in any of the ways
illustrated the following examples:
When following an association (for example, in a view), it is now possible to apply a filter condition; the filter is
merged into the ON-condition of the resulting JOIN. The following example shows how to get a list of customers
and then filter the list according to the sales orders that are currently “open” for each customer. In the
example, the infix filter is inserted after the association orders to get only those orders that satisfy the
condition [status='open'].
Sample Code
The association orders is defined in the entity definition illustrated in the following code example:
Sample Code
entity Customer {
key id : Integer;
orders : Association[*] to SalesOrder on orders.cust_id = id;
name : String(80);
};
entity SalesOrder {
key id : Integer;
cust_id : Integer;
customer: Association[1] to Customer on [Link] = cust_id;
items : Association[*] to Item on items.order_id = id;
status: String(20);
date : LocalDate;
};
entity Item {
key id : Integer;
order_id : Integer;
salesOrder : Association[1] to SalesOrder on [Link] = order_id;
descr : String(100);
price : Decimal(8,2);
};
Tip
For more information about filter conditions and prefixes in CDS views, see CDS Views and CDS View
Syntax Options.
For managed associations, the relationship between source and target entity is defined by specifying a set of
elements of the target entity that are used as a foreign key. If no foreign keys are specified explicitly, the
elements of the target entity’s designated primary key are used. Elements of the target entity that reside inside
substructures can be addressed via the respective path. If the chosen elements do not form a unique key of the
namespace samples;
using samples::[Link];
using samples::[Link];
using samples::[Link];
@Schema: 'MYSCHEMA' // XS classic *only*
context ForeignKeys {
entity Person
{
key id : Integer;
// address1,2,3 are to-one associations
address1 : Association to Address;
address2 : Association to Address { id };
address3 : Association[1] to Address { zipCode, street, country };
// address4,5,6 are to-many associations
address4 : Association[0..*] to Address { zipCode };
address5 : Association[*] to Address { [Link] };
address6 : Association[*] to Address { [Link] AS streetName,
[Link] AS countryName };
};
entity Header {
key id : Integer;
toItems : Association[*] to Item on [Link] = id;
};
entity Item {
key id : Integer;
head : Association[1] to Header { id };
// <...>
};
};
● address1
No foreign keys are specified: the target entity's primary key (the element id) is used as foreign key.
● address2
Explicitly specifies the foreign key (the element id); this definition is similar to address1.
● address3
The foreign key elements to be used for the association are explicitly specified, namely: zipcode and the
structured elements street and country.
● address4
Uses only zipcode as the foreign key. Since zipcode is not a unique key for entity Address, this
association has cardinality “to-many”.
● address5
Uses the subelement name of the structured element street as a foreign key. This is not a unique key and,
as a result, address4 has cardinality “to-many”.
● address6
Uses the subelement name of both the structured elements street and country as foreign key fields.
The names of the foreign key fields must be unique, so an alias is required here. The foreign key is not
unique, so address6 is a “to-many” association.
You can use foreign keys of managed associations in the definition of other associations. In the following
example, the appearance of association head in the ON condition is allowed; the compiler recognizes that the
field [Link] is actually part of the entity Item and, as a result, can be obtained without following the
association head.
entity Header {
key id : Integer;
toItems : Association[*] to Item on [Link] = id;
};
entity Item {
key id : Integer;
head : Association[1] to Header { id };
...
};
Restrictions
CDS name resolution does not distinguish between CDS associations and CDS entities. If you define a
CDS association with a CDS entity that has the same name as the new CDS association, CDS displays an error
message and the activation of the CDS document fails.
Caution
In an CDS document, to define an association with a CDS entity of the same name, you must specify the
context where the target entity is defined, for example, Mycontext.Address3.
The following code shows some examples of associations with a CDS entity that has the same (or a similar)
name. Case sensitivity ("a", "A") is important; in CDS documents, address is not the same as Address. In the
case of Address2, where the association name and the entity name are identical, the result is an error; when
resolving the element names, CDS expects an entity named Address2 but finds a CDS association with the
same name instead. MyContext.Address3 is allowed, since the target entity can be resolved due to the
absolute path to its location in the CDS document.
context MyContext {
entity Address {…}
entity Address1 {…}
entity Address2 {…}
entity Address3 {…}
entity Person
{
key id : Integer;
address : Association to Address; // OK: "address" ≠ "Address”
address1 : Association to Address1; // OK: "address1" ≠ "Address1”
Address2 : Association to Address2; // Error: association name =
entity name
Address3 : Association to MyContext.Address3; //OK: full path to Address3
};
};
The following example shows a more complex association (to-many) between the entity “Header” and the
entity “Item”.
namespace samples;
@Schema: 'MYSCHEMA' // XS classic *only*
context ComplexAssociation {
Entity Header {
key PurchaseOrderId: BusinessKey;
Items: Association [0..*] to Item on
[Link]=PurchaseOrderId;
"History": HistoryT;
NoteId: BusinessKey null;
PartnerId: BusinessKey;
Currency: CurrencyT;
GrossAmount: AmountT;
NetAmount: AmountT;
TaxAmount: AmountT;
LifecycleStatus: StatusT;
ApprovalStatus: StatusT;
ConfirmStatus: StatusT;
OrderingStatus: StatusT;
InvoicingStatus: StatusT;
} technical configuration {
column store;
};
Entity Item {
key PurchaseOrderId: BusinessKey;
key PurchaseOrderItem: BusinessKey;
ToHeader: Association [1] to Header on
[Link]=PurchaseOrderId;
ProductId: BusinessKey;
NoteId: BusinessKey null;
Currency: CurrencyT;
GrossAmount: AmountT;
NetAmount: AmountT;
TaxAmount: AmountT;
Quantity: QuantityT;
QuantityUnit: UnitT;
DeliveryDate: SDate;
} technical configuration {
column store;
};
define view POView as SELECT from Header {
[Link] as poId,
[Link] as poItem,
PartnerId,
[Link]
};
// Missing types from the example above
type BusinessKey: String(50);
type HistoryT: LargeString;
type CurrencyT: String(3);
type AmountT: Decimal(15, 2);
type StatusT: String(1);
type QuantityT: Integer;
type UnitT: String(5);
type SDate: LocalDate;
};
Example:
Managed Associations
Example:
Unmanaged Associations
Overview
Associations are specified by adding an element to a source entity with an association type that points to a
target entity, complemented by optional information defining cardinality and which keys to use.
Note
SAP HANA Extended Application Services (SAP HANA XS) enables you to use associations in the definition of a
CDS entity or a CDS view. When defining an association, bear in mind the following points:
Association Cardinality
When using an association to define a relationship between entities in a CDS view; you use the cardinality to
specify the type of relation, for example:
● one-to-one (to-one)
● one-to-many (to-n)
The relationship is with respect to both the source and the target of the association. The following code
example illustrates the syntax required to define the cardinality of an association in a CDS view:
In the most simple form, only the target cardinality is stated using the syntax [ min .. max ], where max=*
denotes infinity. Note that [] is short for [ 0..* ]. If no cardinality is specified, the default cardinality setting
[ 0..1 ] is assumed. It is possible to specify the maximum cardinality of the source of the association in the
form [ maxs, min .. max], where maxs = * denotes infinity.
namespace samples;
@Schema: 'MYSCHEMA' // XS classic *only*
context AssociationCardinality {
entity Associations {
// To-one associations
assoc1 : Association[0..1] to target;
assoc2 : Association to target;
assoc3 : Association[1] to target;
assoc4 : Association[1..1] to target; // association has one target
instance
// To-many associations
assoc5 : Association[0..*] to target{id1};
assoc6 : Association[] to target{id1}; // as assoc4, [] is short
for [0..*]
assoc7 : Association[2..7] to target{id1}; // any numbers are
possible; user provides
assoc8 : Association[1, 0..*] to target{id1}; // additional info. about
source cardinality
};
// Required to make the example above work
entity target {
key id1 : Integer;
key id2 : Integer;
};
};
assoc2 Like assoc1, this association has no or one target instance and uses the de
fault [0..1]
assoc3 [1] Like assoc1, this association has no or one target instance; the default for
min is 0
assoc5 [0..*] The association has no, one, or multiple target instances
assoc6 [] Like assoc4, [] is short for [0..*] (the association has no, one, or multiple tar
get instances)
assoc8 [1, 0..*] The association has no, one, or multiple target instances and includes addi
tional information about the source cardinality
When an infix filter effectively reduces the cardinality of a “to-N” association to “to-1”, this can be expressed
explicitly in the filter, for example:
assoc[1: <cond> ]
Specifying the cardinality in the filter in this way enables you to use the association in the WHERE clause, where
“to-N” associations are not normally allowed.
Sample Code
namespace samples;
@Schema: 'MYSCHEMA' // XS classic *only*
context CardinalityByInfixFilter {
entity Person {
key id : Integer;
name : String(100);
address : Association[*] to Address on [Link] = id;
};
entity Address {
key id : Integer;
personId : Integer;
type : String(20); // home, business, vacation, ...
street : String(100);
city : String(100);
};
view V as select from Person {
name
} where address[1: type='home'].city = 'Accra';
};
Association Target
You use the to keyword in a CDS view definition to specify the target entity in an association, for example, the
name of an entity defined in a CDS document. A qualified entity name is expected that refers to an existing
The target entity Address specified as the target entity of an association could be expressed as illustrated the
following examples:
Association Keys
In the relational model, associations are mapped to foreign-key relationships. For managed associations, the
relation between source and target entity is defined by specifying a set of elements of the target entity that are
used as a foreign key, as expressed in the forwardLink element of the following code example:
<forwardLink> = { <foreignKeys> }
<foreignKeys> = <targetKeyElement> [ AS <alias> ] [ , <foreignKeys> ]
<targetKeyElement> = <elementName> ( . <elementName> )*
If no foreign keys are specified explicitly, the elements of the target entity’s designated primary key are used.
Elements of the target entity that reside inside substructures can be addressed by means of the respective
path. If the chosen elements do not form a unique key of the target entity, the association has cardinality to-
many. The following examples show how to express foreign keys in an association.
entity Person
{
key id : Integer;
// address1,2,3 are to-one associations
address1 : Association to Address;
address2 : Association to Address { id };
address3 : Association[1] to Address { zipCode, street, country };
// address4,5,6 are to-many associations
address4 : Association[0..*] to Address { zipCode };
address5 : Association[*] to Address { [Link] };
address6 : Association[*] to Address { [Link] AS streetName,
[Link] AS countryName };
};
address1 No foreign keys are specified: the target entity's primary key (the element id) is
used as foreign key.
address2 { id } Explicitly specifies the foreign key (the element id); this definition is identical to
address1.
address3 { zipCode, The foreign key elements to be used for the association are explicitly specified,
street, namely: zipcode and the structured elements street and country.
country }
address4 { zipCode } Uses only zipcode as the foreign key. Since zipcode is not a unique key for
entity Address, this association has cardinality “to-many”.
address5 { [Link] Uses the sub-element name of the structured element street as a foreign key.
} This is not a unique key and, as a result, address4 has cardinality “to-many”.
address6 { [Link] Uses the sub-element name of both the structured elements street and
AS country as foreign key fields. The names of the foreign key fields must be
streetName, unique, so an alias is required here. The foreign key is not unique, so address6
[Link] is a “to-many” association.
AS
countryName }
You can now use foreign keys of managed associations in the definition of other associations. In the following
example, the compiler recognizes that the field [Link] is part of the foreign key of the association
toLocation and, as a result, physically present in the entity Company.
Sample Code
namespace samples;
@Schema: 'MYSCHEMA' // XS classic *only*
context AssociationKeys {
entity Country {
key c_id : String(3);
// <...>
};
entity Region {
key r_id : Integer;
key toCountry : Association[1] to Country { c_id };
// <...>
};
entity Company {
key id : Integer;
toLocation : Association[1] to Region { r_id, toCountry.c_id };
// <...>
};
};
Unmanaged Associations
Unmanaged associations are based on existing elements of the source and target entity; no fields are
generated. In the ON condition, only elements of the source or the target entity can be used; it is not possible to
use other associations. The ON condition may contain any kind of expression - all expressions supported in
views can also be used in the ON condition of an unmanaged association.
Note
The names in the ON condition are resolved in the scope of the source entity; elements of the target entity
are accessed through the association itself .
namespace samples;
@Schema: 'MYSCHEMA' // XS classic *only*
context UnmanagedAssociations {
entity Employee {
key id : Integer;
officeId : Integer;
// <...>
};
entity Room {
key id : Integer;
inhabitants : Association[*] to Employee on [Link] = id;
// <...>
};
entity Thing {
key id : Integer;
parentId : Integer;
parent : Association[1] to Thing on [Link] = parentId;
children : Association[*] to Thing on [Link] = id;
// <...>
};
};
● parent
The unmanaged association parent uses a cardinality of [1] to create a relation between the element
parentId and the target element id. The target element id is accessed through the name of the
association itself.
● children
The unmanaged association children creates a relation between the element id and the target element
parentId. The target element parentId is accessed through the name of the association itself.
entity Thing {
key id : Integer;
parentId : Integer;
parent : Association[1] to Thing on [Link] = parentId;
children : Association[*] to Thing on [Link] = id;
...
};
Constants in Associations
The usage of constants is no longer restricted to annotation assignments and default values for entity
elements. With SPS 11, you can use constants in the “ON”-condition of unmanaged associations, as illustrated
in the following example:
Sample Code
context MyContext {
const MyIntConst : Integer = 7;
const MyStringConst : String(10) = 'bright';
const MyDecConst : Decimal(4,2) = 3.14;
const MyDateTimeConst : UTCDateTime = '2015-09-30 14:33';
entity MyEntity {
key id : Integer;
a : Integer;
b : String(100);
Related Information
A view is a virtual table based on the dynamic results returned in response to an SQL statement. SAP HANA
Extended Application Services (SAP HANA XS) enables you to use CDS syntax to create a database view as a
design-time file in the repository.
Prerequisites
SAP HANA Extended Application Services (SAP HANA XS) enables you to use the CDS syntax to create a
database view as a design-time file in the repository. Repository files are transportable. Activating the CDS view
definition creates the corresponding catalog object in the specified schema. To create a CDS view-definition file
in the repository, perform the following steps:
Note
The following code examples are provided for illustration purposes only.
Procedure
a. Right-click the folder where you want to save the view-definition file and choose New Other...
Database Development DDL Source File in the context-sensitive pop-up menu.
b. Enter the name of the view-definition file in the File Name box, for example, MyModel2.
Tip
File extensions are important. If you are using SAP HANA studio to create artifacts in the SAP
HANA Repository, the file-creation wizard adds the required file extension automatically (for
example, [Link]) and, if appropriate, enables direct editing of the new file in the
corresponding editor.
c. Choose Finish to save the changes and commit the new CDS definition file in the repository.
5. Define the underlying CDS entities and structured types.
If the new entity-definition file is not automatically displayed by the file-creation wizard, in the Project
Explorer view double-click the entity-definition file you created in the previous step, for example,
[Link], and add the code for the entity definitions and structured types to the file.
namespace [Link].myapp1;
@Schema : 'MYSCHEMA'
context MyModel2 {
type StreetAddress {
name : String(80);
number : Integer;
};
type CountryAddress {
name : String(80);
code : String(3);
};
@[Link] : #COLUMN
entity Address {
In the same entity-definition file you edited in the previous step, for example, [Link], add the
code for the view AddressView below the entity Address in the CDS document.
Note
In CDS, a view is an entity without an its own persistence; it is defined as a projection of other entities.
Note
Saving a file in a shared project automatically commits the saved version of the file to the repository;
you do not need to explicitly commit the file again.
Note
If you cannot activate the new CDS artifact, check that the specified schema already exists and
that there are no illegal characters in the name space, for example, the hyphen (-).
9. Ensure access to the schema where the new CDS catalog objects are created.
After activation in the repository, a schema object is only visible in the catalog to the _SYS_REPO user. To
enable other users, for example the schema owner, to view the newly created schema and the objects it
contains, you must grant the user the required SELECT privilege.
Note
If you already have the appropriate SELECT privilege, you do not need to perform this step.
a. In the SAP HANA studio Systems view, right-click the SAP HANA system hosting the repository where
the schema was activated and choose SQL Console in the context-sensitive popup menu.
call
_SYS_REPO.GRANT_SCHEMA_PRIVILEGE_ON_ACTIVATED_CONTENT('select','<SCHEMANAME
>','<username>');
10. Check that the new view has been successfully created.
Views are created in the Views folder in the catalog.
a. In the SAP HANA Development perspective, open the Systems view.
b. Navigate to the catalog location where you created the new view.
Related Information
A view is an entity that is not persistent; it is defined as the projection of other entities. SAP HANA Extended
Application Services (SAP HANA XS) enables you to create a CDS view as a design-time file in the repository.
SAP HANA Extended Application Services (SAP HANA XS) enables you to define a view in a CDS document,
which you store as design-time file in the repository. Repository files can be read by applications that you
develop. In addition, all repository files including your view definition can be transported to other SAP HANA
systems, for example, in a delivery unit.
If your application refers to the design-time version of a view from the repository rather than the runtime
version in the catalog, for example, by using the explicit path to the repository file (with suffix), any changes to
the repository version of the file are visible as soon as they are committed to the repository. There is no need to
wait for the repository to activate a runtime version of the view.
To define a transportable view using the CDS-compliant view specifications, use something like the code
illustrated in the following example:
context Views {
VIEW AddressView AS SELECT FROM Address {
id,
[Link],
[Link]
};
<...>
When a CDS document is activated, the activation process generates a corresponding catalog object for each
of the artifacts defined in the document; the location in the catalog is determined by the type of object
generated. For example, in SAP HANA XS classic the corresponding catalog object for a CDS view definition is
generated in the following location:
Views defined in a CDS document can make use of the following SQL features:
Tip
For more information about the syntax required when using these SQL features in a CDS view, see CDS
View Syntax Options in Related Information.
Type Definition
In a CDS view definition, you can explicitly specify the type of a select item, as illustrated in the following
example:
Sample Code
● a,
Has type “MyInteger”
● a+b as s1,
Has type “Integer” and any information about the user-defined type is lost
● a+b as s2 : MyInteger
Has type “MyInteger”, which is explicitly specified
If necessary, a CAST function is added to the generated view in SAP HANA; this ensures that the select
item's type in the SAP HANA view is the SAP HANA “type” corresponding to the explicitly specified CDS
type.
Related Information
SAP HANA XS includes a dedicated, CDS-compliant syntax, which you must adhere to when using a CDS
document to define a view as a design-time artifact.
Example
Note
The following example is intended for illustration purposes only and might contain syntactical errors. For
further details about the keywords illustrated, click the links provided.
context views {
const x : Integer = 4;
const y : Integer = 5;
const Z : Integer = 6;
VIEW MyView1 AS SELECT FROM Employee
{
a + b AS theSum
};
VIEW MyView2 AS SELECT FROM Employee
{ [Link],
[Link],
[Link],
[Link],
count(id) AS seatsTaken,
count(id)/[Link] as occupancyRate
} WHERE [Link] = 1
GROUP BY [Link],
[Link],
[Link],
[Link],
[Link]
HAVING [Link] = 'office' AND count(id)/[Link] < 0.5;
VIEW MyView3 AS SELECT FROM Employee
{ orgUnit,
In a CDS view definition you can use any of the functions and expressions listed in the following example:
Note
When expressions are used in a view element, an alias must be specified, for example, AS theSum.
Aggregates
● AVG
● COUNT
● MIN
● MAX
● SUM
● STDDEV
● VAR
The following example shows how to use aggregates and expressions to collect information about headcount
and salary per organizational unit for all employees hired from 2011 to now.
Note
Constants in Views
With SPS 11, you can use constants in the views, as illustrated in “MyView” at the end of the following example:
Sample Code
context MyContext {
const MyIntConst : Integer = 7;
const MyStringConst : String(10) = 'bright';
const MyDecConst : Decimal(4,2) = 3.14;
When constants are used in a view definition, their name must be prefixed with the scope operator “:”. Usually
names that appear in a query are resolved as alias or element names. The scope operator instructs the
compiler to resolve the name outside of the query.
Sample Code
context NameResolution {
const a : Integer = 4;
const b : Integer = 5;
const c : Integer = 6;
entity E {
key id : Integer;
a : Integer;
c : Integer;
};
view V as select from E {
a as a1,
b,
:a as a2,
E.a as a3,
:E,
:E.a as a4,
:c
};
}
The following table explains how the constants used in view “V” are resolved.
a as a1, Success “a” is resolved in the space of alias and element names, for example, ele
ment “a” of entity “E”.
b, Error There is no alias and no element with name “b” in entity “E”
:a as a2, Success Scope operator “:” instructs the compiler to search for element “a” outside
of the query (finds the constant “a”).
E.a as a3, Success “E” is resolved in the space of alias and element names, so this matches
element “a” of entity “Entity” .
:E.a as a4, Error Error; no access to “E” (or any of its elements) via “:”
SELECT
In the following example of an association in a SELECT list, a view compiles a list of all employees; the list
includes the employee's name, the capacity of the employee's office, and the color of the carpet in the office.
The association follows the to-one association office from entity Employee to entity Room to collect the
relevant information about the office.
Subqueries
You can define subqueries in a CDS view, as illustrated in the following example:
Restriction
Code Syntax
Note
In a correlated subquery, elements of outer queries must always be addressed by means of a table alias.
The following example shows how the syntax required in the WHERE clause used in a CDS view definition. In this
example, the WHERE clause is used in an association to restrict the result set according to information located
in the association's target. Further filtering of the result set can be defined with the AND modifier.
FROM
The following example shows the syntax required when using the FROM clause in a CDS view definition. This
example shows an association that lists the license plates of all company cars.
If a CDS view references a native SAP HANA table, the table and column names must be specified using their
effective SAP HANA names.
This means that if a table (foo) or its columns (bar and “gloo” were created without using quotation marks
(""), the corresponding uppercase names for the table or columns must be used in the CDS document, as
illustrated in the following example.
The following example shows the syntax required when using the GROUP BY clause in a CDS view definition.
This example shows an association in a view that compiles a list of all offices that are less than 50% occupied.
HAVING
The following example shows the syntax required when using the HAVING clause in a CDS view definition. This
example shows a view with an association that compiles a list of all offices that are less than 50% occupied.
ORDER BY
The ORDER BY operator enables you to list results according to an expression or position, for example salary.
In the same way as with plain SQL, the ASC and DESC operators enable you to sort the list order as follows.
● ASC
LIMIT/OFFSET
You can use the SQL clauses LIMIT and OFFSET in a CDS query. The LIMIT <INTEGER> [OFFSET
<INTEGER>] operator enables you to restrict the number of output records to display to a specified “limit”; the
OFFSET <INTEGER> specifies the number of records to skip before displaying the records according to the
defined LIMIT.
CASE
In the same way as in plain SQL, you can use the case expression in a CDS view definition to introduce IF-
THEN-ELSE conditions without the need to use procedures.
entity MyEntity12 {
key id : Integer;
a : Integer;
color : String(1);
};
In the first example of usage of the CASE operator, CASE color shows a “switched” CASE (one table column
and multiple values). The second example of CASE usage shows a “conditional” CASE with multiple arbitrary
conditions, possibly referring to different table columns.
UNION
Enables multiple select statements to be combined but return only one result set. UNION works in the same
way as the SAP HANA SQL command of the same name; it selects all unique records from all select statements
Note
entity E1 {
key a : Integer;
b : String(20);
c : LocalDate;
};
entity E2 {
key x : String(20);
y : LocalDate;
z : Integer;
};
VIEW MyView5 AS
SELECT FROM E1 { a, b, c}
UNION
SELECT FROM E2 { z, x, y};
JOIN
You can include a JOIN clause in a CDS view definition; the following JOIN types are supported:
● [ INNER ] JOIN
● LEFT [ OUTER ] JOIN
● RIGHT [ OUTER ] JOIN
● FULL [ OUTER ] JOIN
● CROSS JOIN
Sample Code
entity E {
key id : Integer;
a : Integer;
};
entity F {
key id : Integer;
b : Integer;
};
entity G {
key id : Integer;
c : Integer;
};
view V_join as select from E join (F as X full outer join G on [Link] = [Link])
on [Link] = c {
a, b, c
};
You can use the SQL clause TOP in a CDS query, as illustrated in the following example:
Sample Code
Restriction
It is not permitted to use TOP in combination with the LIMIT clause in a CDS query.
SELECT DISTINCT
CDS now supports the SELECT DISTINCT semantic, which enables you to specify that only one copy of each
set of duplicate records selected should be returned. The position of the DISTINCT keyword is important; it
must appear directly in front of the curly brace, as illustrated in the following example:
Sample Code
entity E {
key id : Integer;
a : Integer;
};
entity F {
key id : Integer;
b : Integer;
};
entity G {
key id : Integer;
c : Integer;
};
view V_dist as select from E distinct { a };
With Parameters
You can define parameters for use in a CDS view; this allows you to pass additional values to modify the results
of the query at run time. Parameters must be defined in the view definition before the query block, as
illustrated in the following example:
Restriction
For use in XS advanced only; views with parameters are not supported in XS classic.
context MyContext
{
entity MyEntity1 {
id: Integer;
elt: String(100); };
entity MyEntity2 {
id: Integer;
elt: String(100); };
type MyUserDefinedType: type of [Link];
view MyParamView with parameters PAR1: Integer,
PAR2: MyUserDefinedType,
PAR3: type of [Link]
as select from MyEntity {
id,
elt };
Note
Parameters can be used in a query at any position where an expression is allowed. A parameter is referred to
inside a query by prefixing the parameter name either with the colon Scope operator ':' or the string
“$parameters” .
Tip
If no matching parameter can be found, the scope operator “escapes” from the query and attempts to
resolve the identifier outside the query.
Sample Code
Parameters are passed to views as a comma-separated list in parentheses. Optional filter expressions must
then follow the parameter list.
It is not allowed to use a query as value expression. Nor is it allowed to provide a parameter list in the ON
condition of an association definition to a parameterized view. This is because the association definition
establishes the relationship between the two entities but makes no assumptions about the run-time
conditions. For the same reason, it is not allowed to specify filter conditions in those ON conditions.
The following example shows two entities SourceEntity and TargetEntity and a parameterized view
TargetWindowView, which selects from TargetEntity. An association is established between
SourceEntity and TargetEntity.
Sample Code
entity SourceEntity {
id: Integer;
someElementOfSourceEntity: String(100);
toTargetViaParamView: association to TargetWindowView on
[Link] = id;
};
entity TargetEntity {
targetId: Integer;
someElementOfTargetEntity: String(100);
};
It is now possible to query SourceEntity in a view; it is also possible to follow the association to
TargetWindowView, for example, by providing the required parameters, as illustrated in the following
example:
Sample Code
It is also possible to follow the association in the FROM clause; this provides access only to the elements of the
target artifact:
Sample Code
You can select directly from the view with parameters, adding a free JOIN expression, as illustrated in the
following example:
Sample Code
Tip
To improve readability and comprehension, it is recommended to include only one annotation assignment
per line.
In the following example, the view TargetWindowView selects from the entity TargetEntity; the annotation
@positiveValuesOnly is not checked; and the targetId is required for the ON condition in the entity
SourceEntity.
Sample Code
You can define an association as a view element, for example, by defining an ad-hoc association in the mixin
clause and then adding the association to the SELECT list, as illustrated in the following example:
Restriction
XS classic does not support the use of ad-hoc associations in a view's SELECT list.
Sample Code
entity E {
a : Integer;
b : Integer;
};
entity F {
x : Integer;
y : Integer;
};
view VE as select from E mixin {
f : Association[1] to VF on [Link] = $[Link];
} into {
a as va,
b as vb,
f as vf
};
view VF as select from F {
x as vx,
y as vy
};
In the ON condition of this type of association in a view, it is necessary to use the pseudo-identifier
$projection to specify that the following element name must be resolved in the select list of the view
(“VE”) rather than in the entity (“E”) in the FROM clause
Filter Conditions
It is possible to apply a filter condition when resolving associations between entities; the filter is merged into
the ON-condition of the resulting JOIN. The following example shows how to get a list of customers and then
filter the list according to the sales orders that are currently “open” for each customer. In the example, the filter
is inserted after the association orders; this ensures that the list displayed by the view only contains those
orders that satisfy the condition [status='open'].
Sample Code
Sample Code
Tip
The following example shows how to use the associations orders and items in a view that displays a list of
customers with open sales orders for items with a price greater than 200.
Sample Code
Prefix Notation
The prefix notation can also be used without filters. The following example shows how to get a list of all
customers with details of their sales orders. In this example, all uses of the association orders are combined
so that there is only one JOIN to the table SalesOrder. Similarly, both uses of the association items are
combined, and there is only one JOIN to the table Item.
Sample Code
The example above can be expressed more elegantly by combining the associations orders and items using
the following prefix notation:
Sample Code
Type Definition
In a CDS view definition, you can explicitly specify the type of a select item, as illustrated in the following
example:
Restriction
For use in XS advanced only; assigning an explicit CDS type to an item in a SELECT list is not supported in
XS classic.
Sample Code
● a,
Has type “MyInteger”
● a+b as s1,
Has type “Integer” and any information about the user-defined type is lost
● a+b as s2 : MyInteger
Has type “MyInteger”, which is explicitly specified
Note
If necessary, a CAST function is added to the generated view in SAP HANA; this ensures that the select
item's type in the SAP HANA view is the SAP HANA “type” corresponding to the explicitly specified CDS
type.
Spatial Functions
The following view (SpatialView1) displays a list of all persons selected from the entity Person and uses the
spatial function ST_Distance (*) to include information such as the distance between each person's home
Sample Code
Caution
(*) For information about the capabilities available for your license and installation scenario, refer to the
Feature Scope Description for SAP HANA.
Related Information
CDS supports the use of Geographic Information Systems (GIS) functions and element types in CDS-
compliant entities and views.
Spatial data is data that describes the position, shape, and orientation of objects in a defined space; the data is
represented as two-dimensional geometries in the form of points, line strings, and polygons. The following
examples shows how to use the spatial function ST_Distance in a CDS view. The underlying spatial data used
in the view is defined in a CDS entity using the type ST_POINT.
The following example, the CDS entity Address is used to store geo-spatial coordinates in element loc of type
ST_POINT:
Sample Code
namespace samples;
@Schema: 'MYSCHEMA'
context Spatial {
entity Person {
key id : Integer;
name : String(100);
homeAddress : Association[1] to Address;
officeAddress : Association[1] to Address;
The view GeoView1 is used to display a list of all persons using the spatial function ST_Distance to include
information such as the distance between each person's home and business address
(distanceHomeToWork), and the distance between their home address and the building SAP03
(distFromSAP03). The value for both distances is measured in kilometers.
Caution
(*) For information about the capabilities available for your license and installation scenario, refer to the
Feature Scope Description for SAP HANA.
Related Information
Changes to the definition of a CDS artifact result in changes to the corresponding catalog object. The resultant
changes to the catalog object are made according to strict rules.
Reactivating a CDS document which contains changes to the original artifacts results in changes to the
corresponding objects in the catalog. Before making change to the design-time definition of a CDS artifact, it is
very important to understand what the consequences of the planned changes will be in the generated catalog
objects.
If a CDS design-time artifact (for example, a table or a view) defined in an old version of a CDS document is no
longer present in the new version, the corresponding runtime object is dropped from the catalog.
Note
Renaming a CDS artifact results in the deletion of the artifact with the old name (with all the corresponding
consequences) and the creation of a new CDS artifact with the new name.
If a CDS design-time artifact is present in both the old and the new version of a CDS document, a check is
performed to establish what, if any, changes have occurred. This applies to changes made either directly to a
CDS artifact or indirectly, for example, as a result of a change to a dependent artifact. If changes have been
made to the CDS document, changes are implemented in the corresponding catalog objects according to the
following rules:
● Views
Views in the SAP HANA catalog are dropped and recreated according to the new design-time specification
for the artifact in the CDS document.
● Element types
Changing the type of an element according to the implicit conversion rules described in the SAP HANA
SQL documentation (SAP HANA SQL Data Type Conversion). Note: For some type conversions the
activation will succeed only if the data in the corresponding DB table is valid for the target type (for
example the conversion of String to Integer will succeed only if the corresponding DB table column
contains only numbers that match the Integer type)
● Element modifier: Null/NOT NULL
Adding, removing or changing element modifiers “Null” and “not null” to make an element nullable ot
not nullable respectively can lead to problems when activating the resulting artifact; the activation will
succeed only if the data in the database table corresponding to the CDS entity matches the new modifier.
For example, you cannot make an element not nullable, if in the corresponding column in the database
table some null values exist for which there is no default value defined.
● Element modifier: Default Value
If the default value modifier is removed, this has no effect on the existing data in the corresponding
database table, and no default value will be used for any subsequently inserted record. If the default value
is modified or newly added, the change will be applicable to all subsequent inserts in the corresponding
database table. In addition, if the element is not nullable (irrespective of whether it was defined previously
as such or within the same activation), the existing null values in the corresponding table will be replaced
with the new default value.
● Element modifier: Primary Key
Note
Adding the “key” modifier to an element will also make the column in the corresponding table not
nullable. If column in the corresponding database table contains null values and there is no default
value defined for the element, the activation of the modified CDS document will fail.
For changes to individual elements of a CDS entity, for example, column definitions, the same logic applies as
for complete artifacts in a CDS document.
● Since the elements of a CDS entity are identified by their name, changing the order of the elements in the
entity definition will have no effect; the order of the columns in the generated catalog table object remains
unchanged.
● Renaming an element in a CDS entity definition is not recognized; the rename operation results in the
deletion of the renamed element and the creation of a new one.
● If a new element is added to a CDS entity definition, the order of the columns in the table generated in the
catalog after the change cannot be guaranteed.
Note
If an existing CDS entity definition is changed, the order of the columns in the generated database tables
may be different from the order of the corresponding elements in the CDS entity definition.
In the following example of a simple CDS document, the context OuterCtx contains a CDS entity Entity1 and
the nested context InnerCtx, which contains the CDS entity definition Entity2.
namespace pack;
@Schema: 'MYSCHEMA'
context OuterCtx
{
entity Entity1
{
key a : Integer;
b : String(20);
};
context InnerCtx
{
entity Entity2
{
key x : Integer;
y : String(10);
z : LocalDate;
};
};
};
To understand the effect of the changes made to this simple CDS document in the following example, it is
necessary to see the changes not only from the perspective of the developer who makes the changes but also
the compiler which needs to interpret them.
namespace pack;
@Schema: 'MYSCHEMA'
context OuterCtx
{
context InnerCtx
{
entity Entity1
{
key a : Integer;
b : String(20);
};
entity Entity2
{
key x : Integer;
q : String(10);
z : LocalDate;
};
};
};
Similarly, renaming the element y: String; to q: String; in Entity2 results in the deletion of column y
and the creation of a new column q in the generated catalog object. As a consequence, the content of column y
is lost.
CDS does not support modifications to catalog objects generated from CDS documents. You must never
modify an SAP HANA catalog object (in particular a table) that has been generated from a CDS document. The
next time you activate the CDS document that contains the original CDS object definition and the
corresponding catalog objects are generated, all modifications made to the catalog object are lost or activation
might even fail due to inconsistencies.
If the definition of a CDS entity has already been transported to another system, do not enforce activation of
any illegal changes to this entity, for example, by means of an intermediate deletion.
Restrictions apply to changes that can be made to a CDS entity if the entity has been activated and a
corresponding catalog object exists. If changes to a CDS entity on the source system produce an error during
activation of the CDS document, for example, because you changed an element type in a CDS entity from
Binary to LocalDate, you could theoretically delete the original CDS entity and then create a new CDS entity
with the same name as the original entity but with the changed data type. However, if this change is
transported to another system, where the old version of the entity already exists, the import will fail, because
the information that the entity has been deleted and recreated is not available either on the target system or in
the delivery unit.
You can use the Data Definition Language (DDL) to define a table, which is also referred to as an “entity” in SAP
HANA Core Data Services (CDS). The finished artifact is saved in the repository with the extension
(suffix) .hdbdd, for example, [Link].
Prerequisites
This task describes how to create a file containing a CDS entity (table definition) using DDL. Before you start
this task, note the following prerequisites:
Context
The SAP HANA studio provides a dedicated DDL editor to help you define data-related artifacts, for example,
entities, or views. To create a simple database table with the name "MyTable", perform the following steps:
Tip
File extensions are important. If you are using SAP HANA Studio to create artifacts in the SAP HANA
Repository, the file-creation wizard adds the required file extension automatically and, if appropriate,
enables direct editing of the new file in the corresponding editor.
Procedure
a. Right-click the folder where you want to create the CDS document and choose New DDL Source
File in the context-sensitive popup menu.
Note
This menu option is only available from shared projects; projects that are linked to the SAP HANA
repository.
b. Enter the name of the entity in the File Name box, for example, MyFirstCDSSourceFile.
Note
The file extension .hdbdd is added automatically to the new DDL file name. The repository uses
the file extension to make assumptions about the contents of repository artifacts, for example,
that .hdbdd files contain DDL statements.
Note
If you are using a CDS document to define a single CDS-compliant entity, the name of the CDS
document must match the name of the entity defined in the CDS document, for example, with the
Note
The CDS DDL editor automatically inserts the mandatory keywords namespace and context into any
new DDL source file that you create using the New DDL Source File dialog. The following values are
assumed:
○ namespace = <Current Project Name>
○ context = <New DDL File Name>
The name space declared in a CDS document must match the repository package in which the object
the document defines is located.
In this example, the CDS document [Link] that defines the CDS entity “BOOK” must reside in the
package mycompany.myapp1.
namespace mycompany.myapp1;
@Schema : 'MYSCHEMA'
@[Link]: #COLUMN
@[Link]: [ { name : 'MYINDEX1', unique : true, order : #DESC,
elementNames : ['ISBN'] } ]
entity BOOK {
key Author : String(100);
key BookTitle : String(100);
ISBN : Integer not null;
Publisher : String(100);
};
Note
Saving a file in a shared project automatically commits the saved version of the file to the repository, To
explicitly commit a file to the repository, right-click the file (or the project containing the file) and
choose Team Commit from the context-sensitive popup menu.
"MYSCHEMA"."mycompany.myapp1::BOOK"
The following public synonym is also created, which can be referenced using the standard SQL query
notation:
"mycompany.myapp1::BOOK"
Related Information
The table-import function is a data-provisioning tool that enables you to import data from comma-separated
values (CSV) files into SAP HANA tables.
Prerequisites
Before you start this task, make sure that the following prerequisites are met:
Note
The names used in the following task are for illustration purposes only; where necessary, replace the names
of schema, tables, files, and so on shown in the following examples with your own names.
Context
In this tutorial, you import data from a CSV file into a table generated from a design-time definition that uses
the .hdbdd syntax, which complies with the Core Data Services (CDS) specifications.
Tip
File extensions are important. If you are using SAP HANA Studio to create artifacts in the SAP HANA
Repository, the file-creation wizard adds the required file extension automatically and, if appropriate,
enables direct editing of the new file in the corresponding editor.
Procedure
Naming conventions exist for package names, for example, a package name must not start with
either a dot (.) or a hyphen (-) and cannot contain two or more consecutive dots (..). In addition,
the name must not exceed 190 characters.
For the purposes of this tutorial, the following files must all be created in the same package, for example, a
package called TiTest. However, the table-import feature also allows you to use files distributed in
different packages
Tip
File extensions are important. If you are using SAP HANA Studio to create artifacts in the SAP HANA
Repository, the file-creation wizard adds the required file extension automatically and, if appropriate,
enables direct editing of the new file in the corresponding editor.
Note
In this tutorial, the target table for the table-import operation is [Link], a design-time
table defined using the CDS-compliant .hdbdd syntax.
Note
In the CDS-compliant .hdbdd syntax, the namespace keyword denotes the path to the package
containing the table-definition file.
namespace [Link];
@Schema : 'AMT'
5. Open the CSV file containing the data to import, for example, [Link] in a text editor and enter
the values shown in the following example.
0,Annan,Kwesi,Accra
1,Essuman,Wiredu,Tema
2,Tetteh,Kwame,Kumasi
3,Nterful,Akye,Tarkwa
4,Acheampong,Kojo,Tamale
5,Assamoah,Adjoa,Takoradi
6,Mensah,Afua,Cape Coast
Note
You can import data from multiple .csv files in a single, table-import operation. However, each .csv
file must be specified in a separate code block ({table= ...}) in the table-import configuration file.
6. Create or open the table-import configuration file ([Link]) and enter the following lines of
text.
import = [
{
table = "[Link]::inhabitants";
schema = "AMT";
file = "[Link]:[Link]";
header = false;
}
];
You can import data from comma-separated values (CSV) into the SAP HANA tables using the SAP HANA
Extended Application Services (SAP HANA XS) table-import feature.
In SAP HANA XS, you create a table-import scenario by setting up an table-import configuration file and one or
more comma-separated value (CSV) files containing the content you want to import into the specified SAP
HANA table. The import-configuration file links the import operation to one or more target tables. The table
definition (for example, in the form of a .hdbdd or .hdbtable file) can either be created separately or be
included in the table-import scenario itself.
To use the SAP HANA XS table-import feature to import data into an SAP HANA table, you need to understand
the following table-import concepts:
● Table-import configuration
You define the table-import model in a configuration file that specifies the data fields to import and the
target tables for each data field.
Note
The table-import file must have the .hdbti extension, for example, [Link].
The following constraints apply to the CSV file used as a source for the table-import feature in SAP HANA XS:
● The number of table columns must match the number of CSV columns.
● There must not be any incompatibilities between the data types of the table columns and the data types of
the CSV columns.
● Overlapping data in data files is not supported.
● The target table of the import must not be modified (or appended to) outside of the data-import operation.
If the table is used for storage of application data, this data may be lost during any operation to re-import
or update the data.
Related Information
You can define the elements of a table-import operation in a design-time file; the configuration includes
information about source data and the target table in SAP HANA.
SAP HANA Extended Application Services (SAP HANA XS) enables you to perform data-provisioning
operations that you define in a design-time configuration file. The configuration file is transportable, which
means you can transfer the data-provisioning between SAP HANA systems quickly and easily.
The table-import configuration enables you to specify how data from a comma-separated-value (.csv) file is
imported into a target table in SAP HANA. The configuration specifies the source file containing the data values
to import and the target table in SAP HANA into which the data must be inserted. As further options, you can
specify which field delimiter to use when interpreting data in the source .csv file and if keys must be used to
determine which columns in the target table to insert the imported data into.
Note
If you use multiple table import configurations to import data into a single target table, the keys keyword is
mandatory. This is to avoid problems relating to the overwriting or accidental deletion of existing data.
The following example of a table-import configuration shows how to define a simple import operation which
inserts data from the source files [Link] and [Link] into the table myTable in the schema
mySchema.
import = [
{
table = "myTable";
schema = "mySchema";
file = "[Link]:[Link]";
header = false;
delimField = ";";
keys = [ "GROUP_TYPE" : "BW_CUBE"];
},
{
table = "[Link]::myTable";
file = "[Link]:[Link]";
header = false;
delimField = ";";
keys = [ "GROUP_TYPE" : "BW_CUBE"];
}
];
In the table import configuration, you can specify the target table using either of the following methods:
Note
Both the schema and the target table specified in the table-import operation must already exist. If either
the specified table or the schema does not exist, SAP HANA XS displays an error message during the
You can also use one table-import configuration file to import data from multiple .csv source files. However,
you must specify each import operation in a new code block introduced by the [hdb | cds]table keyword, as
illustrated in the example above.
By default, the table-import operation assumes that data values in the .csv source file are separated by a
comma (,). However, the table-import operation can also interpret files containing data values separated by a
semi-colon (;).
,,,BW_CUBE,,40000000,2,40000000,all
;;;BW_CUBE;;40000000;3;40000000;all
Note
If the activated .hdbti configuration used to import data is subsequently deleted, only the data that was
imported by the deleted .hdbti configuration is dropped from the target table. All other data including any
data imported by other .hdbti configurations remains in the table. If the target CDS entity has no key
(annotated with @nokey) all data that is not part of the CSV file is dropped from the table during each
table-import activation.
You can use the optional keyword keys to specify the key range taken from the source .csv file for import into
the target table. If keys are specified for an import in a table import configuration, multiple imports into same
target table are checked for potential data collisions.
Note
The configuration-file syntax does not support wildcards in the key definition; the full value of a selectable
column value has to be specified.
Security Considerations
In SAP HANA XS, design-time artifacts such as tables (.hdbtable or .hdbdd) and table-import
configurations (.hdbti) are not normally exposed to clients via HTTP. However, design-time artifacts
containing comma-separated values (.csv) could be considered as potential artifacts to expose to users
through HTTP. For this reason, it is essential to protect these exposed .csv artifacts by setting the appropriate
application privileges; the application privileges prevents data leakage, for example, by denying access to data
by users, who are not normally allowed to see all the records in such tables.
Tip
Place all the .csv files used to import content to into tables together in a single package and set the
appropriate (restrictive) application-access permissions for that package, for example, with a
dedicated .xsaccess file.
The design-time configuration file used to define a table-import operation requires the use of a specific syntax.
The syntax comprises a series of keyword=value pairs.
If you use the table-import configuration syntax to define the details of the table-import operation, you can use
the keywords illustrated in the following code example. The resulting design-time file must have the .hdbti file
extension, for example, [Link].
import = [
{
table = "myTable";
schema = "mySchema";
file = "[Link]:[Link]";
header = false;
useHeaderNames = false;
delimField = ";";
delimEnclosing=“\““;
distinguishEmptyFromNull = true;
keys = [ "GROUP_TYPE" : "BW_CUBE", "GROUP_TYPE" : "BW_DSO", "GROUP_TYPE" :
"BW_PSA"];
}
];
table
In the table-import configuration, the table, cdstable, and hdbtable keywords enable you to specify the
name of the target table into which the table-import operation must insert data. The target table you specify in
the table-import configuration can be a runtime table in the catalog or a design-time table definition, for
example, a table defined using either the .hdbtable or the .hdbdd (Core Data Services) syntax.
Note
The target table specified in the table-import configuration must already exist. If the specified table does
not exist, SAP HANA XS displays an error message during the activation of the configuration file, for
example: Table import target table cannot be found.
Use the table keyword in the table-import configuration to specify the name of the target table using the
qualified name for a catalog table.
table = "target_table";
schema = "mySchema";
You must also specify the name of the schema in which the target catalog table resides, for example, using
the schema keyword.
The hdbtable keyword in the table-import configuration enables you to specify the name of a target table using
the public synonym for a design-time table defined with the .hdbtable syntax.
hdbtable = "[Link]::target_table";
The cdstable keyword in the table-import configuration enables you to specify the name of a target table using
the public synonym for a design-time table defined with the CDS-compliant .hdbdd syntax.
cdstable = "[Link]::target_table";
Caution
There is no explicit check if the addressed table is created using the .hdbtable or CDS-compliant .hdbdd
syntax.
If the table specified with the cdstable or hdbtable keyword is not defined with the corresponding syntax,
SAP HANA displays an error when you try to activate the artifact, for example,Invalid combination of
table declarations found, you may only use [cdstable | hdbtable | table] .
schema
The following code example shows the syntax required to specify a schema in a table-import configuration.
schema = "TI2_TESTS";
Note
The schema specified in the table-import configuration file must already exist.
If the schema specified in a table-import configuration file does not exist, SAP HANA XS displays an error
message during the activation of the configuration file, for example:
The schema is only required if you use a table's schema-qualified catalog name to reference the target table for
an import operation, for example, table = "myTable"; schema = "mySchema";. The schema is not
required if you use a public synonym to reference a table in a table-import configuration, for example,
hdbtable = "[Link]::target_table";.
Use the file keyword in the table-import configuration to specify the source file containing the data that the
table-import operation imports into the target table. The source file must be a .csv file with the data values
separated either by a comma (,) or a semi-colon (;). The file definition must also include the full package path
in the SAP HANA repository.
file = "[Link]:[Link]";
header
Use the header keyword in the table-import configuration to indicate if the data contained in the
specified .csv file includes a header line. The header keyword is optional, and the possible values are true or
false.
header = false;
useHeaderNames
Use the useHeaderNames keyword in the table-import configuration to indicate if the data contained in the
first line of the specified .csv file must be interpreted. The useHeaderNames keyword is optional; it is used in
combination with theheader keyword. The useHeaderNames keyword is boolean: possible values are true or
false.
Note
useHeaderNames = false;
The table-import process considers the order of the columns; if the column order specified in the .csv, file
does not match the order used for the columns in the target table, an error occurs on activation.
delimField
Use the delimField keyword in the table-import configuration to specify which character is used to separate
the values in the data to be imported. Currently, the table-import operation supports either the comma (,) or
the semi-colon (;). The following example shows how to specify that values in the .csv source file are
separated by a semi-colon (;).
delimField = ";";
By default, the table-import operation assumes that data values in the .csv source file are separated by a
comma (,). If no delimiter field is specified in the .hdbti table-import configuration file, the default setting
is assumed.
delimEnclosing
Use the delimEnclosing keyword in the table-import configuration to specify a single character that
indicates both the start and end of a set of characters to be interpreted as a single value in the .csv file, for
example “This is all one, single value”. This feature enables you to include in data values in a .CSV file even the
character defined as the field delimiter (in delimField), for example, a comma (,) or a semi-colon (;).
Tip
If the value used to separate the data fields in your .csv file (for example, the comma (,)) is also used
inside the data values themselves ("This, is, a, value"), you must declare and use a delimiter
enclosing character and use it to enclose all data values to be imported.
The following example shows how to use the delimEnclosing keyword to specify the quote (") as the
delimiting character that indicates both the start and the end of a value in the .csv file. Everything enclosed
between the delimEnclosing characters (in this example, “”) is interpreted by the import process as one,
single value.
delimEnclosing=“\““;
Note
Since the hdbti syntax requires us to use the quotes (“”) to specify the delimiting character, and the
delimiting character in this example is, itself, also a quote ("), we need to use the backslash character (\) to
escape the second quote (").
In the following example of values in a .csv file, we assume that delimEnclosing“\““, and
delimField=",". This means that imported values in the .csv file are enclosed in the quote character
("value”) and multiple values are separated by the comma ("value1”,"value 2”). Any commas inside the
quotes are interpreted as a comma and not as a field delimiter.
You can use other characters as the enclosing delimiter, too, for example, the hash (#). In the following
example, we assume that delimEnclosing="#" and delimField=";". Any semi-colons included inside the
hash characters are interpreted as a semi-colon and not as a field delimiter.
Use the distinguishEmptyFromNull keyword in combination with delimEnclosing to ensure that the
table-import process correctly interprets any empty value in the .CSV file, which is enclosed with the value
defined in the delimEnclosing keyword, for example, as an empty space. This ensures that an empty space
is imported “as is” into the target table. If the empty space in incorrectly interpreted, it is imported as NULL.
distinguishEmptyFromNull = true;
Note
"Value1",,"",Value2
The table-import process would add the values shown in the example .csv above into the target table as
follows:
keys
Use the keys keyword in the table-import configuration to specify the key range to be considered when
importing the data from the .csv source file into the target table.
In the example above, all the lines in the .csv source file where the GROUP_TYPE column value matches one of
the given values (BW_CUBE, BW_DSO, or BW_PSA) are imported into the target table specified in the table-import
configuration.
;;;BW_CUBE;;40000000;3;40000000;slave
;;;BW_DSO;;40000000;3;40000000;slave
;;;BW_PSA;;2000000000;1;2000000000;slave
All the lines in the .csv source file where the GROUP_TYPE column is empty are imported into the target table
specified in the table-import configuration.
;;;;;40000000;2;40000000;all
During the course of the activation of the table-import configuration and the table-import operation itself, SAP
HANA checks for errors and displays the following information in a brief message.
40201 If you import into a catalog table, You specified a target table with the table key
please provide schema word but did not specify a schema with the
schema keyword.
40202 Schema could not be resolved The schema specified with the schema key
word does not exist or could not be found
(wrong name).
40203 Schema resolution error The schema specified with the schema key
word does not exist or could not be found
(wrong name).
40204 Table import target table cannot be The table specified with the table keyword does
found not exist or could not be found (wrong name or
wrong schema name).
40210 Table import syntax error The table-import configuration file (.hdbti)
contains one or more syntax errors.
40211 Table import constraint checks The same key is specified in multiple table-im
failed port configurations (.hdbti files), which
leads to overlaps in the range of data to import.
40212 Importing data into table failed Either duplicate keys were written (due to du
plicates in the .CSV source file) or
40213 CSV table column count mismatch Either the number of columns in the .