0% found this document useful (0 votes)
383 views904 pages

SAP HANA Developer Guide For SAP HANA Studio en

Uploaded by

Prasad Raj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
383 views904 pages

SAP HANA Developer Guide For SAP HANA Studio en

Uploaded by

Prasad Raj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PUBLIC

SAP HANA Platform 2.0 SPS 04


Document Version: 1.1 – 2019-10-31

SAP HANA Developer Guide


For SAP HANA Studio
© 2019 SAP SE or an SAP affiliate company. All rights reserved.

THE BEST RUN


Content

1 SAP HANA Developer Guide for SAP HANA Studio. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

2 Introduction to SAP HANA Development. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10


2.1 SAP HANA Architecture. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
SAP HANA In-Memory Database. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
SAP HANA Database Architecture. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
SAP HANA Extended Application Services. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
SAP HANA-Based Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.2 Developer Information Map for XS Classic. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.3 Developer Scenarios. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Developing Native SAP HANA Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Developing Non-Native SAP HANA Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

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

4 Setting Up Your Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59


4.1 Roles and Permissions for XS Development. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .60
4.2 Maintaining Delivery Units. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Maintain the Delivery-Unit Vendor ID. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Create a Delivery Unit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .65
4.3 Using SAP HANA Projects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Maintain a Repository Workspace. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Create a Project for SAP HANA XS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .70
Share an SAP HANA XS Project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Import an SAP HANA XS Project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
4.4 Maintaining Repository Packages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Define the Repository Package Hierarchy. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
Assign Repository Package Privileges. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .81
Create a Repository Package. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Delete a Repository Package. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .85

SAP HANA Developer Guide


2 PUBLIC Content
4.5 Creating the Application Descriptors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Create an Application Descriptor File. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Enable Access to SAP HANA XS Application Packages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
Create an SAP HANA XS Application Privileges File. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
4.6 Maintaining Application Security. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
Set up Application Security. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Set up Application Authentication. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
4.7 Maintaining HTTP Destinations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
Tutorial: Create an HTTP Destination. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
Tutorial: Extend an HTTP Destination. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
Tutorial: Create an OAuth Configuration Package. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .135
4.8 Maintaining Application Artifacts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
Design-Time Application Artifacts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
Studio-Based SAP HANA Development Tools. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153

5 Setting up the Data Persistence Model in SAP HANA. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157


5.1 Creating the Persistence Model in Core Data Services. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .160
CDS Editors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
Create a CDS Document. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
Create an Entity in CDS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .189
Migrate an Entity from hdbtable to CDS (hdbdd). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .207
Create a User-Defined Structured Type in CDS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
Create an Association in CDS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
Create a View in CDS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
Modifications to CDS Artifacts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
Tutorial: Get Started with CDS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .266
Import Data with CDS Table-Import. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
5.2 Creating the Persistence Model with HDBTable. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
Create a Schema. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
Create a Table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
Create a Reusable Table Structure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .296
Create a Sequence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
Create an SQL View. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
Create a Synonym. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
Import Data with hdbtable Table-Import. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319

6 Setting Up the Analytic Model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333


6.1 Setting Up the Modeling Environment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
Set Modeler Preferences. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
Set Keyboard Shortcuts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
6.2 Creating Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
Attributes and Measures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335

SAP HANA Developer Guide


Content PUBLIC 3
First Steps to View Creation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
Create Attribute Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
Native HANA Models. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
Create Graphical Calculation Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
Create Script-Based Calculation Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
Activating Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
Description Mapping. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
Import BW Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
Group Related Measures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
6.3 Additional Functionality for Information Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
Create Level Hierarchies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
Create Parent-Child Hierarchies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .374
Input Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
Assign Variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .379
Using Currency and Unit of Measure Conversions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
Manage Information Views with Missing Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .380
6.4 Working with Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
Manage Editor Layout. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
Validate Models. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
Maintain Search Attributes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
Data Preview Editor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
Using Functions in Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
Resolving Conflicts in Modeler Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .384
6.5 Create Decision Tables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
Changing the Layout of a Decision Table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
Using Parameters in a Decision Table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
Using Calculated Attributes in Decision Tables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
6.6 Generate Object Documentation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393

7 Developing Procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .394


7.1 SQLScript Security Considerations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .395
7.2 Create and Edit Procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
Define and Use Table Types in Procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
Tutorial: Create an SQLScript Procedure that Uses Imperative Logic. . . . . . . . . . . . . . . . . . . . . 401
7.3 Create Scalar and Table User-Defined Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
Tutorial: Create a Scalar User-Defined Function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
Tutorial: Create a Table User-Defined Function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
7.4 Create Procedure Templates. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
Create Procedure Template Instances. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
Update Procedure Templates and Instances. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
Delete Procedure Templates and Instances. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .419
7.5 Debugging Procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420

SAP HANA Developer Guide


4 PUBLIC Content
Setup Debugger Privileges. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
Debug Design-Time and Catalog Procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .421
Debug an External Session. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
7.6 Developing Procedures in the Modeler Editor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .426
7.7 Transforming Data Using SAP HANA Application Function Modeler. . . . . . . . . . . . . . . . . . . . . . . . 427
Converting deprecated AFL Models (AFLPMML objects). . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
Setting up the SAP HANA Application Function Modeler. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
Flowgraphs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
Modeling a flowgraph. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
Tutorial: Creating a Runtime Procedure using Application Function Modeler (AFM). . . . . . . . . . .472
Node palette flowgraphs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476

8 Defining Web-based Data Access in XS Classic. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481


8.1 Data Access with OData in SAP HANA XS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
OData in SAP HANA XS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
Define the Data an OData Service Exposes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
OData Service Definitions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
Create an OData Service Definition. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
Tutorial: Use the SAP HANA OData Interface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
OData Service-Definition Examples. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
OData Service Definition Language Syntax (XS Advanced). . . . . . . . . . . . . . . . . . . . . . . . . . . . 516
OData Service Definition: SQL-EDM Type Mapping (XS Advanced). . . . . . . . . . . . . . . . . . . . . . 518
OData Security Considerations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
OData Batch Requests (XS Advanced). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
8.2 Data Access with XMLA in SAP HANA XS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523
XML for Analysis (XMLA). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
XMLA Service Definition. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
XMLA Security Considerations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
Multidimensional Expressions (MDX). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .526
MDX Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
MDX Extensions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
Define the Data an XMLA Service Exposes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 532
Create an XMLA Service Definition. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
Tutorial: Use the SAP HANA XMLA Interface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 534
8.3 Using the SAP HANA REST API. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536
SAP HANA REST Info API. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
SAP HANA REST File API. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
SAP HANA REST Change-Tracking API. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
SAP HANA REST Metadata API. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
SAP HANA REST Transfer API. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546
SAP HANA REST Workspace API. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 547

SAP HANA Developer Guide


Content PUBLIC 5
9 Writing Server-Side JavaScript Code. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549
9.1 Data Access with JavaScript in SAP HANA XS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549
9.2 Using Server-Side JavaScript in SAP HANA XS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 550
Tutorial: Write Server-Side JavaScript Application Code. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 550
9.3 Using Server-Side JavaScript Libraries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564
Import Server-Side JavaScript Libraries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .566
Write Server-Side JavaScript Libraries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567
9.4 Using the Server-Side JavaScript APIs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 568
Tutorial: Use the XSJS Outbound API. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580
Tutorial: Call an XS Procedure with Table-Value Arguments. . . . . . . . . . . . . . . . . . . . . . . . . . . 584
Tutorial: Query a CDS Entity using XS Data Services. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589
Tutorial: Update a CDS Entity Using XS Data Services. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 594
9.5 Creating Custom XS SQL Connections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597
Create an XS SQL Connection Configuration. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599
9.6 Setting the Connection Language in SAP HANA XS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 605
9.7 Scheduling XS Jobs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 607
Tutorial: Schedule an XS Job. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .608
Add or Delete a Job Schedule during Runtime. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617
9.8 Tracing Server-Side JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619
Trace Server-Side JavaScript Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619
View XS JavaScript Application Trace Files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 621
9.9 Debugging Server-Side JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 621
Create a Debug Configuration. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
Execute XS JavaScript Debugging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 626
Troubleshoot Server-Side JavaScript Debugging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631
9.10 Testing XS JavaScript Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 633
Automated Tests with XSUnit in SAP HANA. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 634
Application Development Testing Roles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 635
Test an SAP HANA XS Application with XSUnit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 635
Testing JavaScript with XSUnit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649

10 Building UIs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 656


10.1 Building User Interfaces with SAPUI5 for SAP HANA. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 656
10.2 Consuming Data and Services with SAPUI5 for SAP HANA. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 657
10.3 SAPUI5 for SAP HANA Development Tutorials. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 658
Tutorial: Create a Hello-World SAP UI5 Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 659
Tutorial: Consume an XSJS Service from SAPUI5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 663
Tutorial: Consume an OData Service from SAPUI5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 669
Tutorial: Consume an OData Service with the CREATE Option. . . . . . . . . . . . . . . . . . . . . . . . . .676
Tutorial: Create and Translate Text Bundles for SAPUI5 Applications. . . . . . . . . . . . . . . . . . . . . 683
10.4 Using UI Integration Services. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 688
Creating Content for Application Sites. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 689

SAP HANA Developer Guide


6 PUBLIC Content
SAP Fiori Launchpad Sites. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 701
Creating a Standard Site. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .708
Configuring the SAP HANA Home Page. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 709

11 Setting Up Roles and Privileges. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .710


11.1 Create a Design-Time Role. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 711
Database Roles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 717
Privileges. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 728
11.2 Creating Analytic Privileges. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 750
Create Classical XML-based Analytic Privileges. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 751
Create SQL Analytic Privileges. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .754
Analytic Privileges. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 756

12 SAP HANA Application Lifecycle Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 778


12.1 Preparing to Use SAP HANA Application Lifecycle Management. . . . . . . . . . . . . . . . . . . . . . . . . . 780
Assign User Roles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .781
Maintain the Delivery-Unit Vendor ID. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 785
12.2 Setting Up the Transport. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 787
Setting Up and Using Native SAP HANA Transport. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 788
Setting Up and Using CTS Transport. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 796
12.3 Maintaining Delivery Units. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 805
Create a Delivery Unit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 806
Assign Packages to a Delivery Unit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 808
Export a Delivery Unit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809
Import a Delivery Unit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 811
12.4 Maintaining Products. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .812
Create a Product. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 813
Assign a Delivery Unit to a Product. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .815
12.5 SAP HANA Change Recording. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 816
Enable SAP HANA Change Recording. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 817
Create Changelists. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 819
Assign Objects to Changelists. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 820
Approve Contributions to Changelists. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 822
Release Changelists. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 823
Filter and Search for Changelists. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 824
12.6 Assembling Add-On Products and Software Components. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 826
12.7 Installing and Updating SAP HANA Products and Software Components in SAP HANA XS Classic
Model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 828
12.8 Using hdbalm. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 829
hdbalm Commands, Options, and Variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 831
Enable SSL for hdbalm. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 835
Proxy Support for hdbalm. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .836

SAP HANA Developer Guide


Content PUBLIC 7
hdbalm install Command. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 837
hdbalm assemble Command. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 841
hdbalm import Command. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 842
hdbalm transport Command. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .843
hdbalm log Command. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 844
hdbalm product Command. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .845
hdbalm du Command. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 846
hdbalm dependencies Command. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 848
hdbalm package Command. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 849
hdbalm admin Command. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 850
12.9 SAP HANA Repository Translation Tool. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 851
SAP HANA Repository Translation Tool (RTT) Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . 853
Configure the Repository Translation Tool. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .855
Create Text-Strings Packages for Translation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 856
Export Text-Strings Files for Translation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 857
Import Translated Text-Strings Files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 857
12.10 Maintaining Translation Text Strings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 858
Create and Edit Text Translations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .859
Export and Import Translated Text. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 864

13 SAP HANA Database Client Interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 866


13.1 Setting Session-Specific Client Information. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 867
13.2 Connect to SAP HANA via ODBC. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .871
Use the User Store (hdbuserstore). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 873
Test the ODBC Installation on Microsoft Windows. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 874
13.3 Connect to SAP HANA via JDBC. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 875
Trace a JDBC Connection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 876
Valid Java-to-SQL Conversions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 880
JDBC Command-Line Connection Options. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 883
JDBC Connection Options in Java Code. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 884
13.4 Connect to SAP HANA via ODBO. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 885
Connecting with Microsoft Excel. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 886
Multidimensional Expressions (MDX). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .887
MDX Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 888
MDX Extensions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 891

14 Migrating XS Classic Applications to XS Advanced Model. . . . . . . . . . . . . . . . . . . . . . . . . . . 894


14.1 The XS Advanced Application-Migration Process. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 895
14.2 The XS Advanced Migration Assistant. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 897
14.3 The XS Application Migration Report. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 899
14.4 Legacy Object Types not Supported in XS Advanced. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 900

SAP HANA Developer Guide


8 PUBLIC Content
1 SAP HANA Developer Guide for SAP
HANA Studio

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:

● Introduction and overview


A high-level overview of the basic capabilities and architecture of SAP HANA XS classic model. This section
also includes an information map, which is designed to help you navigate the library of information
currently available for SAP HANA developers.
● Getting started
A collection of tutorials which are designed to demonstrate how to build and deploy a simple SAP HANA-
based application on SAP HANA XS classic model quickly and easily
● The development process
Step-by-step information that shows in detail how to develop the various elements that make up an XS
classic application. The information provided uses tasks and tutorials to explain how to develop the SAP
HANA development objects. Where appropriate, you can also find background information that explains
the context of the task, and reference information that provides the detail you need to adapt the task-
based examples to suit the requirements of your application environment.
● Reference sources
A selection of reference guides that support the XS classic application development process, for example:
information about application life-cycle management including transport packages, and details of the
client interfaces you can use to connect applications to SAP HANA.

SAP HANA Developer Guide


SAP HANA Developer Guide for SAP HANA Studio PUBLIC 9
2 Introduction to SAP HANA Development

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.

This guide is organized as follows:

● Introduction and overview


○ SAP HANA architecture
Describes the basic capabilities and architecture of SAP HANA
○ SAP HANA developer information map
Information in graphical and textual form that is designed to help you navigate the library of
information currently available for SAP HANA developers and find the information you need quickly
and easily. The information provided enables access from different perspectives, for example: by SAP
HANA guide, by development scenario, or by development task
○ SAP HANA development scenarios
Describes the main developer scenarios for which you can use SAP HANA to develop applications. The
information focuses on native development scenarios, for example, applications based on SAP HANA
XS JavaScript and XS OData services, but also provides a brief overview of the development of non-
native applications (for example, using JDBC, ODBC, or ODBO connections to SAP HANA).
● Getting started
A collection of tutorials which are designed to demonstrate how to build a simple SAP HANA-based
application quickly and easily, including how to use the SAP HANA studio tools and work with the SAP
HANA repository
● The development process
Most of the remaining chapters use tasks and tutorials to explain how to develop the SAP HANA
development objects that you can include in your SAP HANA application. Where appropriate, you can also
find background information which explains the context of the task and reference information that
provides the detail you need to adapt the task-based information to suit the requirements of your
application enviroment.
Some of the tutorials in this guide refer to models that are included in the demonstration content provided
with the SAP HANA Interactive Education (SHINE) delivery unit (DU). The SHINE DU is available for
download in the SAP Software Download Center.

 Note

Access to the SAP Software Download Center is only available to SAP customers and requires logon
credentials.

Audience

This guide is aimed at people performing the following developer roles:

SAP HANA Developer Guide


10 PUBLIC Introduction to SAP HANA Development
● Database developers
Often a business/data analyst or database expert, the database developer is concerned with the definition
of the data model and schemas that will be used in SAP HANA, the specification and definition of tables,
views, primary keys, indexes, partitions and other aspects of the layout and inter-relationship of the data in
SAP HANA.
The database developer is also concerned with designing and defining authorization and access control,
through the specification of privileges, roles and users.
● Application programmers
The programmer is concerned with building SAP HANA applications, which could take many forms but are
designed based on the model-view-controller architecture. Programmers develop the code for the
following component layers:
○ Views
Running inside a browser or on a mobile device
○ Controller
Typically running in the context of an application server
○ Model
Interacting closely with the data model and performing queries. Using embedded procedures or
libraries, the model can be developed to run within the SAP HANA data engine.
● Client UI developers
The user-interface (UI) client developer designs and creates client applications which bind business logic
(from the application developer) to controls, events, and views in the client application user interface. In
this way, data exposed by the database developer can be viewed in the client application's UI.

Related Information

SAP HANA Architecture [page 11]


Developer Information Map
Developer Scenarios [page 19]

2.1 SAP HANA Architecture

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 Developer Guide


Introduction to SAP HANA Development PUBLIC 11
2.1.1 SAP HANA In-Memory Database

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.

[Link] Columnar Data Storage


A database table is conceptually a two-dimensional data structure organized in rows and columns. Computer
memory, in contrast, is organized as a linear structure. A table can be represented in row-order or column-
order. A row-oriented organization stores a table as a sequence of records. Conversely, in column storage the
entries of a column are stored in contiguous memory locations. SAP HANA supports both, but is particularly
optimized for column-order storage.

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.

[Link] Parallel Processing


SAP HANA was designed to perform its basic calculations, such as analytic joins, scans and aggregations in
parallel. Often it uses hundreds of cores at the same time, fully utilizing the available computing resources of
distributed systems.

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

SAP HANA Developer Guide


12 PUBLIC Introduction to SAP HANA Development
efficiently be executed in the CPU cache. With row-oriented storage, the same operation would be much slower
because data of the same column is distributed across memory and the CPU is slowed down by cache misses.

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.

[Link] Simplifying Applications

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.

SAP HANA Developer Guide


Introduction to SAP HANA Development PUBLIC 13
2.1.2 SAP HANA Database Architecture

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.

SAP HANA Database High-Level Architecture

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 Developer Guide


14 PUBLIC Introduction to SAP HANA Development
functional libraries are the SAP HANA Business Function Library (BFL) and the SAP HANA Predictive Analytics
Library (PAL). BFL and PAL functions can be called directly from within SQLScript.

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.

2.1.3 SAP HANA Extended Application Services

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.

SAP HANA Developer Guide


Introduction to SAP HANA Development PUBLIC 15
In support of this data-integrated application paradigm, SAP HANA Extended Application Services provides a
comprehensive set of embedded services that provide end-to-end support for Web-based applications. This
includes a lightweight web server, configurable OData support, server-side JS execution and, of course, full
access to SQL and SQLScript.

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.

SAP HANA Developer Guide


16 PUBLIC Introduction to SAP HANA Development
The application services can be used to expose the database data model, with its tables, views and database
procedures, to clients. This can be done in a declarative way using OData services or by writing native
application-specific code that runs in the SAP HANA context . Also, you can use SAP HANA XS to build
dynamic HTML5 UI applications.

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

SAPUI5 Demo Kit (version 1.28)


SAP HANA Search Developer Guide
SAP Note 1779803

2.1.4 SAP HANA-Based Applications

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.

SAP HANA Developer Guide


Introduction to SAP HANA Development PUBLIC 17
The SAP HANA XS server completes SAP HANA to make it a comprehensive development platform. With the
SAP HANA XS server, developers can write SAP HANA-based applications that cover all server-side aspects,
such as tables and database views, database procedures, server-side control logic, integration with external
systems, and provisioning of HTTP-based services. The integration of the SAP HANA XS server into the SAP
HANA system also helps to reduce cost of ownership, as all servers are installed, operated and updated as one
system.

2.2 Developer Information Map for XS Classic

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.

SAP HANA Developer Guide


18 PUBLIC Introduction to SAP HANA Development
Application Development in SAP HANA XS Classic Model

Related Information

Developer Information Map

2.3 Developer Scenarios


The possibility to run application specific code in SAP HANA creates several possibilities for developing SAP
HANA based applications, representing various integration scenarios, and corresponding development
processes.

Application developers can choose between the following scenarios when designing and building applications
that access an SAP HANA data model:

● Native Application Development


Native applications are developed and run in SAP HANA, for example, using just SQLScript or the extended
application services provided by the SAP HANA XS platform (or both)

SAP HANA Developer Guide


Introduction to SAP HANA Development PUBLIC 19
● Non-native Application Development
Non-native applications are developed in a separate, external environment (for example, ABAP or Java)
and connected to SAP HANA by means of an external application server and a client connection: ADBC,
JDBC, ODBC, or ODBO. These more traditional scenarios only use SQL and native SQLScript procedures.

Native and Non-Native SAP HANA Application Architecture

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).

SAP HANA Developer Guide


20 PUBLIC Introduction to SAP HANA Development
SAP HANA Applications and Development Languages

2.3.1 Developing Native SAP HANA Applications

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:

● All application artifacts are stored in the SAP HANA repository


● Server-side procedural logic is defined in server-side (XS) JavaScript or SQLScript
● UI rendering occurs completely in the client (browser, mobile applications)

SAP HANA Developer Guide


Introduction to SAP HANA Development PUBLIC 21
Each of the levels illustrated in the graphic is manifested in a particular technology and dedicated languages:

Native SAP HANA Application Development with SAP HANA XS

● Calculation Logic - data-processing technology:


○ Data:
SQL / SQLScript, Core Data Services (CDS), DDL, HDBtable
○ SQL / SQLScript
○ Calculation Engine Functions (CE_*)

 Note

SAP recommends you use SQL rather than the Calculation Engine functions.

○ Application Function Library (AFL)


● Control-flow logic with SAP HANA XS:
○ OData
Validation models for OData services can be written in XS JavaScript or SQLScript
○ Server-Side JavaScript (XSJS)
HTTP requests are implemented directly in XS JavaScript
○ XMLA
● Client UI/Front-end technology:
○ HTML5 / SAPUI5
○ Client-side JavaScript

SAP HANA Developer Guide


22 PUBLIC Introduction to SAP HANA Development
The development scenarios for native application development are aimed at the following broadly defined
audiences:

Target Development Audience for Native SAP HANA Applications


Audience Language Tools Development Artifacts

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

Database Development Scenarios [page 23]


Professional Application Development Scenarios [page 24]
UI Client-Application Development Scenarios [page 25]

[Link] Database Development Scenarios

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.

Typical Database-Development Tasks


Task Details Information Source

Create tables, SQL views, sequences… Code, syntax, … SAP HANA SQLScript Reference

SAP HANA SQL and System Views Ref­


erence

SAP HANA Developer Guide for SAP


HANA Studio

Packaging, activation, implementation, SAP HANA Developer Guide for SAP


… HANA Studio

SAP HANA Developer Guide


Introduction to SAP HANA Development PUBLIC 23
Task Details Information Source

Create attribute, analytic, calculation Code, syntax, … SAP HANA SQLScript Reference
views
SAP HANA Developer Guide for SAP
HANA Studio

Packaging, activation, implementation, SAP HANA Developer Guide for SAP


… HANA Studio

Examples, background SAP HANA Modeling Guide for SAP


HANA Studio

Create/Write SQLScript procedures, Code, syntax, … SAP HANA SQLScript Reference


UDFs, triggers…
SAP HANA SQL and System Views Ref­
erence

SAP HANA Developer Guide for SAP


HANA Studio

Packaging, activation, implementation, SAP HANA Developer Guide for SAP


… HANA Studio

Create/Use application functions Code, syntax, … SAP HANA SQLScript Reference

SAP HANA Business Function Library


(BFL) (*)

SAP HANA Predictive Analysis Library


(PAL) (*)

SAP HANA Developer Guide for SAP


HANA Studio

Packaging, activation, implementation, 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.

[Link] Professional Application Development Scenarios

The primary focus of the professional application developer it to create applications.

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.

SAP HANA Developer Guide


24 PUBLIC Introduction to SAP HANA Development
Typical Application-Development Tasks
Task Details Information Source

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)

SQL code, syntax, … SAP HANA SQLScript Reference

UI controls, events… SAPUI5 Demo Kit (version 1.28)

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

UI controls, events… SAPUI5 Demo Kit (version 1.28)

[Link] UI Client-Application Development Scenarios

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.

Typical UI-Client Development Tasks


Task Details Information Source

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)

2.3.2 Developing Non-Native SAP HANA Applications

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.

SAP HANA Developer Guide


Introduction to SAP HANA Development PUBLIC 25
 Note

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.

Non-native SAP HANA Application Architecture

Related Information

ABAP Client Interface [page 27]


The JDBC Client Interface [page 27]
ODBC Client Interface [page 28]
ODBO Client Interface [page 28]

SAP HANA Developer Guide


26 PUBLIC Introduction to SAP HANA Development
[Link] ABAP Client Interface

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.

[Link] The JDBC Client Interface

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:

1. Write a Java application in your own development environment.


2. Connect the Java development environment to SAP HANA using the JDBC client interface; the Java
environment can be either:
○ A Java application server
○ Your development machine
3. Run the Java application to connect to an SAP HANA data model.

Related Information

Connect to SAP HANA via JDBC [page 875]

SAP HANA Developer Guide


Introduction to SAP HANA Development PUBLIC 27
[Link] ODBC Client Interface

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:

1. Install the client ODBC interface on your development machine.


2. Write a .NET application in your development environment.
3. Connect the .NET application to SAP HANA using the ODBC interface.
4. Run the .NET application to connect to an SAP HANA data model.

 Note

The SAP HANA data provider for Microsoft [Link] is installed as part of the SAP HANA client installation.

Related Information

Connect to SAP HANA via ODBC [page 871]

[Link] ODBO Client Interface

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:

1. Install the client ODBO interface on your development machine.


2. Write an application that uses multi-dimensional expressions (MDX) in your own development
environment.
3. Connect the application to SAP HANA using the ODBO interface.
4. Run the Windows-based MDX application to connect to an SAP HANA data model.

Related Information

Connect to SAP HANA via ODBO [page 885]

SAP HANA Developer Guide


28 PUBLIC Introduction to SAP HANA Development
[Link] SAP HANA Data Provider for Microsoft [Link]

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

SAP HANA Developer Guide


Introduction to SAP HANA Development PUBLIC 29
3 Getting Started

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.

As part of the getting-started process, you go through the following steps:

● 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.

● Creating application descriptors


Each native SAP HANA application requires descriptor files. The application descriptors are the core files
that you use to describe an application's framework within SAP HANA XS, for example: to mark the root
point from which content can be served, which content is to be exposed, or who has access to the content.
● Tutorials
A selection of “Hello World” tutorials are used to demonstrate the application-development process in SAP
HANA XS and show you how to produce a simple application quickly and easily. Some of the tutorials in
this guide refer to models that are included in the demonstration content provided with the SAP HANA
Interactive Education (SHINE) delivery unit (DU). The SHINE DU is available for download in the SAP
Software Download Center.

 Note

Access to the SAP Software Download Center is only available to SAP customers and requires logon
credentials.

Related Information

Prerequisites [page 31]

SAP HANA Developer Guide


30 PUBLIC Getting Started
3.1 Prerequisites
To start working with the tools provided to enable application development on SAP HANA Extended Application
Services (SAP HANA XS), it is necessary to ensure that the developers have the required software and access
permissions.

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.

● Access to the SAP HANA repository


● Access to selected run-time catalog objects
● Some of the tutorials in this guide refer to models that are included in the demonstration content provided
with the SAP HANA Interactive Education (SHINE) delivery unit (DU). The SHINE DU is available for
download in the SAP Software Download Center.

 Note

Access to the SAP Software Download Center is only available to SAP customers and requires logon
credentials.

3.2 SAP HANA Studio


The SAP HANA studio is an Eclipse-based development and administration tool for working with SAP HANA.
You use the SAP HANA studio to develop native applications that can take advantage of the benefits provided
by SAP HANA Extended Application Services (SAP HANA XS).

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:

● The SAP HANA Development perspective


Provides views and menu options that enable you to perform all the tasks relating to application
development on SAP HANA XS, for example: to manage application-development projects, display content

SAP HANA Developer Guide


Getting Started PUBLIC 31
of application packages, and browse the SAP HANA repository. You can also define your data-persistence
model here by using design-time artifacts to define tables, views, sequences, and schemas.
● The Debug perspective
Provides views and menu options that help you test your applications, for example: to view the source
code, monitor or modify variables, and set break points.
● The Modeler perspective
Provides views and menu options that enable you to define your analytic model, for example, attribute,
analytic, and calculation views of SAP HANA data.
● The Team Synchronizing perspective
Provides views and menu options that enable you to synchronize artifacts between your local file system
and the SAP HANA Repository.
● The Administration Console perspective
Provides views that enable you to perform administrative tasks on SAP HANA instances.

3.2.1 The SAP HANA Development Perspective

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:

● Creating and sharing projects


● Creating and modifying development objects
● Managing development object versions
● Committing development objects to the SAP HANA repository

 Note

By default, saving a file automatically commits the saved version of the file to the Repository.

● Activating development objects in the SAP HANA 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.

SAP HANA Developer Guide


32 PUBLIC Getting Started
[Link] The Repositories View

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.

SAP HANA Developer Guide


Getting Started PUBLIC 33
The Repositories view is a list of repository workspaces that you have created for development purposed on
various SAP HANA systems. Generally, you create a workspace, check out files from the repository, and then
do most of your development work in the Project Explorer. However, with more recent versions of SAP HANA,
you can use the Repositories view to perform actions directly on repository objects in multiple workspaces, for
example: edit objects, activate objects, and manage object versions - all without the need to set up a project.
The Repositories view also provides direct access to lifecycle-management tools.

[Link] The Project Explorer View

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.

SAP HANA Developer Guide


34 PUBLIC Getting 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.

[Link] The Systems View

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.

The Systems view is divided into the following main sections:

● 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.

SAP HANA Developer Guide


Getting Started PUBLIC 35
3.3 SAP HANA XS Application Descriptors

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.

● The application descriptor


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.
● The application-access file
The configuration file you use to specify who or what is authorized to access the content exposed by an
SAP HANA XS application package and what content they are allowed to see. For example, you use the
application-access file to specify the following:
○ The application content that can be exposed to client requests
○ The authentication method used to enable access to package content, for example, form-based, basic,
or none at all.

3.4 SAP HANA Projects

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:

1. Add a development system


2. Create a development workspace.
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. When you check out a package from the
repository, SAP HANA copies the contents of the package hierarchy to your workspace. To ensure that the
changes you make to project-related files are visible to other team members, you must commit the
artifacts back into the repository and activate them.

 Note

By default, saving the file automatically commits the saved version of the file to the repository.

SAP HANA Developer Guide


36 PUBLIC Getting Started
3. Create a project
You use the project to collect all your application-related artifacts in one convenient place. Shared projects
enable multiple people to work on the same files at the same time.

 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

Tutorial: Use the SAP HANA OData Interface [page 54]


Tutorial: My First SAP HANA Application [page 38]

SAP HANA Developer Guide


Getting Started PUBLIC 37
3.5.1 Tutorial: My First SAP HANA Application

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:

● Connect to an SAP HANA system


Add (and connect to) an SAP HANA system, which hosts the repository where development objects are
stored
● Create a repository workspace
Create a development workspace which enables you to synchronize the development artifacts in your local
file system with the repository hosted on the SAP HANA system you connect to.
● Create and share a project
Add a project which you can use to hold the application-development artifacts in a convenient central
location.
Sharing the project makes the contents of the new project available to other members of the application-
development team by linking the local project to the SAP HANA repository. In this way, you can manage
object versions and synchronize changes to development objects.
● Write server-side JavaScript code
Use JavaScript code to extract data from the SAP HANA database in response to a client request; the code
will include SQLScript to perform the data extraction.
● Display data
Display data extracted from the SAP HANA database in a Web browser.

Related Information

Tutorial: Add an SAP HANA System [page 39]


Tutorial: Add a Repository Workspace [page 42]
Tutorial: Add an Application Project [page 44]
Tutorial: Write Server-Side JavaScript [page 49]
Tutorial: Retrieve Data from SAP HANA [page 53]

SAP HANA Developer Guide


38 PUBLIC Getting Started
[Link] Tutorial: Add an SAP HANA System

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.

● Access to the SAP HANA Repository

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

1. Open SAP HANA studio.


2. Open the SAP HANA Development perspective.
3. In the Systems view, click [+] Add System... and choose Add System....

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

SAP HANA Developer Guide


Getting Started PUBLIC 39
the tenant database. Every tenant database requires a virtual host name so that the system's internal
SAP Web Dispatcher can forward HTTP requests to the XS server of the correct database.

 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.

SAP HANA Developer Guide


40 PUBLIC Getting Started
Results

After adding the system, you will see the system in the Systems view.

SAP HANA Developer Guide


Getting Started PUBLIC 41
[Link] Tutorial: Add a Repository Workspace

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.

To create a repository workspace, perform the following steps:

Procedure

1. Open SAP HANA studio.


2. In the SAP HANA Development perspective, open the Repositories view.

3. In the Repositories view, choose File New Repository Workspace .


4. You must provide the following information:

○ SAP HANA system


The name of the SAP HANA system hosting the repository that you want to synchronize your
workspace with; choose the same system you just added for this tutorial.
○ Workspace Name
If a default repository workspace exists, uncheck the Default workspaceoption and enter a workspace
name; the workspace name can be anything you like, for example, DevWS.
A folder with the name you type is created below the Workspace Root.
○ Workspace root
The Workspace Root is a folder that contains the workspace you create in this step. The Workspace
Root can be anywhere on your local file system. For this tutorial, create a folder at C:\users\<PATH>
\workspaces and make this the Workspace Root.

SAP HANA Developer Guide


42 PUBLIC Getting Started
5. Click Finish.

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.

6. Remove a repository workspace.

SAP HANA Developer Guide


Getting Started PUBLIC 43
If it is necessary to remove a workspace, you can choose between multiple deletion options; the option you
choose determines what is removed, from where (local file system or remote repository), and what, if
anything, is retained.
a. Open the SAP HANA Development perspective.
b. Choose the Repositories view and expand the repository node containing the workspace you want to
remove.
c. Right-click the workspace you want to remove.
d. Choose the workspace-deletion mode.
The following modes apply when you delete a workspace in SAP HANA studio:

Workspace Deletion Modes


Workspace Deletion Mode Description

Delete Remove workspace; delete all workspace-related local


files; delete related changes to remote (repository)
data.

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.

[Link] Tutorial: Add an Application Project

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.

SAP HANA Developer Guide


44 PUBLIC Getting Started
There are a variety of project types for different types of development objects. Generally, a project type ensures
that only the necessary libraries are imported to enable you to work with development objects that are specific
to a project type. In this tutorial, you create an XS Project.

Procedure

1. Open SAP HANA studio.

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.

SAP HANA Developer Guide


Getting Started PUBLIC 45
5. Choose Finish.

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.

SAP HANA Developer Guide


46 PUBLIC Getting Started
 Note

If you disabled the option Share project in SAP repository when you created the project, you must share the
new project manually.

Related Information

Tutorial: Share an Application Project [page 47]

[Link] Tutorial: Share an Application Project

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.

SAP HANA Developer Guide


Getting Started PUBLIC 47
If you need to manually share a project, perform the following steps:

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.

SAP HANA Developer Guide


48 PUBLIC Getting Started
The .project file is shown with an asterisk , which indicates that the file has changed but has yet to be
committed to the repository.

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].

[Link] Tutorial: Write Server-Side JavaScript

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.

SAP HANA Developer Guide


Getting Started PUBLIC 49
Context

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

1. Open SAP HANA studio.


2. Open the SAP HANA Development perspective.

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.

SAP HANA Developer Guide


50 PUBLIC Getting Started
The application descriptors (.xsapp and .xsaccess) are mandatory and describe the framework in
which an SAP HANA XS application runs. The .xsapp file indicates the root point in the package hierarchy
where content is to be served to client requests; the .xsaccess file defines who has access to the exposed
content and how.

 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.

SAP HANA Developer Guide


Getting Started PUBLIC 51
9. Activate the new files in the SAP HANA repository.
Activating a file makes the file available to other project members. Right-click the new files (or the folder/
package containing the files) and select Team Activate from the context-sensitive popup menu.
The activate operation publishes your work and creates the corresponding catalog objects; you can now
test it.

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.

If everything works as expected, you should see the following result:

SAP HANA Developer Guide


52 PUBLIC Getting Started
After logging in with your SAP HANA user name and password, the following page should be displayed:

[Link] Tutorial: Retrieve Data from SAP HANA

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:

select * from DUMMY

The SQL statement returns one row with one field called DUMMY, whose value is X.

Procedure

1. Open SAP HANA studio.


2. Open the SAP HANA Development perspective.
3. In the Project Explorer view, located the server-side JavaScript file [Link] and open
it in the embedded JavaScript editor.
4. In [Link], replace your existing code with the code in the following example.

$.[Link] = "text/html";
var output = "Hello, World !";
var conn = $.[Link]();

SAP HANA Developer Guide


Getting Started PUBLIC 53
var pstmt = [Link]( "select * from DUMMY" );
var rs = [Link]();
if (![Link]()) {
$.[Link]( "Failed to retrieve data" );
$.[Link] = $.[Link].INTERNAL_SERVER_ERROR;
} else {
output = output + "This is the response from my SQL: " + [Link](1);
}
[Link]();
[Link]();
[Link]();
$.[Link](output);

5. Save the file [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:

3.5.2 Tutorial: Use the SAP HANA OData Interface

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:

● Create a development workspace in the SAP HANA repository


● Create a project in the workspace

SAP HANA Developer Guide


54 PUBLIC Getting Started
● Share the new project

Context

To create a simple OData application, 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 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.

2. Create a schema, for example, HELLO_ODATA.hdbschema.


The schema is required for the table that contains the data to be exposed by your OData service-definition.
The schema is defined in a flat file with the file extension .hdbschema that you save in the repository and
which you must activate.

 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.

Enter the following code in the HELLO_ODATA.hdbschema file:

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.

SAP HANA Developer Guide


Getting Started PUBLIC 55
 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.

Enter the following code in the [Link] file:

 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"];

4. Grant SELECT privileges to the owner of the new schema.


After activation in the repository, the 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 in the SAP HANA
studio's Modeler perspective, you must grant the user the required SELECT privilege.
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>');

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.

SAP HANA Developer Guide


56 PUBLIC Getting Started
b. Save and activate the application-descriptor file in the 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.

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.

c. Save and activate the application-access file in the repository.


7. Create an OData service-definition file and place it in your root OData package helloodata.
The Odata service-definition file has the file extension .xsodata, for example, [Link] and for
the purposes of this tutorial should be located in the root package of the OData application:

 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";

SAP HANA Developer Guide


Getting Started PUBLIC 57
}

c. Save and activate the OData service-definition file in the repository.


8. Test the new OData service.
Open a browser and enter the following URL.

 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.

SAP HANA Developer Guide


58 PUBLIC Getting Started
4 Setting Up Your Application

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:

Application Setup Steps


Step Action Notes

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.

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 59
Related Information

Roles and Permissions for XS Development [page 60]


Maintaining Delivery Units [page 62]
Using SAP HANA Projects [page 67]
Maintaining Repository Packages [page 75]
Creating the Application Descriptors [page 86]
Set up Application Security [page 111]

4.1 Roles and Permissions for XS Development

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:

● SAP HANA XS Classic Model [page 60]


● SAP HANA XS Advanced Model [page 61]

 Note

The required privileges can only be granted by someone who has the necessary authorizations in SAP
HANA, for example, an SAP HANA administrator.

SAP HANA XS Classic Model

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

SAP HANA Developer Guide


60 PUBLIC Setting Up Your Application
 Note

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:

● One of the following:


○ MODELING
The predefined MODELING role assigns wide-ranging SQL privileges, for example, on _SYS_BI and
_SYS_BIC. It also assigns the analytic privilege _SYS_BI_CP_ALL, and some system privileges. If these
permissions are more than your development team requires, you can create your own role with a set of
privileges designed to meet the needs of the application-development team.
○ Custom DEVELOPMENT role
A user with the appropriate authorization can create a custom DEVELOPMENT role specially for
application developers. The new role would specify only those privileges an application-developer
needs to perform the everyday tasks associated with application development, for example:
maintaining packages in the repository, executing SQL statements, displaying data previews for views,
and so on.
● PUBLIC
This is a role that is assigned to all users by default.

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.

SAP HANA XS Advanced Model

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)

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 61
● A valid user account in the SAP HANA database on that system
● Access to development tools, for example, provided in:
○ SAP Web IDE for SAP HANA
○ SAP HANA Run-time Tools (included in the SAP Web IDE for SAP HANA)

 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.

● Access to the SAP HANA XS advanced design-time workspace and repository


● Access to selected run-time catalog objects
● Access to the XS command-line interface (CLI); the XS CLI client needs to be downloaded and installed

Related Information

Create a Design-Time Role [page 711]


Assign Repository Package Privileges [page 81]
SAP HANA Web-Based Development Workbench

4.2 Maintaining Delivery Units

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:

● You have access to an SAP HANA system.


● You have been assigned the privileges granted by a role based on the SAP HANA
[Link]::Administrator user role template.
● A vendor ID (repository namespace) is already defined.

SAP HANA Developer Guide


62 PUBLIC Setting Up Your Application
Context

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

1. Understand delivery units.


You must be familiar with the conventions that exist for delivery-unit names and understand the phases of
the delivery-unit lifecycle.
2. Maintain details of the vendor ID associated with a delivery unit.
Delivery units are located in the namespace associated with the vendor who creates them and who
manages the delivery-unit's lifecycle.
3. Create a delivery unit.
Create a transportable “container” to hold the repository packages in application.
4. Assign packages to a delivery unit.
Add to a delivery unit the repository packages that make up your application.
5. Export a delivery unit.
You can export the contents of a delivery unit from the SAP HANA Repository to a compressed Zip archive,
which you can download to a client file system.
6. Import a delivery unit.
You can import the contents of a delivery unit into the SAP HANA Repository, for example, from a
compressed Zip archive, which you upload from a client file system.

Related Information

Maintain the Delivery-Unit Vendor ID [page 64]


Create a Delivery Unit [page 65]
Export a Delivery Unit [page 809]
Import a Delivery Unit [page 811]

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 63
4.2.1 Maintain the Delivery-Unit Vendor ID

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:

● You have access to an SAP HANA system.


● You have been assigned the privileges granted by a role based on the SAP HANA XS
[Link]::Administrator user role template.

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

1. Start the SAP HANA Application Lifecycle Management.


The SAP HANA Application Lifecycle Management is available on the SAP HANA XS Web server at the
following URL: [Link]

 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.

2. Choose the SETTINGS tab.


3. Maintain details of the vendor ID.
In the SETTINGS tab, perform the following steps:
a. Choose Change Vendor.
b. In the Set Vendor dialog, enter the name of the new vendor, for example, [Link].
c. Choose OK to save the changes.
The new vendor ID appears in the Vendor box.

 Note

The vendor ID is required to create a delivery unit.

SAP HANA Developer Guide


64 PUBLIC Setting Up Your Application
Related Information

SAP HANA Application Lifecycle Management [page 778]

4.2.2 Create a Delivery Unit

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:

● You have access to an SAP HANA system.


● You have the privileges granted by a role based on the SAP HANA
[Link]::Administrator user role template.
● The vendor ID is defined for the DU; the vendor ID defines the repository namespace in which the new DU
resides.

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

1. Open SAP HANA Application Lifecycle Management.


SAP HANA Application Lifecycle Management is available on the SAP HANA XS Web server at the following
URL: [Link]
2. Choose the PRODUCTS tab.
3. Choose the Delivery Units tab.
4. Choose Create.
The New Delivery Unit dialog box appears.
5. Enter details for the new DU.
When entering details, note the following points:

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 65
○ Name
The field is mandatory and you must follow strict naming conventions, for example, use capital letters.
○ Vendor
This field is mandatory. However, you cannot enter a vendor here; the box is populated by the value you
enter when defining the vendor in the SETTINGS tab.
○ Version
Version numbers must take the form “#.#.#”, for example, 1.0.5, where:
○ 1 = the DU version number
○ 0 = the support package version (if required)
○ 5 = the patch version (if required)

 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

You have created a delivery unit.

Related Information

SAP HANA Application Lifecycle Management [page 778]


SAP HANA Change Recording [page 816]
Enable SAP HANA Change Recording [page 817]

[Link] SAP HANA Delivery Unit Naming Conventions

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 (_).

SAP HANA Developer Guide


66 PUBLIC Setting Up Your Application
● The name must start with a letter.
● The maximum length of a delivery-unit name must not exceed 30 characters

 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).

4.3 Using SAP HANA Projects

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

1. Create a development workspace.


The workspace is the link between the SAP HANA repository and your local filesystem, where you work on
project-related objects.
2. Create a project.
Create a new project for a particular application or package; you can use the project to collect in a
convenient place all your application-related artifacts.
3. Share a project.
Sharing a project enables you to ensure that changes you make to project-related files are visible to other
team members and applications. Shared projects are available for import by other members of the
application-development team.

 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.

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 67
4. Import a project.
Import a project (and its associated artifacts) that has been shared by another member of the application-
development team.

Related Information

Maintain a Repository Workspace [page 68]


Create a Project for SAP HANA XS [page 70]
Share an SAP HANA XS Project [page 73]
Import an SAP HANA XS Project [page 74]

4.3.1 Maintain a Repository Workspace

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

1. Open the SAP HANA studio.


2. Open the SAP HANA Development perspective.
3. Choose the Repositories view.
4. Choose Create Workspace…
The Create Workspace… button is located in the top right-hand corner of the Repositories view.
5. Specify the workspace details. In the Create New Repository Workspace dialog, enter the following
information and choose Finish:
a. Specify the SAP HANA system, for which you want to create a new workspace.

SAP HANA Developer Guide


68 PUBLIC Setting Up Your Application
b. Enter a workspace name, for example the name of the SAP HANA system where the repository is
located. To avoid the potential for confusion, it is recommended to associate one workspace with one
repository.
c. Specify where the workspace root directory should be located on your local file system, for example:
C:\users\username\workspaces
The new workspace is displayed in the Repositories view.

 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.

The Repositories view displays the status of a workspace as follows:

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

6. Remove a repository workspace.


If it is necessary to remove a workspace, you can choose between multiple deletion options; the option you
choose determines what is removed, from where (local file system or remote repository), and what, if
anything, is retained.
a. Open the SAP HANA Development perspective.
b. Choose the Repositories view and expand the repository node containing the workspace you want to
remove.
c. Right-click the workspace you want to remove.
d. Choose the workspace-deletion mode.
The following modes apply when you delete a workspace in SAP HANA studio:

Workspace Deletion Modes


Workspace Deletion Mode Description

Delete Remove workspace; delete all workspace-related local


files; delete related changes to remote (repository)
data.

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.

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 69
[Link] SAP HANA 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:

● Yellow database icon


An inactive workspace exists in the SAP HANA repository
● Yellow database icon with a blue check mark
An inactive workspace has been imported to your local file system (and the contents checked out from the
SAP HANA repository)

4.3.2 Create a Project for SAP HANA XS

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

1. Open the SAP HANA studio.


2. Open the SAP HANA Development perspective.

SAP HANA Developer Guide


70 PUBLIC Setting Up Your Application
3. Choose the Project Explorer view.

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.

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 71
[Link] SAP HANA Studio Projects

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:

● Checkout folders and files from the repository


● Commit changes to the repository
● Activate the committed changes
● Revert inactive changes to the previously saved version

 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

Always unshare a project before deleting it.

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.

SAP HANA Developer Guide


72 PUBLIC Setting Up Your Application
4.3.3 Share an SAP HANA XS 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

1. Open the SAP HANA studio


2. Open the SAP HANA Development perspective.
3. Open the Project Explorer view.
4. Share the project.

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

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 73
projects for a selected package, for example, if you are creating a root project in your root application
package.

8. Click Finish to complete the project-sharing procedure.


9. Add new files as required
At this point you can start adding project-specific files to the shared project. These artifacts can then be
committed to the repository, where they reside as inactive objects until they are activated, for example,
using the Team Activate option in the context-sensitive menus available in the Project Explorer view.

 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

Import an SAP HANA XS Project [page 74]

4.3.4 Import an SAP HANA XS Project

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.

SAP HANA Developer Guide


74 PUBLIC Setting Up Your Application
Procedure

1. Open the SAP HANA studio


2. Open the SAP HANA Development perspective.
3. Choose the Repositories view.
4. Right-click the package where the project you want to import is located and choose Checkout and Import
Projects... in the popup menu.
Projects can be assigned to a package at any level of the package hierarchy. If you know where the project
is located, browse to the package first before choosing the Checkout and Import Projects... option. This
reduces the amount of files to checkout and download to your local file system.

 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.

4.4 Maintaining Repository Packages

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

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 75
properties (for example, privileges, component, the package maintainer, and so on) you must use the
Modeling perspective in the SAP HANA studio.

As part of the process of maintaining your application packages, you typically perform the following tasks:

Procedure

1. Define the package hierarchy


The package hierarchy is essential for ease of maintenance as well as the configuration of access to
packages and the privileges that are required to perform actions on the packages.
2. Define package privileges
You can set package authorizations for a specific user or for a role. Authorizations that are assigned to a
repository package are implicitly assigned to all sub-packages, too.
3. Create a package
Packages are necessary to group logically distinct artifacts together in one object location that is easy to
transport.

Related Information

Creating a Package [page 84]


Defining the Package Hierarchy [page 76]
Defining Package Privileges [page 81]

4.4.1 Define the Repository Package Hierarchy

Packages belonging to an application-development delivery unit (DU) should be organized in a clear


hierarchical structure under a single root package representing the vendor, for example, [Link].

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).

SAP HANA Developer Guide


76 PUBLIC Setting Up Your Application
The following simple example shows a package structure containing tutorials for the use of a new application:

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

1. Create a new root package.


Open the SAP HANA Development perspective, choose the Systems view, and perform the following steps:
a. 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.
b. Choose New > Package .
2. Maintain the package details.
In the Create Package dialog, perform the following steps:
a. Enter the name of the package (mandatory).
Guidelines and conventions apply to package names.
b. Enter a package description (optional).
c. Specify the delivery unit that the package is assigned to.
You can add additional packages to a delivery unit at a later point in time, too.
d. Specify a language for the package content.
e. Assign responsibility of the package to a specific user (optional).
By default, the responsible user for a new package is the database user connected to the SAP HANA
repository in the current SAP HANA studio session.
f. Maintain translation details.

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 77
If you plan to have the content translated, you need to maintain the translation details; this is covered
in another topic.
g. Choose OK to save the changes and create the new package.
3. Create a new subpackage.
In the Systems view of the SAP HANA Development perspective, perform the following steps:
a. Right-click the package to which you want to add a new subpackage.
b. In the pop-up menu, choose New > Package...
4. Maintain the subpackage details.
In the Create Package dialog, perform the following steps:
a. Enter the name of the subpackage (mandatory).
Guidelines and conventions apply to package names.
b. Enter a description for the new subpackage (optional).
c. Specify the delivery unit that the subpackage is assigned to.
You can add additional packages to a delivery unit at a later point in time, too.
d. Specify a language for the subpackage content.
e. Assign responsibility of the subpackage to a specific user (optional).
By default, the responsible user for a new package is the database user connected to the SAP HANA
repository in the current SAP HANA studio session.
f. Maintain translation details.
If you plan to have the content translated, you need to maintain the translation details; this is covered
in another topic.
g. Choose OK to save the changes and create the new subpackage.

Related Information

SAP HANA Delivery Unit Naming Conventions [page 66]

[Link] Repository Package Hierarchy

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.

SAP HANA Developer Guide


78 PUBLIC Setting Up Your Application
 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).

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.

[Link] SAP HANA Repository Packages and Namespaces

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.

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 79
Before you start the package development process, consider the following important points:

● 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.

Package Naming Conventions

The following rules apply to package names:

● 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]

SAP HANA Developer Guide


80 PUBLIC Setting Up Your Application
4.4.2 Assign Repository Package Privileges

In the SAP HANA repository, you can set package authorizations for a specific user or for a role.

Prerequisites

The following prerequisites are assumed for assigning package privileges:

● Administrator access to the SAP HANA repository


● Permission to modify user privileges (for example, to grant privileges to other SAP HANA users)

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

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 81
Related Information

Package Privilege Options [page 82]


Package Privileges [page 746]

[Link] Package Privilege Options

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.

Privileges for Native Repository Packages

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:

Package Privilege Description

[Link] Read access to the selected package and design-time ob­


jects (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

REPO.ACTIVATE_NATIVE_OBJECTS Authorization to activate/reactivate design-time objects in


packages originating in the system the user is working in

REPO.MAINTAIN_NATIVE_PACKAGES Authorization to update or delete native packages, or create


sub-packages of packages originating in the system in which
the user is working

SAP HANA Developer Guide


82 PUBLIC Setting Up Your Application
Privileges for Imported Repository Packages

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.

Package Privilege Description

[Link] Read access to the selected package and design-time ob­


jects (both native and imported)

REPO.EDIT_IMPORTED_OBJECTS Authorization to modify design-time objects in packages


originating in a system other than the one in which the user
is currently working

REPO.ACTIVATE_IMPORTED_OBJECTS Authorization to activate (or reactivate) design-time objects


in packages originating in a system other than the one in
which the user is currently working

REPO.MAINTAIN_IMPORTED_PACKAGES Authorization to update or delete packages, or create sub-


packages of packages, which originated in a system other
than the one in which the user is currently working

Related Information

Package Privileges [page 746]

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 83
4.4.3 Create a Repository Package

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 Developer Guide


84 PUBLIC Setting Up Your Application
[Link] Repository Package Types

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.

The following packages are delivered by default with the repository:

● 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.

4.4.4 Delete a Repository Package

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.

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 85
Context

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

System Privileges (Reference)

4.5 Creating the Application Descriptors

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).

SAP HANA Developer Guide


86 PUBLIC Setting Up Your Application
Context

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

1. Create an application-descriptor file.


The package that contains the application descriptor file becomes the root path of the resources exposed
to client requests by the application you develop.
2. Create an application-access file.
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. You can use keywords in
the application-access file to set authentication rules, define package-privilege levels (for example,
EXECUTE or ADMIN, specify the connection security level (for example, SSL/HTTPS), and allow (or
prevent) the creation of entity tags (Etags). You can also define rewrite rules for URLs exposed by an
application, for example, to hide internal details of URL paths from external users, clients, and search
engines.
3. Create an application-privileges file. (Optional)
The application-privileges file enables you to define the authorization privileges required for access to an
SAP HANA XS application, for example, to start the application (EXECUTE) or to perform administrative
actions on an application (ADMIN). The privileges defined here are activated for a particular application in
the application-access file. These privileges can be checked by an application at runtime. Privileges defined
apply to the package where the privileges file is located as well as any packages further down the package
hierarchy unless an additional privileges file is present, for example, in a subpackage.

Related Information

Create an application descriptor [page 88]


Create an application-access file [page 90]
Create an application-privileges file [page 106]

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 87
4.5.1 Create an Application Descriptor File

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

● A repository workspace with a shared project


● A root package for your application, for example, MyAppPackage

 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

For backward compatibility, content is allowed in [Link] file but ignored.

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.

3. In the context-sensitive popup menu, choose New Other... .

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.

SAP HANA Developer Guide


88 PUBLIC Setting Up Your Application
7. Choose Finish.
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 .xsapp automatically.

 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.

8. Save and activate your changes and additions.


a. In the SAP HANA Development perspective, open the Project Explorer view and right-click the new
(.xsapp) package.
b. In the context-sensitive popup menu, choose Team Activate .

[Link] The SAP HANA XS Application Descriptor

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

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 89
File descriptors can give details about the internal coding of the application, and files that contain the
names of developers are useful; they can be used by an attacker in combination with social-engineering
techniques.

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 [page 93]

4.5.2 Enable Access to SAP HANA XS Application Packages

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

● A repository workspace with a shared project


● A root package for your application, for example, MyAppPackage

 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.

● An application descriptor file (.xsapp) for the selected application

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.

SAP HANA Developer Guide


90 PUBLIC Setting Up Your Application
 Note

The application-access file does not have a name before the dot (.); it only has the suffix .xsaccess.

To create the application access file, perform the following steps:

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.

3. Define the application authentication method.

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 91
To ensure that form-based logon works when you enable it using the SAP HANA XS Administration Tool, the
authentication keyword is required in the .xsaccess file, too, and must be set to the value "form", as
illustrated in the following example.

{
"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.

4. Specify the application privileges if required. (Optional)


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. The authorization keyword requires a corresponding
entry in the .xsprivileges file, for example, execute for basic privileges or admin for administrative
privileges on the specified package.

{
"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.

6. Activate the .xsaccess file to the repository.

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

Create an Application Descriptor File [page 88]


Application-Access File Keyword Options [page 95]
The Application-Privileges File

SAP HANA Developer Guide


92 PUBLIC Setting Up Your Application
[Link] The Application-Access File

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"
},

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 93
"authorization": // Privileges for application access
[
"[Link]::Execute",
"[Link]::Admin"
],
"rewrite_rules" : // URL rewriting rules
[ {
"source": "/entries/(\\d+)/(\\d+)/(\\d+)/",
"target": "/logic/[Link]?year=$1&month=$2&day=$3"
} ],
"mime_mapping" : // Map file-suffix to MIME type
[ {
"extension":"jpg", "mimetype":"image/jpeg"
} ],
"force_ssl" : true, // Accept only HTTPS requests
"enable_etags" : true, // Allow generation of etags
"prevent_xsrf" : true, // Prevent cross-site request forgery
"anonymous_connection" : "[Link]::AnonConn", //.xssqlcc object
"default_connection" : "[Link]::sqlcc", //.xssqlcc object
"cors" : // Permit cross-origin browser requests
{
"enabled" : false
},
"default_file" : "[Link]", // Override default access setting
"cache_control" : "no-cache, no-store", // Manage static Web-content cache
"headers": // Enable X-Frame-Options HTTP header field
{
"enabled": true,
"customHeaders":
[ {
"name":"X-Frame-Options","value":"SAMEORIGIN"
} ]
}
}

Related Information

Application-Access File Keyword Options [page 95]


Set up Application Security [page 111]

SAP HANA Developer Guide


94 PUBLIC Setting Up Your Application
[Link] Application-Access File Keyword Options

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>"} ]
}
}

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 95
exposed

{
"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

It is not recommended to enable anonymous access.

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).

SAP HANA Developer Guide


96 PUBLIC Setting Up Your Application
default_connection

{
"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.

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 97
 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.

● 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.

SAP HANA Developer Guide


98 PUBLIC Setting Up Your Application
Authorization settings are inherited down the package hierarchy from a package to a subpackage. However,
you can specify different authorization levels for different subpackages; this new setting is then inherited by
any subpackages further down the hierarchy. To disable authorization for a subpackage (for example, to
prevent inheritance of authorizations from the parent package), you can create a (sub)package-
specific .xsaccess file with the authorization keyword explicitly set to null, as illustrated in the following
example.

{
"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:

● From a client perspective:


If an application is handling sensitive data, it is bad practice to cache the data in the local browser since
this could lead to unintended disclosure of information.
● From a server perspective:
Allowing an application to cache data can open up the application to attack. For example, if attackers build
a malicious page and host it on a proxy server between your server and the requesting client, it would be
possible to steal data from the client or prevent access to the application altogether. Since the risk of such
an attack is small, you might want to consider allowing caching, as long as it does not adversely affect
performance.

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 99
cors

{
"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:

● The server does not respond to any CORS preflight requests


● The server does not add CORS response headers to any CORS requests
● The server refuses to execute the resource specified in the request

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>}}

Default Settings for CORS Options


CORS Option Description

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.

SAP HANA Developer Guide


100 PUBLIC Setting Up Your Application
Alternatively, you can isolate the part of the application where CORS must be allowed, for example, in a specific
subpackage. By adding a dedicated .xsaccess file to this CORS-related subpackage, you can set the cors
option in the dedicated .xsaccess file to true.

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

It is not recommended to rely on rewrite rules to make an application secure.

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" :
[{

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 101
"source": "/go/(\\d+)/",
"target": "/logic/[Link]?filename=$1"
}],
}

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.

SAP HANA Developer Guide


102 PUBLIC Setting Up Your Application
Enabling theforce_ssl option ensures that your application is reachable only by means of an HTTPS
connection. If your application must support standard HTTP (without SSL), make sure that no sensitive data is
being sent either to or from the application. Disabling the force_ssl option allows attackers to read whatever
is sent over the network. Although it is possible to use message-based encryption for sensitive data while
allowing HTTP, it is much better to work with HTTPS.

 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

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 103
determines if an application responds to the client's request to display content; if no valid security token is
available, a 403 Forbidden message is displayed. A security token is considered to be valid if it matches the
token that SAP HANA XS generates in the back end for the corresponding session.

 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

Runtime settings override any settings specified in the design-time configuration.

<VALUE> can be one of the following:

● 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.

SAP HANA Developer Guide


104 PUBLIC Setting Up Your Application
Related Information

Server-Side JavaScript Security Considerations [page 553]


The SQL Connection Configuration File [page 603]

[Link] Application-Access URL Rewrite Rules

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"
}

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 105
]
}

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 rewriting of the following URLs would be allowed:

/sap/apptest/users/123/ ==> /sap/appTest/logic/[Link]?id=123


/sap/apptest/posts/2011/10/12/ ==> /sap/appTest/logic/[Link]?
year=2011&month=10&day=12

4.5.3 Create an SAP HANA XS Application Privileges File

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

● A repository workspace with a shared project


● A root package for your application, for example, MyAppPackage

 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.

● An application descriptor file (.xsapp) for the selected application


● An application access file (.xsaccess) for the selected application

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.

SAP HANA Developer Guide


106 PUBLIC Setting Up Your Application
Procedure

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.

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 107
"privileges" :
[
{ "name" : "Execute", "description" : "Basic execution
privilege" },
{ "name" : "Admin", "description" : "Administration
privilege" }
]
}

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"
]
}

4. Save and activate your changes and additions.


The activation of the application privileges creates the corresponding objects, which you can use to assign
the specified privileges to an author.
5. Assign the application privilege to the users who require it.
After activation of the .xsprivileges object, the only user who by default has the application privileges
specified in the .xsprivileges file is the _SYS_REPO user. To grant the specified privilege to (or revoke
them from) other users, use the GRANT_APPLICATION_PRIVILEGE or REVOKE_APPLICATION_PRIVILEGE
procedure in the _SYS_REPO schema.

SAP HANA Developer Guide


108 PUBLIC Setting Up Your Application
To grant the execute application privilege to a user, run the following command in the SAP HANA studio's
SQL Console:

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

Create an Application Descriptor File [page 88]


Enable Access to SAP HANA XS Application Packages [page 90]

[Link] The Application-Privileges File

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.

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 109
In the following above, if the application-privileges file is located in the application package [Link],
then the following privileges are created:

● [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>')

4.6 Maintaining Application Security

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.

SAP HANA Developer Guide


110 PUBLIC Setting Up Your Application
● Authentication
Select an authentication type to use when checking user credentials before authorizing access to an
application, for example: form-based authentication (with user name and password), SAML (SSO with
Security Assertion Markup Language), SAP logon tickets...

Related Information

Set up Application Security [page 111]


Application Security [page 113]
Application Authentication [page 116]

4.6.1 Set up Application Security

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:

● You have access to an SAP HANA system


● You have the privileges granted in the following SAP HANA XS user roles:
○ [Link]::RuntimeConfAdministrator

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

1. Start the SAP HANA XS Administration Tool.


The tool is available on the SAP HANA XS Web server at the following URL: [Link]
80<SAPHANAinstance>/sap/hana/xs/admin/.

 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

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 111
access to all necessary features, the user who logs on should have the SAP HANA XS role
[Link]::RuntimeConfAdministrator.

2. Select the security options your applications use.


You can setup the following application-related security options:

 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

SAP HANA XS Application Security [page 113]


Set up Application Authentication [page 113]
SAP HANA XS Application Authentication [page 116]
The Application-Access File [page 93]

SAP HANA Developer Guide


112 PUBLIC Setting Up Your Application
[Link] SAP HANA XS Application Security

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:

● Public (no authentication required)


Use the Public option to specify if applications require user authentication to start. 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).

 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

SAP HANA XS Application Authentication [page 116]


The Application-Access File [page 93]

4.6.2 Set up Application Authentication

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:

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 113
● You have access to an SAP HANA system
● You have the privileges granted in the following SAP HANA XS user roles:
○ [Link]::RuntimeConfAdministrator

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

1. Start the SAP HANA XS Administration Tool.


The tool is available on the SAP HANA XS Web server at the following URL: [Link]
80<SAPHANAinstance>/sap/hana/xs/admin/.

 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.

2. Select the security options your applications use.


If you have already set the application security level, you can safely skip this step. You can setup the
following application-related security options:

 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.

SAP HANA Developer Guide


114 PUBLIC Setting Up Your Application
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.

3. Select the authentication method your applications must use.


Authentication settings are automatically inherited by applications further down the application hierarchy.
However, you can override the inherited authentication settings at any application level by modifying the
settings for a particular application. Applications below the application with the modified authentication
settings inherit the new, modified settings.

 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.

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 115
Related Information

Set up Application Authentication [page 111]


SAP HANA XS Application Security [page 113]
SAP HANA XS Application Authentication [page 116]
The Application-Access File [page 93]

[Link] SAP HANA XS Application Authentication

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 Developer Guide


116 PUBLIC Setting Up Your Application
 Note

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:

● For non-interactive logon:


1. X509 authentication
2. SPNego
3. SAP logon ticket
4. Basic authentication

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 117
● For interactive logon:
1. SAML
2. Form-based authentication

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

The Application-Access File [page 93]


Application-Access File Keyword Options [page 95]

4.7 Maintaining HTTP Destinations

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

SAP HANA Developer Guide


118 PUBLIC Setting Up Your Application
specified in a separate configuration file. Like the original HTTP destination that the extension modifies,
the configuration-file extension must have the file extension .xshttpdest and be located in the same
package as the HTTP destination configuration file it extends and the application that uses it.
4. Check the HTTP destination configuration using the SAP HANA XS Administration Tool.
The SAP HANA XS Administration Tool is available on the SAP HANA XS Web server at the following URL:
[Link]

 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 Configuration [page 119]


Extend an HTTP Destination Configuration [page 131]
HTTP Destination Configuration Syntax [page 123]

4.7.1 Tutorial: Create an HTTP Destination

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:

● Create a development workspace in the SAP HANA repository


● Create a project in the workspace
● Share the new project
● Assigned your user the following SAP HANA roles:
○ HTTPDestAdministrator
○ RuntimeConfAdministrator

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 119
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
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.

a. Create a plain-text file called [Link] and open it in a text editor.


b. Enter the following code in the new file [Link].

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;

SAP HANA Developer Guide


120 PUBLIC Setting Up Your Application
c. Save and activate the file.

 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.

3. View the activated HTTP destination.


You can use the SAP HANA XS Administration Tool to check the contents of an HTTP destination
configuration.

 Note

To make changes to the HTTP Destination configuration, you must use a text editor, save the changes
and reactivate the file.

a. Start the SAP HANA XS Administration Tool.


The SAP HANA XS Administration Tool is available on the SAP HANA XS Web server at the following
URL: [Link]

 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.

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 121
Related Information

Tutorial: Extend an HTTP Destination [page 131]


The HTTP Destination Configuration [page 122]
HTTP Destination Configuration Syntax [page 123]

[Link] The HTTP Destination Configuration

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.

SAP HANA Developer Guide


122 PUBLIC Setting Up Your Application
 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

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

HTTP Destination Configuration Syntax [page 123]


Tutorial: Create an HTTP Destination [page 119]

[Link] HTTP Destination Configuration Syntax

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.

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 123
 Note

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.

SAP HANA Developer Guide


124 PUBLIC Setting Up Your Application
description

description = "my short description of the HTTP connection";

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

useSSL = [true | false];

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

sslAuth = [client | anonymous];

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.

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 125
sslHostCheck

sslHostCheck = [true | false];

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

authType = [none | basic | AssertionTicket | SamlAssertion |


SamlAssertionPropagation];

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

The saplogontickettruststore parameter can be set in [indexserver | xsengine].ini authentication


saplogontickettruststore .

SAP HANA Developer Guide


126 PUBLIC Setting Up Your Application
If authType = AssertionTicket is set you also need to set values for the keywords remoteSID and
remoteclient.

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:

● "" (empty string)


A SAML response (including the SAML assertion) is sent to the HTTP destination end point as a POST
parameter.
● /saml/acs/sso
If you provide a URL path, the SAML response (including the SAML Assertion) is sent to the specified
endpoint in an additional Web connection to establish the authentication context (session).When the
outbound communication is being established, there are two connections: first to the specified end point
(for example, /saml/asc/sso) and then to the destination service end point.
● header
The SAML response (including the SAML assertion) is sent in the HTTP header authorization with the
following syntax: Authorization: SAML2.0 &lt;base-64-saml-response&gt;.
● parameter:assertion
The SAML Assertion is sent as a POST parameter. This flavor is needed for JAM integrations.

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.

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 127
samlNameId

samlNameId = ["email", "unspecified"];

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

SAP HANA Developer Guide


128 PUBLIC Setting Up Your Application
keywords to specify the fully qualified name of the host providing the proxy service (and the port number to use
for connections). The name of the proxy host must be wrapped in quotes, as illustrated in the following
example,

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.

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 129
remoteClient

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

SAP HANA Developer Guide


130 PUBLIC Setting Up Your Application
destination extension overwrite any identical settings in the original HTTP destination configuration. The HTTP
destination configuration referenced by the modifies keyword must already exist.

 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

The HTTP Destination Configuration [page 122]


The HTTP Destination Extension [page 134]

4.7.2 Tutorial: Extend an HTTP Destination

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:

● Create a development workspace in the SAP HANA repository


● Create a project in the workspace
● Share the new project
● Assigned your user the following SAP HANA roles:
○ HTTPDestAdministrator
○ RuntimeConfAdministrator

 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

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 131
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 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.

a. Create a plain-text file called [Link] and open it in a text editor.


b. Enter the following code in the new file [Link].

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;

c. Save and activate the file.

 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.

SAP HANA Developer Guide


132 PUBLIC Setting Up Your Application
3. View the activated HTTP destination.
You can use the SAP HANA XS Administration Tool to check the contents of an HTTP destination
configuration.

 Note

To make changes to the HTTP Destination configuration, you must use a text editor, save the changes
and reactivate the file.

a. Open a Web browser.


b. Start the SAP HANA XS Administration Tool.
The SAP HANA XS Administration Tool tool is available on the SAP HANA XS Web server at the
following URL: [Link]

 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.

a. Create a plain-text file called [Link] and open it in a text editor.


b. Enter the following code in the new file [Link].

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.

c. Save and activate the file.


5. View and check the details of the activated HTTP destination extension [Link].
You can use the SAP HANA XS Administration Tool to check the contents of an HTTP destination
configuration or an extension to the configuration.

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 133
 Note

To make changes to the HTTP Destination configuration (or any extension), you must use a text editor,
save the changes and reactivate the file.

a. Open a Web browser.


b. Start the SAP HANA XS Administration Tool.
The SAP HANA XS Administration Tool tool is available on the SAP HANA XS Web server at the
following URL: [Link]

 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

Tutorial: Create an HTTP Destination [page 119]


The HTTP Destination Configuration [page 122]
HTTP Destination Configuration Syntax [page 123]

[Link] The HTTP Destination Extension

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.

SAP HANA Developer Guide


134 PUBLIC Setting Up Your Application
 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.

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

4.7.3 Tutorial: Create an OAuth Configuration Package

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:

● A development workspace in the SAP HANA repository


● A shared project in the workspace
● Access to SAP HANA development tools, for example:
○ SAP HANA studio
○ SAP HANA Web-based Workbench

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 135
● An HTTP destination configuration (.xshttpdest)
● Your SAP HANA database user has the permissions granted by the following roles:
○ RuntimeConfAdministrator
○ HTTPDestAdministrator
○ oAuthAdmin

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.

An OAuth configuration requires the following dependent configuration files:

● OAuth application configuration (<filename>.xsoauthappconfig)


Describes the configuration of the OAuth application parameters including the name and package location
of the associated client configuration and any mandatory or optional scopes.
● OAuth client configuration (<filename>.xsoauthclientconfig)
Describes the configuration of the OAuth client including: the client ID, the client authentication type, and
the name and package location of the associated client flavor.
● OAuth client flavor configuration (<filename>.xsoauthclientflavor)
Describes the OAuth client flavor setup used by the XS OAuth client configuration, including: the protocol
steps and the parameters to be set. Note that, normally, you do not need to change the OAuth client flavor
configuration.

 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

1. Create an OAuth application configuration.

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:

SAP HANA Developer Guide


136 PUBLIC Setting Up Your Application
"clientConfig" :
"[Link]:abap_ac",
"mandatoryScopes" : ["OAUTH2_TEST_SCOPE1", "OAUTH2_TEST_SCOPE2"],
"description" : "ABAP Testapplication for OAuth"
}

 Note

In this example, the OAuth client configuration is located in the package


[Link]; you can change the path to suit
your own requirements.

2. Create an OAuth client configuration (optional).

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"
}

3. Create the OAuth client flavor (optional).


The OAuth client flavor file is a design-time artifact that provides details of the OAuth protocol for a client
application which 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.

 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.

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 137
 Note

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" },
] }

4. Activate all the XS OAuth configuration files.


Activating the configuration files creates the corresponding catalog objects.
5. Add the OAuth configuration to the runtime configuration of the HTTP destination configuration that
requires it.
The SAP HANA XS Administration Tool is available on the SAP HANA XS Web server at the following URL:
[Link]

 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

a. Start the XS Artifact Administration tool.


b. In the Application Objects list, locate and choose the HTTP destination configuration that you want to
modify.
c. Choose the OAuth Details tab.
d. Choose Edit Browse OAuth App Configs
e. Select an OAuth application configuration from the list displayed.
The name of the application configuration you choose and the absolute path to the package where it is
located are displayed in the appropriate fields, for example.
○ OAuth App Config Package: [Link]
○ OAuth App Config Name: abapTest

 Note

The values displayed here must also be present in the HTTP destination configuration to which the
OAuth configuration applies.

SAP HANA Developer Guide


138 PUBLIC Setting Up Your Application
For example, the HTTP destination corresponding to the OAuth configuration you are setting up in this
task must also contain entries that describe the name and package location of the OAuth application
configuration to use.

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

Tutorial: Create an HTTP Destination [page 119]


OAuth Application Configuration Syntax [page 139]
OAuth Client Configuration Syntax [page 141]
OAuth Client Flavor Syntax [page 146]

[Link] OAuth Application Configuration Syntax

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"
}

An OAuth configuration requires the following dependent configuration files:

● OAuth application configuration (.xsoauthappconfig)


● OAuth client configuration (.xsoauthclientconfig)
● OAuth client flavor configuration (.xsoauthclientflavor)

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 139
clientConfig

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.

"description":"ABAP test application for OAuth",

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

SAP HANA Developer Guide


140 PUBLIC Setting Up Your Application
associated SAP HANA XS OAuth application configuration artifact (xsoauthappconfig), using the format
<[Link]>:<ObjectName>.

"modifies":"[Link]:[Link]",

Related Information

OAuth Client Configuration Syntax [page 141]


OAuth Client Flavor Syntax [page 146]
Tutorial: Create an OAuth Configuration Package [page 135]

[Link] OAuth Client Configuration Syntax

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]

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 141
clientFlavor

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.

"clientID" : "<The OAuth ClientId you registered at ABAP>",

 Note

It is mandatory to define the clientID.

clientAuthType

Use the clientAuthType keyword to define a number that specifies the client authentication type, for
example, “cert” or “basic”.

"clientAuthType" : "basic",

 Note

It is mandatory to define the clientAuthType.

The following values are permitted:

● basic (user and password)


● cert (authentication by client certificate)

SAP HANA Developer Guide


142 PUBLIC Setting Up Your Application
authorizationEndpointURL

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

It is mandatory to define the authorizationEndpointURL.

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

It is mandatory to define the tokenEndpointURL.

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

It is mandatory to define a value for the revocationEndpointURL.

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",

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 143
 Note

It is mandatory to define a value for flow.

The following values are permitted:

● 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

If "flow" : "authCode", it is mandatory to define a value for the redirectURL.

SAP HANA Developer Guide


144 PUBLIC Setting Up Your Application
scopeReq

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",

The following values are permitted:

● maxScopes
● iterativeScopes

 Note

Currently only maxScopes is implemented.

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",

The following values are permitted:

● true (shared)
● false (not shared)

 Note

Currently only true is implemented.

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",

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 145
Related Information

OAuth Client Flavor Syntax [page 146]


OAuth Application Configuration Syntax [page 139]
Tutorial: Create an OAuth Configuration Package [page 135]

[Link] OAuth Client Flavor Syntax

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" },

SAP HANA Developer Guide


146 PUBLIC Setting Up Your Application
{ "flavorStep":"4Ref", "paramLocation":"head", "paramName":"Authorization",
"paramValue":"Basic Authentication", "valueType":"sec",
"paramMandatory":"true" },
{ "flavorStep":"4Ref", "paramLocation":"head", "paramName":"Content-Type",
"paramValue":"application/x-www-form-urlencoded", "valueType":"litr",
"paramMandatory":"true" },
{ "flavorStep":"4Ref", "paramLocation":"para", "paramName":"grant_type",
"paramValue":"refresh_token", "valueType":"litr",
"paramMandatory":"true" },
{ "flavorStep":"4Ref", "paramLocation":"para", "paramName":"refresh_token",
"paramValue":"refresh_token", "valueType":"sec",
"paramMandatory":"true" },
{ "flavorStep":"5Rev", "paramLocation":"para", "paramName":"token",
"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

The example OAuth client flavors are located in the package


[Link].

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",

The following values are permitted:

● IAut
● 2Gra
● 3Prc
● 4Ref

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 147
● 5Rev
● saml

paramLocation

Use the paramLocation keyword to specify the location of the parameter defined, as shown in the following
example:

"paramLocation":"uri",

The following values are permitted:

● 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",

SAP HANA Developer Guide


148 PUBLIC Setting Up Your Application
The following values are permitted:

● 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

Use the paramMandatory keyword to specify if a parameter is required or not.

"paramMandatory":"true",

The following values are permitted:

● true
Required
● false
Not Required

Related Information

OAuth Client Configuration Syntax [page 141]


OAuth Application Configuration Syntax [page 139]
Tutorial: Create an OAuth Configuration Package [page 135]

4.8 Maintaining Application Artifacts

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-

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 149
in reads the repository artifact selected for activation (for example, a table definition, a complete CDS
document, or server-side JavaScript code), interprets the object description in the file, and creates the
appropriate runtime object in the designated catalog schema.

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

Design-Time Application Artifacts [page 150]


Studio-Based SAP HANA Development Tools [page 153]

4.8.1 Design-Time Application Artifacts

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.

Design-time Application Building Blocks


File Extension Object Description

.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.

.calculationview Calculation view A file containing a design-time definition of an calculation view;


the view can be referenced in an OData service definition.

.hdbdd CDS document A file containing a design-time definition of a CDS-compliant


data-persistence object (for example, an entity or a data type)
using the Data Definition Language (DDL).

.hdbprocedure Procedure Replaces .procedure. A design-time definition of a database


function for performing complex and data-intensive business
logic that cannot be performed with standard SQL.

SAP HANA Developer Guide


150 PUBLIC Setting Up Your Application
File Extension Object Description

.hdbrole Role A file containing a design-time definition of an SAP HANA user


role.

.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.

.hdbschema Schema A design-time definition of a database schema, which organizes


database objects into groups.

.hdbsequence Sequence A design-time definition of a database sequence, which is set of


unique numbers, for example, for use as primary keys for a spe­
cific table.

.hdbstructure Table type A design-time definition of a database table type using


the .hdbtable syntax. Used for defining reusable table types,
for example, for parameters in procedures.

.hdbsynonym Database synonym A design-time definition of a database synonym using


the .hdbsynonym syntax.

.hdbtable Table A design-time definition of a database table using


the .hdbtable syntax.

.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.

.procedure Procedure A design-time definition of a database function for performing


complex and data-intensive business logic that cannot be per­
formed with standard SQL.

.proceduretemplate Procedure template A design-time artifact containing a base script with predefined
placeholders for objects such as tables, views and columns.

.project Project An Eclipse project for developing your application or part of an


application. The .project file is a design-time artifact that is
stored in the SAP HANA repository.

.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.

.xsapp Application Descriptor An application-specific file in a repository package that defines


the root folder of a native SAP HANA application. All files in that
package (and any subpackages) are available to be called via
URL.

.xsappsite Application Site A file that defines an application site

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 151
File Extension Object Description

.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.

Additional Application Building Blocks


Object Description File Extension

Package A container in the repository for development objects. Packages are represented by
folders.

SAP HANA Developer Guide


152 PUBLIC Setting Up Your Application
Object Description File Extension

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.

4.8.2 Studio-Based SAP HANA Development Tools

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.

Project Explorer View

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.

SAP HANA XS Development Options


Menu Group Menu Option Description

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.

Activate Use the corresponding design-time definition in the Repository to


generate a catalog object for the currently selected inactive arti­
fact.

Activate All... Generate a catalog object based on the corresponding design-time


definition in the Repository for all currently inactive artifacts in a
particular workspace; 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 Simulate an activate operation (including a syntax check)

Regenerate Force generation of a run-time catalog object without starting the


corresponding design-time activation process

Remove from Client Undo a check-out operation without the risk of deleting content in
the SAP HANA Repository

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 153
Menu Group Menu Option Description

Show in Display details of the selected repository artifact in the


Repositories, Synchronize, or History view.

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.

Refresh Refresh Triggers a recursive checkout of Repository content, synchronizes


differences between the Repository workspace and the local file
system by fetching changes from the server

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.

Additional SAP HANA XS Development Options


Tool Description

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.

SAP HANA Developer Guide


154 PUBLIC Setting Up Your Application
Tool Description

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 Simulate an activate operation (including a syntax check)

Check out Copy package content from the Repository to the local workspace folder. Synchronize the
repository with the local workspace (refresh)

SAP HANA Developer Guide


Setting Up Your Application PUBLIC 155
Tool/Feature Description

Create Repository Work­ Start the repository workspace wizard.


space

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.

Open Open the selected file in the appropriate editor.

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

SAP HANA Developer Guide


156 PUBLIC Setting Up Your Application
5 Setting up the Data Persistence Model in
SAP HANA

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 [page 157]


● SAP HANA XS Advanced Model [page 158]

SAP HANA XS Classic Model

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:

XS Classic Data Persistence Artifacts by Language Syntax and File Suffix


XS Classic Artifact Type CDS HDBTable

Schema .hdbschema * .hdbschema

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 157
XS Classic Artifact Type CDS HDBTable

Synonym .hdbsynonym* .hdbsynonym

Table .hdbdd .hdbtable

Table Type .hdbdd .hdbstructure

View .hdbdd .hdbview

Association .hdbdd -

Sequence .hdbsequence* .hdbsequence

Structured Types .hdbdd -

Data import .hdbti .hdbti

 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.

SAP HANA XS Advanced Model

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.

SAP HANA Developer Guide


158 PUBLIC Setting up the Data Persistence Model in SAP HANA
In XS advanced, application development takes place in the context of a project. The project brings together
individual applications in a so-called Multi-Target Application (MTA), which includes a module in which you
define and store the database objects required by your data model.

1. Define the data model.


Set up the folder structure for the design-time representations of your database objects; this could include
CDS documents that define tables, data types, views, and so on. But it could also include other database
artifacts, too, for example: your stored procedures, synonyms, sequences, scalar (or table) functions, and
any other artifacts your application requires.

 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.

2. Set up the SAP HANA HDI deployment infrastructure.


This includes the following components:
○ The HDI configuration
Map the design-time database artifact type (determined by the file extension, for
example, .hdbprocedure, or .hdbcds in XS advanced) to the corresponding HDI build plug-in in the
HDI configuration file (.hdiconfig).
○ Run-time name space configuration (optional)
Define rules that determine how the run-time name space of the deployed database object is formed.
For example, you can specify a base prefix for the run-time name space and, if desired, specify if the
name of the folder containing the design-time artifact is reflected in the run-time name space that the
deployed object uses.
Alternatively, you can specify the use of freestyle names, for example, names that do not adhere to any
name-space rules.
3. Deploy the data model.
Use the design-time representations of your database artifacts to generate the corresponding active
objects in the database catalog.
4. Consume the data model.
Reference the deployed database objects from your application, for example, using OData services bound
to UI elements.

Related Information

Creating the Persistence Model in Core Data Services [page 160]


Creating Data Persistence Artifacts with CDS in XS Advanced
CDS Documents in XS Advanced

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 159
5.1 Creating the Persistence Model in Core Data Services

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

Create a CDS Document [page 164]


Create an Entity in CDS [page 189]
Create a User-defined Structured Type in CDS [page 211]
Create an Association in CDS [page 225]
Create a View in CDS [page 240]
CDS Annotations [page 178]

SAP HANA Developer Guide


160 PUBLIC Setting up the Data Persistence Model in SAP HANA
5.1.1 CDS Editors

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.

● CDS Text Editor [page 161]


View and edit DDL source code in a CDS document as text with the syntax elements highlighted for easier
visual scanning.
Right-click a CDS document: Open With Text Editor
● CDS Graphical Editor [page 162]
View a graphical representation of the contents of a CDS source file, with the option to edit the source code
as text with the syntax elements highlighted for easier visual scanning.
Right-click a CDS document: Open With Graphical Editor

CDS Text Editor

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.

The CDS editor provides the following features:

● 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.

The following values are assumed:


○ namespace = <ProjectName>.<ApplDBModuleName>
○ context = <NewCDSFileName>

● 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.

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 161
● Code validity
The CDS text editor provides syntax validation, which checks for parser errors as you type. Semantic errors
are only shown when you build the XS advanced application module to which the CDS artifacts belong; the
errors are shown in the console tab.
● 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).

CDS Graphical Editor

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

Getting Started with the CDS Graphical Editor

[Link] CDS Text Editor

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.

The CDS editor provides the following features:

● Syntax highlights

SAP HANA Developer Guide


162 PUBLIC Setting up the Data Persistence Model in SAP HANA
The CDS DDL editor supports syntax highlighting, for example, for keywords and any assigned values
(@Schema: 'MySchema'). You can customize the colors and fonts used in the Eclipse Preferences
( Window Preferences General Appearance Colors and Fonts CDS DDL ).

 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

Activating a file automatically commits the file first.

● 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.

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 163
5.1.2 Create a CDS Document

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

To complete this task successfully, note the following prerequisites:

● You must have access to an SAP HANA system.


● You must have already created a development workspace and a project.
● You must have shared a project for the CDS artifacts so that the newly created files can be committed to
(and synchronized with) the repository.

SAP HANA Developer Guide


164 PUBLIC Setting up the Data Persistence Model in SAP HANA
● You must have created a schema for the CDS catalog objects created when the CDS document is activated
in the repository, for example, MYSCHEMA
● The owner of the schema must have SELECT privileges in the schema to be able to see the generated
catalog objects.

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

1. Start the SAP HANA studio.


2. Open the SAP HANA Development perspective.
3. Open the Project Explorer view.
4. Create the CDS document.
Browse to the folder in your project workspace where you want to create the new CDS document and
perform the following steps:

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 {

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 165
};

5. Define the details of the CDS artifacts.

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.

a. Add a schema name.


The @Schema annotation defines the name of the schema to use to store the artifacts that are
generated when the CDS document is activated. The schema name must be inserted before the top-
level element in the CDS document; in this example, the context MyModel.

 Note

If the schema you specify does not exist, you cannot activate the new CDS document.

namespace [Link];
@Schema: 'SAP_HANA_CDS'
context MyModel {

};

b. Add structured types, if required.


Use the type keyword to define a type artifact in a CDS document. In this example, you add the user-
defined types and structured types to the top-level entry in the CDS document, the context MyModel.

namespace [Link];
@Schema: 'SAP_HANA_CDS'
context MyModel {
type BusinessKey : String(10);
type SString : String(40);
type <[...]>
<[...]>
};

c. Add a new context, if required.


Contexts enable you to group together related artifacts. A CDS document can only contain one top-
level context, for example, MyModel {};. Any new context must be nested within the top-level entry
in the CDS document, as illustrated in the following example.

namespace [Link];
@Schema: 'SAP_HANA_CDS'
context MyModel {
type BusinessKey : String(10);
type SString : String(40);
type <[...]>
context MasterData {
<[...]>
};
context Sales {
<[...]>
};
context Purchases {
<[...]>
};

SAP HANA Developer Guide


166 PUBLIC Setting up the Data Persistence Model in SAP HANA
};

d. Add new entities.


You can add the entities either to the top-level entry in the CDS document; in this example, the context
MyModel or to any other context, for example, MasterData, Sales, or Purchases. In this example,
the new entities are column-based tables in the MasterData context.

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 {
<[...]>
};
};

6. Save the CDS document.

 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.

7. Activate the changes in the repository.


a. Locate and right-click the new CDS document in the Project Explorer view.
b. In the context-sensitive pop-up menu, choose Team Activate .

 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.

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 167
 Note

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.

a. In the SAP HANA Development perspective, open the Systems view.


b. Navigate to the catalog location where new object has been created, for example:

Catalog Object Location

Entities <SID> Catalog <MYSCHEMA> Tables

Types <SID> Catalog <MYSCHEMA> Procedures Table Types

c. Open a data preview for the new object.


Right-click the new object and choose Open Data Preview in the pop-up menu.

Related Information

CDS Namespaces [page 174]


CDS Naming Conventions [page 173]
CDS Contexts [page 175]
CDS Annotations [page 178]
CDS Comment Types [page 187]

SAP HANA Developer Guide


168 PUBLIC Setting up the Data Persistence Model in SAP HANA
[Link] CDS Documents

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:

● A name space declaration


The name space you define must be the first declaration in the CDS document and match the absolute
package path to the location of the CDS document in the repository. It is possible to enclose parts of the
name space in quotes (“”), for example, to solve the problem of illegal characters in name spaces.

 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.

Catalog Location for CDS-generated Artifacts


CDS Artifact Catalog Location

Entity <SID> Catalog <MYSCHEMA> Tables

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 169
CDS Artifact Catalog Location

View <SID> Catalog <MYSCHEMA> Views

Structured type <SID> Catalog <MYSCHEMA> Procedures Table Types

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

SAP HANA Developer Guide


170 PUBLIC Setting up the Data Persistence Model in SAP HANA
@MyAnnotation : 'foo'
Entity Item {
key SalesOrderId: BusinessKey;
key SalesOrderItem: BusinessKey;
<[...]>
};
};
context Purchases {
<[...]>
};
};

Related Information

Create a CDS Document [page 164]


CDS Namespaces [page 174]
CDS Annotations [page 178]
External Artifacts in CDS [page 171]

[Link] External Artifacts in CDS

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)

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 171
e : ict3; // structured
x : [Link]::ContextA.T1; // error, direct reference not allowed
};
context ContextBI {
type T1 : String(7); // hides the T1 coming from the first using declaration
type T2 : T1; // String(7)
};
};

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].

SAP HANA Developer Guide


172 PUBLIC Setting up the Data Persistence Model in SAP HANA
[Link] CDS Naming Conventions

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:

● CDS source-file name


From SAP HANA 2.0 SPS 01, it is possible to define multiple top-level artifacts (for example, contexts,
entities, etc.) in a single CDS document. For this reason, you can choose any name for the CDS source file;
there is no longer any requirement that the name of the CDS source file must be the same as the name of a
top-level artifact.
● File suffix
The file suffix differs according to SAP HANA XS version:
○ XS classic
.hdbdd, for example, [Link].
○ XS advanced
.hdbcds, for example, [Link].
● Permitted characters
CDS object and package names can include the following characters:
○ Lower or upper case letters (aA-zZ) and the underscore character (_)
○ Digits (0-9)
● Forbidden characters
The following restrictions apply to the characters you can use (and their position) in the name of a CDS
document or a package:
○ You cannot use either the hyphen (-) or the dot (.) in the name of a CDS document.
○ You cannot use a digit (0-9) as the first character of the name of either a CDS document or a package,
for example, [Link] (XS classic) or [Link] (XS advanced).
○ The CDS parser does not recognize either CDS document names or package names that consist
exclusively of digits, for example, [Link] (XS classic) or [Link] (XS
advanced).

 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

Create a CDS Document [page 164]


CDS Documents [page 169]
CDS Namespaces [page 174]

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 173
[Link] CDS Namespaces

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

A CDS document cannot contain more than one namespace declaration.

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.

namespace pack1.pack2; // wrong spelling


namespace "Pack1.pack2"; // incorrect use of quotes
namespace [Link]; // CDS file name not allowed in namespace
namespace [Link]; // package does not exist

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.

SAP HANA Developer Guide


174 PUBLIC Setting up the Data Persistence Model in SAP HANA
● [Link];
The package path [Link]; does not exist in the Repository.

Related Information

Create a CDS Document [page 164]


CDS Documents [page 169]

[Link] CDS Contexts


You can define multiple CDS-compliant entities (tables) in a single file by assigning them to a context.

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”.

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 175
 Note

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;
};

@[Link] : [{ name : 'IndexA', order : #ASC, unique: true,


elementNames : ['field1'] }]

SAP HANA Developer Guide


176 PUBLIC Setting up the Data Persistence Model in SAP HANA
entity MyEntity1 {
key id : Integer;
field1 : MyType3 not null;
field2 : String(24);
field3 : LocalDate;
field4 : type of field3;
field5 : type of MyType1.field2;
field6 : type of [Link].b; // refers to nested context
field7 : [Link]; // more context references
};
};

Name Resolution Rules

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;

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 177
type T2 : String(20);
};
context NameB
{
type NameA : Integer;
type Use : NameA.T1; // invalid: NameA is an Integer
type Use2 : [Link].T2; // ok
};
};

Related Information

CDS User-Defined Data Types [page 214]


Create a CDS Document [page 164]

[Link] CDS Annotations

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;
};
};

SAP HANA Developer Guide


178 PUBLIC Setting up the Data Persistence Model in SAP HANA
Overview

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:

● elementNames : ['<name1>', '<name2>' ]


The names of the fields to use in the index; the elements are specified for the entity definition, for example,
elementNames:['fint', 'futcshrt' ]
● name : '<IndexName>'
The names of the index to be generated for the specified entity, for example, name:'myIndex'

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 179
● 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.
○ 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.

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

SAP HANA Developer Guide


180 PUBLIC Setting up the Data Persistence Model in SAP HANA
exists for the duration of the session, and data from the global temporary table is automatically dropped
when the session is terminated. A global temporary table can be dropped only when the table does not
have any records in it.

 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);
};

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 181
 Note

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 .

SAP HANA Developer Guide


182 PUBLIC Setting up the Data Persistence Model in SAP HANA
@WithStructuredPrivilegeCheck

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

Create a CDS Document [page 164]


User-Defined CDS Annotations [page 183]
CDS Structured Type Definition [page 217]

[Link].1 User-Defined CDS Annotations

In CDS, you can define your own custom annotations.

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);
}

CDS supports the following types of user-defined annotations:

● Scalar annotations
● Structured annotations
● Annotation arrays

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 183
Scalar Annotations

The following example shows how to define a scalar annotation.

annotation MyAnnotation_1 : Integer;


annotation MyAnnotation_2 : String(20);

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

The following example shows how to define a structured annotation.

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

The following example shows how to define an array-like annotation.

annotation MyAnnotation_8 : array of Integer;


annotation MyAnnotation_9 : array of String(12);
annotation MyAnnotation_10 : array of { a: Integer; b: String(10); };

SAP HANA Developer Guide


184 PUBLIC Setting up the Data Persistence Model in SAP HANA
[Link].2 CDS Annotation Usage Examples

Reference examples of the use of user-defined CDS 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:

User-defined CDS Annotations


CDS Annotation Type Description

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

The following examples show how to use a scalar annotation:

@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”

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 185
type MyType8 : Integer;
@MyAnnotation_4 : false
type MyType9 : Integer;

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:

@MyAnnotation_5 : { a : 12, b : 'Jupiter', c : #blue, d : false }


type MyType10 : Integer;
@MyAnnotation_5 : { c : #green } // not all elements need to be filled
type MyType11 : Integer;

The following example shows how to assign the same structured annotation element by element.

 Note

It is not necessary to assign a value for each element.

@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.

@MyAnnotation_5 : { c : #green, c : #green } // error, assign an element once


only
type MyType15 : Integer;
@MyAnnotation_5.c : #green
@MyAnnotation_5.c : #blue // error, assign an element once only
type MyType16 : Integer;

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;

SAP HANA Developer Guide


186 PUBLIC Setting up the Data Persistence Model in SAP HANA
Related Information

CDS Annotations [page 178]


CDS Documents [page 169]
Create a CDS Document [page 164]

[Link] CDS Comment Types

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

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 187
In-line Comments

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:.

element Flocdat: /*comment text*/ LocalDate;

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:.

element Flocdat: LocalDate; // Comment text

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:

// element Flocdat: LocalDate; Additional comment text

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
*/

SAP HANA Developer Guide


188 PUBLIC Setting up the Data Persistence Model in SAP HANA
Related Information

Create a CDS Document [page 164]

5.1.3 Create an Entity in CDS

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

To complete this task successfully, note the following prerequisites:

● You must have access to an SAP HANA system.


● You must have already created a development workspace and a project.
● You must have shared the project so that the newly created files can be committed to (and synchronized
with) the repository.
● You must have created a schema for the CDS catalog objects, for example, MYSCHEMA
● The owner of the schema must have SELECT privileges in the schema to be able to see the generated
catalog objects.

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

1. Start the SAP HANA studio.


2. Open the SAP HANA Development perspective.
3. Open the Project Explorer view.
4. Create the CDS entity-definition file.
Browse to the folder in your project workspace where you want to create the new CDS entity-definition file
and perform the following steps:

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.

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 189
b. Enter the name of the entity-definition file in the File Name box, for example, MyEntity.

 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);
};

6. Save the CDS entity-definition file.

 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.

7. Activate the changes in the repository.


a. Locate and right-click the new CDS entity-definition file in the Project Explorer view.
b. In the context-sensitive pop-up menu, choose Team Activate .

 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.

SAP HANA Developer Guide


190 PUBLIC Setting up the Data Persistence Model in SAP HANA
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 the new entity has been successfully created.


CDS entities are created in the Tables 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 entity.

<SID> Catalog <MYSCHEMA> Tables


c. Open a data preview for the new entity MyEntity.
Right-click the new entity <[Link]>::MyEntity and choose Open Data Preview in the pop-up
menu.

 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

CDS Entities [page 191]


Entity Element Modifiers [page 193]
CDS Entity Syntax Options [page 198]

[Link] CDS Entities


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.

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.

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 191
The following code illustrates an example of a single design-time entity definition using CDS-compliant DDL. In
the example below, you must save the entity definition “MyTable” 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'
@[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:

<SID> Catalog <MYSCHEMA> Tables

Entity Element Definition

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.

SAP HANA Developer Guide


192 PUBLIC Setting up the Data Persistence Model in SAP HANA
● null
Defines if an 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).
● default <literal_value>
Defines the default value for an entity element in the event that no value is provided during an INSERT
operation. The syntax for the literals is defined in the primitive data-type specification.

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

CDS Primitive Data Types [page 222]


Entity Element Modifiers [page 193]
CDS Entity Syntax Options [page 198]

[Link] Entity Element Modifiers

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 {

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 193
key id : Integer;
a : integer;
b : integer;
c : integer generated always as a+b;
};
entity MyEntity2 {
autoId : Integer generated [always|by default] as identity ( start with 10
increment by 2 );
name : String(100);
};

key

key MyKey : Integer;


key MyKey2 : Integer null; // illegal combination
key MyKey3 : Integer default 2;

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

elem3 : String(20) default 'John Doe' null;


elem4 : String default 'Jane Doe' not 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:

SAP HANA Developer Guide


194 PUBLIC Setting up the Data Persistence Model in SAP HANA
○ A default it also defined
○ no null data is already in the table
● Unless the table is empty, bear in mind that when adding a new not null element to an existing entity,
you must declare a default value because there might already be existing rows that do not accept NULL as
a value for the new element.
● null elements with default values are permitted
● You cannot combine the element key with the element modifier null.
● The elements used for a unique index must have the not null property.

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';
};

generated always as <expression>

entity MyEntity1 {
key id : Integer;
a : integer;
b : integer;
c : integer generated always as a+b;

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 195
};

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.

generated [always | by default] as identity

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);

SAP HANA Developer Guide


196 PUBLIC Setting up the Data Persistence Model in SAP HANA
};

 Restriction

CDS does not support the use of reset queries, for example, RESET BY <subquery>.

Column Migration Behavior

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.

● Change to the column type


In case of a column type change, the content is converted into the new type. HANA conversion rules apply.
● Change to the expression clause
The expression is re-evaluated in the following way:
○ “early”
As part of the column change
○ “late”
As part of a query
● Change to a calculated column
A calculated column is transformed into a plain column; the new column is initialized with NULL.

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>

Plain Migrate Drop/add Drop/add Migrate Migrate

Keep content Evaluate on Evaluate on add Keep content Keep content


select

generated by default Migrate Drop/add Drop/add Migrate Migrate


as identity <expr>
Keep content Evaluate on Evaluate on add Keep content Keep content
select

generated always as Migrate Drop/add Drop/add Migrate Migrate


identity <expr>
Keep content Evaluate on Evaluate on add Keep content Keep content
select

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 197
generated by de­
Before column/ Af­ generated always as generated always as fault as identity
ter row Plain As <expr> <expr> identity <expr> <expr>

generated always as Drop/add Drop/add Drop/add Drop/add Migrate


<expr>
NULL Evaluate on Evaluate on add Keep content Keep content
select

as <expr> Drop/add Drop/add Drop/add Drop/add Migrate

NULL Evaluate on Evaluate on add Keep content Keep content


select

Related Information

Create an Entity in CDS [page 189]


Create an Entity in CDS
CDS Entity Syntax Options [page 198]
SAP HANA SQL and System Views Reference (CREATE TABLE)

[Link] CDS Entity Syntax Options

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'] }
]
}

SAP HANA Developer Guide


198 PUBLIC Setting up the Data Persistence Model in SAP HANA
entity MyEntity2 {
key id : Integer;
x : Integer;
y : Integer;
a : Integer;
field7 : Decimal(20,10) = power(ln(x)*sin(y), a);
};
entity MyEntity {
key id : Integer;
a : Integer;
b : Integer;
c : Integer;
s {
m : Integer;
n : Integer;
};
} technical configuration {
row store;
index MyIndex1 on (a, b) asc;
unique index MyIndex2 on (c, s) desc;
};
context MySpatialContext {
entity Address {
key id : Integer;
street_number : Integer;
street_name : String(100);
zip : String(10);
city : String(100);
loc : hana.ST_POINT(4326);
};
}
context MySeriesContext {
entity MySeriesEntity {
key setId : Integer;
t : UTCTimestamp;
value : Decimal(10,4);
series (
series key (setId)
period for series (t)
equidistant increment by interval 0.1 second
equidistant piecewise //increment or piecewise; not both
)
};
}
}

 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:

● Key definition [page 200]


● Index definition [page 200]
● Table type specification [page 201]
● Calculated Fields [page 202]

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 199
● Technical Configuration [page 203]
● Spatial data * [page 205]
● Series Data * [page 206]

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

To define an entity without a key, use the @nokey annotation.

Index Definition

@Catalog:
{ tableType : #COLUMN,
index : [
{ name:'Index1', order:#DESC, unique:true, elementNames:['field1',
'field2'] },
{ name:'Index2', order:#ASC, unique:false, elementNames:['field1',
'field7'] }
]
}

SAP HANA Developer Guide


200 PUBLIC Setting up the Data Persistence Model in SAP HANA
You use the @[Link] or @Catalog: { index: [...]} annotation to define an index for a CDS
entity. You can define the following values for the @[Link] annotation:

● 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;

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 201
b : String(20);
};
};

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:

Table-Type Syntax Options


Table-Type Option Description

#COLUMN @Catalog: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 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);
};

SAP HANA Developer Guide


202 PUBLIC Setting up the Data Persistence Model in SAP HANA
The calculation expression can contain arbitrary expressions and SQL functions. The following restrictions
apply to the expression you include in a calculated field:

● 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.

In a query, calculated fields can be used like ordinary elements.

 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;

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 203
};

 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.

Full text indexes


In the technical configuration for an entity, you can use the fulltext index keyword to specify the full-text
index type for the generated table, as illustrated in the following example.

 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

SAP HANA Developer Guide


204 PUBLIC Setting up the Data Persistence Model in SAP HANA
PHRASE INDEX RATIO 0.721
SEARCH ONLY off
FAST PREPROCESS off
TEXT ANALYSIS off;
fuzzy search index on (s.u);
};

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
};
};

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 205
Series Data *

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.

SAP HANA Developer Guide


206 PUBLIC Setting up the Data Persistence Model in SAP HANA
 Caution

(*) For information about the capabilities available for your license and installation scenario, refer to the
Feature Scope Description for SAP HANA.

Related Information

Create an Entity in CDS [page 189]


Create an Entity in CDS
CDS Annotations [page 178]
CDS Primitive Data Types [page 222]

5.1.4 Migrate an Entity from hdbtable to CDS (hdbdd)

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

To complete this task successfully, note the following prerequisites:

● You must have access to an SAP HANA system.


● You must have already created a development workspace and a project.
● You must have shared the project so that the newly created files can be committed to (and synchronized
with) the repository.
● You must have created a schema for the CDS catalog objects, for example, MYSCHEMA
● The owner of the schema must have SELECT privileges in the schema to be able to see the generated
catalog objects.
● You must have a design-time definition of the hdbtable entity you want to migrate to CDS.

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.

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 207
 Note

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.

SAP HANA Developer Guide


208 PUBLIC Setting up the Data Persistence Model in SAP HANA
 Tip

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.

3. Check that the table is in the catalog in the specified schema.


To ensure that the new CDS-defined table is identical to the old (HDBtable-defined) table, check the
contents of the table in the catalog.

Related Information

Migration Guidelines: hdbtable to CDS Entity [page 209]


SAP HANA to CDS Data-Type Mapping [page 210]

[Link] Migration Guidelines: hdbtable to CDS Entity

Replace an existing hdbtable definition with the equivalent CDS document.

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:

● CDS document structure


The new entity (that replaces the old hdbtable definition) must be defined at the top-level of the new CDS
document; it cannot be defined deeper in the CDS document, for example, nested inside a CDS context. If
the table (entity) is not defined as the top-level element in the CDS document, the resulting catalog name
of the entity (on activation) will not match the name of the runtime table that should be taken over by the
new CDS object. Instead, the name of the new table would also include the name of the CDS context in
which it was defined, which could lead to unintended consequences after the migration.
If the top-level element of the target CDS entity is not an entity (for example, a context or a type), the
activation of the CDS document creates the specified artifact (a context or a type) and does not take over
the catalog table defined by the source (hdbtable) definition.
● Structural compatibility
The new CDS document (defined in the hdbdd artifact) must be structurally compatible with the table
definition in the old hdbtable artifact (that is, with the runtime table).

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 209
○ Data types
All elements of the new CDS entity that have equally named counterparts in the old hdbtable
definition must be convertible with respect to their data type. The implicit conversion rules described
in the SAP HANA SQL documentation apply.
○ Elements/Columns
Elements/columns that exist in the runtime table but are not defined in the CDS entity will be dropped.
Elements/columns that do not exist in the runtime table but are defined in the CDS entity are added to
the runtime table.

Related Information

SAP HANA to CDS Data-Type Mapping [page 210]


SAP HANA SQL Data Type Conversion

[Link] SAP HANA to CDS Data-Type Mapping

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.

Mapping SAP HANA and CDS Types


SAP HANA Type (hdbtable) CDS Type (hdbdd)

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

SAP HANA Developer Guide


210 PUBLIC Setting up the Data Persistence Model in SAP HANA
SAP HANA Type (hdbtable) CDS Type (hdbdd)

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

Migrate an Entity from hdbtable to CDS (hdbdd) [page 207]


CDS Entity Syntax Options [page 198]
SAP HANA SQL Data Type Conversion

5.1.5 Create a User-Defined Structured Type in CDS

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

To complete this task successfully, note the following prerequisites:

● You must have access to an SAP HANA system.


● You must have already created a development workspace and a project.
● You must have shared the project so that the newly created files can be committed to (and synchronized
with) the repository.

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 211
● You must have created a schema for the CDS catalog objects, for example, MYSCHEMA
● The owner of the schema must have SELECT privileges in the schema to be able to see the generated
catalog objects.

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

1. Start the SAP HANA studio.


2. Open the SAP HANA Development perspective.
3. Open the Project Explorer view.
4. Create the CDS definition file for the user-defined structured type.
Browse to the folder in your project workspace where you want to create the CDS definition file for the new
user-defined structured type and perform the following steps:
a. Right-click the folder where you want to save the definition file for the user-defined structured type and
choose New Other... Database Development DDL Source File in the context-sensitive popup
menu.
b. Enter the name of the user-defined structured type in the File Name box, for example,
MyStructuredType.

 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:

SAP HANA Developer Guide


212 PUBLIC Setting up the Data Persistence Model in SAP HANA
 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 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.

7. Activate the changes in the repository.


a. Locate and right-click the new CDS definition file in the Project Explorer view.
b. In the context-sensitive pop-up menu, choose Team Activate .
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 (-).

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

CDS User-Defined Data Types [page 214]

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 213
CDS Structured Type Definition [page 217]
CDS Structured Types [page 220]

[Link] CDS User-Defined Data Types

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:

● Using allowed structured types (for example, user-defined)


● Referencing another data type

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;

SAP HANA Developer Guide


214 PUBLIC Setting up the Data Persistence Model in SAP HANA
@Schema: 'MYSCHEMA' // user-defined structured data types
type MyType3 {
field1 : UTCTimestamp;
field2 : 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
};

You can use the type of keyword in the following ways:

● 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 {

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 215
field1 : UTCTimestamp;
field2 : MyType2;
};

@[Link] : [{ name : 'IndexA', order : #ASC, unique: true,


elementNames : ['field1'] }]
entity MyEntity1 {
key id : Integer;
field1 : MyType3 not null;
field2 : String(24);
field3 : LocalDate;
field4 : type of field3;
field5 : type of MyType1.field2;
field6 : type of [Link].b; // refers to nested context
field7 : [Link]; // more context references
};
};

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.

SAP HANA Developer Guide


216 PUBLIC Setting up the Data Persistence Model in SAP HANA
Related Information

Create a User-Defined Structured Type in CDS


Create a User-Defined Structured Type in CDS [page 211]
CDS Structured Type Definition [page 217]
CDS Primitive Data Types [page 222]

[Link] CDS Structured Type Definition

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:

<SID> Catalog <MYSCHEMA> Procedures Table Types

Structured User-Defined Types

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 (;).

The type MyString80 is defined in the following CDS document:

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;

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 217
using Package1.Package2::MyString80; //contains definition of MyString80
@Schema: 'MySchema'
type MyStruct
{
aNumber : Integer;
someText : String(80);
otherText : MyString80; // defined in a separate type
};

 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.

Nested Structured Types

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:

type MyOtherInt : type of [Link]; // => Integer


type MyOtherStruct : type of [Link]; // => MyStruct

Generated Table Types

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 name space (for example, Pack1.Pack2)

SAP HANA Developer Guide


218 PUBLIC Setting up the Data Persistence Model in SAP HANA
● the names of all artifacts that enclose the type (for example, MyModel)
● the name of the type itself (for example, MyNestedStruct)

create type "Pack1.Pack2::[Link]" as table (


name nvarchar(80),
[Link] integer,
[Link] nvarchar(80),
[Link] nvarchar(80)
);

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

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 219
{
text : LargeString;
nested : MyNestedStruct;
};
};

Related Information

Create a User-Defined Structured Type in CDS [page 211]


Create a User-Defined Structured Type in CDS
CDS User-Defined Data Types [page 214]
CDS Structured Types [page 220]
CDS Primitive Data Types [page 222]

[Link] CDS Structured Types

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;

SAP HANA Developer Guide


220 PUBLIC Setting up the Data Persistence Model in SAP HANA
};
};

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

Create a User-Defined Structured Type in CDS [page 211]

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 221
Create a User-Defined Structured Type in CDS
CDS Primitive Data Types [page 222]
CDS User-Defined Data Types [page 214]
CDS Structured Type Definition [page 217]

[Link] CDS Primitive Data Types

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:

● DDL data types [page 222]


● Native SAP HANA data types [page 224]

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.

Supported SAP HANA DDL Primitive Types


Name Description SQL Literal Syntax SQL Name EDM Name

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.

LargeString Variable length string of up to 2 GB 'text with “quote”' NCLOB String


(no comparison)

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.

LargeBinary Variable length byte string of up to 2 x'01Cafe', X'01Cafe' BLOB Binary


GB (no comparison)

Integer Respective container's standard 13, -1234567 INTEGER Int64


signed integer. Signed 32 bit integers
in 2's complement, -2**31 .. 2**31-1.
Default=NULL

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.

SAP HANA Developer Guide


222 PUBLIC Setting up the Data Persistence Model in SAP HANA
Name Description SQL Literal Syntax SQL Name EDM Name

DecimalFloat Decimal floating-point number (IEEE 12.345, -9.876 DECIMAL Decimal


754-2008) with 34 mantissa digits;
range is roughly ±1e-6143 through
±9.99e+6144

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.

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 223
 Note

* In CDS, the name of SAP HANA data types are prefixed with the word “hana”, for example,
[Link], or [Link], or [Link].

Supported Native SAP HANA Data Types


Data Type * Description SQL Literal Syntax SQL Name EDM Name

ALPHANUM Variable-length char­ - ALPHANUMERIC -


acter string with spe­
cial comparison

SMALLINT Signed 16-bit integer -32768, 32767 SMALLINT Int16

TINYINT Unsigned 8-bit integer 0, 255 TINYINT Byte

REAL 32-bit binary floating- - REAL Single


point number

SMALLDECIMAL 64-bit decimal float- - SMALLDECIMAL Decimal


ing-point number

VARCHAR Variable-length ASCII - VARCHAR String


character string with
user-definable length
limit n

CLOB Large variable-length - CLOB String


ASCII character string,
no comparison

BINARY Byte string of fixed - BINARY Blob


length n

ST_POINT 0-dimensional geome­ - - -


try representing a sin­
gle location

ST_GEOMETRY Maximal supertype of - - -


the geometry type hi­
erarchy; includes
ST_POINT

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];

SAP HANA Developer Guide


224 PUBLIC Setting up the Data Persistence Model in SAP HANA
j : [Link](10);
k : hana.ST_POINT;
l : hana.ST_GEOMETRY;
};

Related Information

Create a User-Defined Structures Type in CDS [page 211]


Create a CDS User-Defined Structure in XS Advanced

5.1.6 Create an Association in CDS

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

To complete this task successfully, note the following prerequisites:

● You must have access to an SAP HANA system.


● You must have already created a development workspace and a project.
● You must have shared the project so that the newly created files can be committed to (and synchronized
with) the repository.
● You must have created a schema for the CDS catalog objects, for example, MYSCHEMA
● The owner of the schema must have SELECT privileges in the schema to be able to see the generated
catalog objects.

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

1. Start the SAP HANA studio.

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 225
2. Open the SAP HANA Development perspective.
3. Open the Project Explorer view.
4. Create the CDS entity-definition file which will contain the associations you define.
Browse to the folder in your project workspace where you want to create the new CDS entity-definition file
and perform the following steps:

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
};

};

6. Define a one-to-one association between CDS entities.

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:

SAP HANA Developer Guide


226 PUBLIC Setting up the Data Persistence Model in SAP HANA
 Note

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;
};

7. Define an unmanaged association with cardinality one-to-many between CDS entities.

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;
};

8. Save the CDS entity-definition file containing the new associations.

 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.

9. Activate the changes in the repository.


a. Locate and right-click the new CDS entity-definition file in the Project Explorer view.
b. In the context-sensitive pop-up menu, choose Team Activate .

 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

CDS Associations [page 228]


CDS Association Syntax Options [page 234]

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 227
[Link] CDS Associations

Associations define relationships between entities.

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

CDS supports both managed and unmanaged associations.

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

SAP HANA Developer Guide


228 PUBLIC Setting up the Data Persistence Model in SAP HANA
cardinality of the source of the association in the form [ maxs, min .. max], too, where maxs = * denotes
infinity.

 Tip

The information concerning the maximum cardinality is only used as a hint for optimizing the execution of
the resulting JOIN.

The following examples illustrate how to express cardinality in an association definition:

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;
};
};

Target Entities in Associations

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:

address1 : Association to Address;


address2 : Association to Address { id };
address3 : Association[1] to Address { zipCode, street, country };

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 229
Filter Conditions and Prefix Notation

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

view C1 as select from Customer {


name,
orders[status='open'].id as orderId
};

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.

Foreign Keys in Associations

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

SAP HANA Developer Guide


230 PUBLIC Setting up the Data Persistence Model in SAP HANA
target entity, the association has cardinality to-many. The following examples show how to express foreign keys
in an association.

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.

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 231
 Sample Code

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

};
};

SAP HANA Developer Guide


232 PUBLIC Setting up the Data Persistence Model in SAP HANA
Example:
Complex (One-to-Many) Association

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;
};

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 233
Related Information

Create an Association in CDS [page 225]


Create a CDS Association in XS Advanced

[Link] CDS Association Syntax Options

Associations define relationships between entities.

Example:
Managed Associations

Association [ <cardinality> ] to <targetEntity> [ <forwardLink> ]

Example:
Unmanaged Associations

Association [ <cardinality> ] to <targetEntity> <unmanagedJoin>

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

CDS supports both managed and unmanaged associations.

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:

● <Cardinality> [page 235]


The relationship between the source and target in the association, for example, one-to-one, one-to-many,
many-to-one
● <targetEntity> [page 236]
The target entity for the association
● <forwardLink> [page 237]

SAP HANA Developer Guide


234 PUBLIC Setting up the Data Persistence Model in SAP HANA
The foreign keys to use in a managed association, for example, element names in the target entity
● <unmanagedJoin> [page 238]
Unmanaged associations only; the ON condition specifies the elements of the source and target elements
and entities to use in the association

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:

[ [ ( maxs | * ) , ] // source cardinality


[ min .. ] ( max | * ) // target cardinality
]

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.

The following examples illustrate how to express cardinality in an association definition:

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;
};
};

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 235
The following table describes the various cardinality expressions illustrated in the example above:

Association Cardinality Syntax Examples


Association Cardinality Explanation

assoc1 [0..1] The association has no or one target instance

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

assoc4 [1..1] The association has one target instance

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)

assoc7 [2..7] Any numbers are possible; the user provides

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

SAP HANA Developer Guide


236 PUBLIC Setting up the Data Persistence Model in SAP HANA
entity. A target entity specification is mandatory; a default value is not assumed if no target entity is specified
in an association relationship.

Association[ <cardinality> ] to <targetEntity> [ <forwardLink> ]

The target entity Address specified as the target entity of an association could be expressed as illustrated the
following examples:

address1 : Association to Address;


address2 : Association to Address { id };
address3 : Association[1] to Address { zipCode, street, country };

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:

Association[ <cardinality> ] to <targetEntity> [ <forwardLink> ]

The forwardLink element of the association could be expressed as follows:

<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 };
};

Association Syntax Options


Association Keys Explanation

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.

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 237
Association Keys Explanation

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 .

SAP HANA Developer Guide


238 PUBLIC Setting up the Data Persistence Model in SAP HANA
In the following example, the association inhabitants relates the element id of the source entity Room with
the element officeId in the target entity Employee. The target element officeId is accessed through the
name of 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;
// <...>
};
};

The following example defines two related unmanaged associations:

● 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);

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 239
c : Decimal(20,10);
d : UTCDateTime;
your : Association[1] to YourEntity on your.a - a < MyIntConst;
};
entity YourEntity {
key id : Integer;
a : Integer;
};
entity HerEntity {
key id : Integer;
t : String(20);
};
view MyView as select from MyEntity
inner join HerEntity on locate (b, :MyStringConst) > 0
{
a + :MyIntConst as x,
b || ' is ' || :MyStringConst as y,
c * sin(:MyDecConst) as z
} where d < :[Link];
};

Related Information

Create a CDS Association in XS Advanced


CDS Associations [page 228]

5.1.7 Create a View in CDS

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

To complete this task successfully, note the following prerequisites:

● You must have access to an SAP HANA system.


● You must have already created a development workspace and a project.
● You must have shared the project so that the newly created files can be committed to (and synchronized
with) the repository.
● You must have created a schema for the CDS catalog objects, for example, MYSCHEMA
● The owner of the schema must have SELECT privileges in the schema to be able to see the generated
catalog objects.

SAP HANA Developer Guide


240 PUBLIC Setting up the Data Persistence Model in SAP HANA
Context

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

1. Start the SAP HANA studio.


2. Open the SAP HANA Development perspective.
3. Open the Project Explorer view.
4. Create the CDS-definition file which will contain the view you define in the following steps.
Browse to the folder in your project workspace where you want to create the new CDS-definition file and
perform the following steps:

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 {

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 241
key id : Integer;
street : StreetAddress;
zipCode : Integer;
city : String(80);
country : CountryAddress;
type : String(10); // home, office
};
};

6. Define a view as a projection of a CDS entity.

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.

view AddressView as select from Address


{
id,
[Link],
[Link]
};

7. Save the CDS-definition file containing the new view.

 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.

8. Activate the changes in the repository.


a. Locate and right-click the new CDS-definition file in the Project Explorer view.
b. In the context-sensitive pop-up menu, choose Team Activate .

 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.

SAP HANA Developer Guide


242 PUBLIC Setting up the Data Persistence Model in SAP HANA
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>');

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.

<SID> Catalog <MYSCHEMA> Views


c. Open a data preview for the new view AddressView.
Right-click the new view <[Link]>::[Link] and choose Open Data
Preview in the pop-up menu.

Related Information

CDS Views [page 243]


CDS View Syntax Options [page 245]
Spatial Types and Functions [page 261]

[Link] CDS Views

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]
};
<...>

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 243
}

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:

<SID> Catalog <MYSCHEMA> Views

Views defined in a CDS document can make use of the following SQL features:

● CDS Type definition


● Expressions and functions (for example, “a + b as theSum”)
● Aggregates, “GROUP BY”, and “HAVING” clauses
● Associations (including filters and prefixes)
● ORDER BY, CASE, UNION, JOIN, and TOP
● With Parameters
● Select Distinct
● Spatial Data (for example, “ST_Distance”)

 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

type MyInteger : Integer;


entity E {
a : MyInteger;
b : MyInteger;
};
view V as select from E {
a,
a+b as s1,
a+b as s2 : MyInteger
};

In the example of different type definitions, the following is true:

● 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

SAP HANA Developer Guide


244 PUBLIC Setting up the Data Persistence Model in SAP HANA
 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.

Related Information

Create a CDS View in XS Advanced


CDS View Syntax Options [page 245]
CDS Associations [page 228]

[Link] CDS View Syntax Options

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,

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 245
salary
} ORDER BY salary DESC;
VIEW MyView4 AS SELECT FROM Employee {
CASE
WHEN a < 10 then 'small'
WHEN 10 <= a AND a < 100 THEN 'medium'
ELSE 'large'
END AS size
};
VIEW MyView5 AS
SELECT FROM E1 { a, b, c}
UNION
SELECT FROM E2 { z, x, y};
VIEW MyView6 AS SELECT FROM Customer {
name,
orders[status='open'].{ id as orderId,
date as orderDate,
items[price>200].{ descr,
price } }
};
VIEW MyView7 as
select from E { a, b, c}
order by a limit 10 offset 30;
VIEW V_join as select from E join (F as X full outer join G on [Link] = [Link]) on
[Link] = c {
a, b, c
};
VIEW V_top as select from E TOP 10 { a, b, c};
VIEW V_dist as select from E distinct { a };
VIEW V_param with parameters PAR1: Integer, PAR2: MyUserDefinedType, PAR3: type
of [Link]
as select from MyEntity {
id,
elt };
VIEW V_type as select from E {
a,
a+b as s1,
a+b as s2 : MyInteger
};
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 SpatialView1 as select from Person {
name,
homeAddress.street_name || ', ' || [Link] as home,
officeAddress.street_name || ', ' || [Link] as office,
round( [Link].ST_Distance([Link], 'meter')/1000, 1) as
distanceHomeToWork,
round( [Link].ST_Distance(NEW ST_POINT(8.644072, 49.292910),
'meter')/1000, 1) as distFromSAP03
};
}

Expressions and Functions

In a CDS view definition you can use any of the functions and expressions listed in the following example:

View MyView9 AS SELECT FROM SampleEntity


{

SAP HANA Developer Guide


246 PUBLIC Setting up the Data Persistence Model in SAP HANA
a + b AS theSum,
a - b AS theDifference,
a * b AS theProduct,
a / b AS theQuotient,
-a AS theUnaryMinus,
c || d AS theConcatenation
};

 Note

When expressions are used in a view element, an alias must be specified, for example, AS theSum.

Aggregates

In a CDS view definition, you can use the following 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.

VIEW MyView10 AS SELECT FROM Employee


{
orgUnit,
count(id) AS headCount,
sum(salary) AS totalSalary,
max(salary) AS maxSalary
}
WHERE joinDate > date'2011-01-01'
GROUP BY orgUnit;

 Note

Expressions are not allowed in the GROUP BY clause.

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;

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 247
const MyDateTimeConst : UTCDateTime = '2015-09-30 14:33';
entity MyEntity {
key id : Integer;
a : Integer;
b : String(100);
c : Decimal(20,10);
d : UTCDateTime;
your : Association[1] to YourEntity on your.a - a < MyIntConst;
};
entity YourEntity {
key id : Integer;
a : Integer;
};
entity HerEntity {
key id : Integer;
t : String(20);
};
view MyView as select from MyEntity
inner join HerEntity on locate (b, :MyStringConst) > 0
{
a + :MyIntConst as x,
b || ' is ' || :MyStringConst as y,
c * sin(:MyDecConst) as z
} where d < :[Link];
};

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.

Constant Declaration and Result

Constant Expression Result Comments

a as a1, Success “a” is resolved in the space of alias and element names, for example, ele­
ment “a” of entity “E”.

SAP HANA Developer Guide


248 PUBLIC Setting up the Data Persistence Model in SAP HANA
Constant Expression Result Comments

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, Success Error: no access to “E” via “:”

:E.a as a4, Error Error; no access to “E” (or any of its elements) via “:”

:c Error Error: there is no alias for “c”.

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.

VIEW MyView11 AS SELECT FROM Employee


{
[Link],
[Link],
[Link]
};

Subqueries

You can define subqueries in a CDS view, as illustrated in the following example:

 Restriction

For use in XS advanced only; subqueries are not supported in XS classic

 Code Syntax

select from (select from F {a as x, b as y}) as Q {


x+y as xy,
(select from E {a} where b=Q.y) as a
} where x < all (select from E{b})

 Note

In a correlated subquery, elements of outer queries must always be addressed by means of a table alias.

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 249
WHERE

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.

VIEW EmployeesInRoom_ABC_3_4 AS SELECT FROM Employee


{
[Link]
} WHERE [Link] = 'ABC'
AND [Link] = 3
AND [Link] = 4;

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.

VIEW CompanyCarLicensePlates AS SELECT FROM [Link]


{
licensePlate
};

In the FROM clause, you can use the following elements:

● an entity or a view defined in the same CDS source file


● a native SAP HANA table or view that is available in the schema specified in the schema annotation
(@Schema in the corresponding CDS document)

If a CDS view references a native SAP HANA table, the table and column names must be specified using their
effective SAP HANA names.

create table foo (


bar : Integer,
"gloo" : Integer
)

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.

VIEW MyViewOnNative as SELECT FROM FOO


{
BAR,
gloo
};

SAP HANA Developer Guide


250 PUBLIC Setting up the Data Persistence Model in SAP HANA
GROUP BY

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.

VIEW V11 AS SELECT FROM Employee


{
[Link],
[Link],
[Link],
[Link],
count(id) as seatsTaken,
count(id)/[Link] as occupancyRate
} GROUP BY [Link],
[Link],
[Link],
[Link],
[Link]
HAVING [Link] = 'office' AND count(id)/capacity < 0.5;

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.

VIEW V11 AS SELECT FROM Employee


{
[Link],
[Link],
[Link],
[Link],
count(id) as seatsTaken,
count(id)/[Link] as occupancyRate
} GROUP BY [Link],
[Link],
[Link],
[Link],
[Link]
HAVING [Link] = 'office' AND count(id)/capacity < 0.5;

ORDER BY

The ORDER BY operator enables you to list results according to an expression or position, for example salary.

VIEW MyView3 AS SELECT FROM Employee


{
orgUnit,
salary
} ORDER BY salary DESC;

In the same way as with plain SQL, the ASC and DESC operators enable you to sort the list order as follows.

● ASC

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 251
Display the result set in ascending order
● DESC
Display the result set in descending order

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.

VIEW MyViewV AS SELECT FROM E


{ a, b, c}
order by a limit 10 offset 30;

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);
};

VIEW MyView12 AS SELECT FROM MyEntity12 {


id,
CASE color // defined in MyEntity12
WHEN 'R' THEN 'red'
WHEN 'G' THEN 'green'
WHEN 'B' THEN 'blue'
ELSE 'black'
END AS color,
CASE
WHEN a < 10 then 'small'
WHEN 10 <= a AND a < 100 THEN 'medium'
ELSE 'large'
END AS size
};

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

SAP HANA Developer Guide


252 PUBLIC Setting up the Data Persistence Model in SAP HANA
by removing duplicates found from different select [Link] signature of the result view is equal to the
signature of the first SELECT in the union.

 Note

View MyView5 has elements a, b, and c.

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

The following example shows a simple 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
};

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 253
TOP

You can use the SQL clause TOP in a CDS query, as illustrated in the following example:

 Sample Code

view V_top as select from E TOP 10 { a, b, c};

 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.

SAP HANA Developer Guide


254 PUBLIC Setting up the Data Persistence Model in SAP HANA
 Sample Code

Parameters in a CDS View

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

Keywords are case insensitive.

Parameters in View Queries

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

Using Parameters in a View Query

view ExampleView with parameters PAR1: Integer,


PAR2: UserDefinedType,
PAR3: type of [Link]
as select from SomeEntity
left outer join SomeOtherEntity
on [Link] < [Link] + :PAR1
{
id + :PAR1 as idWithOffset,
elt,
:PAR1,
$parameters.PAR3
} where elt != $parameters.PAR2;

Invoking a View with Parameters

Parameters are passed to views as a comma-separated list in parentheses. Optional filter expressions must
then follow the parameter list.

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 255
 Restriction

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);
};

view TargetWindowView with parameters LOWER_LIMIT: Integer


as select from TargetEntity {
targetId,
someElementOfTargetEntity
} where targetId > :LOWER_LIMIT
and targetId <= :LOWER_LIMIT + 10;

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

Query a Parameterized CDS View (with Association)

view SourceConsumption with parameters CUSTOMER_ID: Integer


as select from SourceEntity {
someElementOfSourceEntity,
toTargetViaParamView(LOWER_LIMIT:
$parameters.CUSTOMER_ID).someElementOfTargetEntity
};

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

Follow an Association in the FROM Clause

view ConsumptionView with parameters CUSTOMER_ID: Integer


as select from [Link](LOWER_LIMIT: :CUSTOMER_ID)
{
id,
someElementOfTargetEntity

SAP HANA Developer Guide


256 PUBLIC Setting up the Data Persistence Model in SAP HANA
};

You can select directly from the view with parameters, adding a free JOIN expression, as illustrated in the
following example:

 Sample Code

Select from a Parameterized View with JOIN Expression

view ConsumptionView with parameters CUSTOMER_ID: Integer


as select from TargetWindowView(LOWER_LIMIT: :CUSTOMER_ID) as TWV_ALIAS
RIGHT OUTER JOIN ... ON TWV_ALIAS.targetId ....
{
...
};

Annotations in Parameter Definitions


Parameter definitions can be annotated in the same way as any other artifact in CDS; the annotations must be
prepended to the parameter name. Multiple annotations are separated either by whitespace or new-line
characters.

 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

Annotation Assignments to Parameter Definitions in CDS Views

annotation remark: String(100);

view TargetWindowView with parameters


@remark: 'This is an arbitrary annotation'
@positiveValuesOnly: true
LOWER_LIMIT: Integer
as select from TargetEntity
{
targetId,
....
} where targetId > :LOWER_LIMIT and targetId <= :LOWER_LIMIT + 10;

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 257
Associations, Filters, and Prefixes

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

Associations as View Elements

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

view C1 as select from Customer {


name,
orders[status='open'].id as orderId
};

SAP HANA Developer Guide


258 PUBLIC Setting up the Data Persistence Model in SAP HANA
The following example shows how to use the prefix notation to ensure that the compiler understands that there
is only one association (orders) to resolve but with multiple elements (id and date):

 Sample Code

view C1 as select from Customer {


name,
orders[status='open'].{ id as orderId,
date as orderDate
}
};

 Tip

Filter conditions and prefixes can be nested.

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

view C2 as select from Customer {


name,
orders[status='open'].{ id as orderId,
date as orderDate,
items[price>200].{ descr,
price
}
}
};

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

view C3 as select from Customer {


name,
[Link] as orderId,
[Link] as orderDate,
[Link] as itemDescr,
[Link] as itemPrice
};

The example above can be expressed more elegantly by combining the associations orders and items using
the following prefix notation:

 Sample Code

view C1 as select from Customer {


name,
orders.{ id as orderId,

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 259
date as orderDate,
items. { descr as itemDescr,
price as itemPrice
}
}
};

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

type MyInteger : Integer;


entity E {
a : MyInteger;
b : MyInteger;
};
view V as select from E {
a,
a+b as s1,
a+b as s2 : MyInteger
};

In the example of different type definitions, the following is true:

● 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

SAP HANA Developer Guide


260 PUBLIC Setting up the Data Persistence Model in SAP HANA
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, which is rounded
up and displayed to one decimal point.

 Sample Code

view SpatialView1 as select from Person {


name,
homeAddress.street_name || ', ' || [Link] as home,
officeAddress.street_name || ', ' || [Link] as office,
round( [Link].ST_Distance([Link], 'meter')/1000, 1)
as distanceHomeToWork,
round( [Link].ST_Distance(NEW ST_POINT(8.644072, 49.292910),
'meter')/1000, 1) as distFromSAP03
};

 Caution

(*) For information about the capabilities available for your license and installation scenario, refer to the
Feature Scope Description for SAP HANA.

Related Information

Create a View in CDS [page 240]


Create a View in CDS
Spatial Types and Functions [page 261]

[Link] Spatial Types and Functions

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;

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 261
};
entity Address {
key id : Integer;
street_number : Integer;
street_name : String(100);
zip : String(10);
city : String(100);
loc : hana.ST_POINT(4326);
};
view GeoView1 as select from Person {
name,
homeAddress.street_name || ', ' || [Link] as home,
officeAddress.street_name || ', ' || [Link] as office,
round( [Link].ST_Distance([Link], 'meter')/1000,
1) as distanceHomeToWork,
round( [Link].ST_Distance(NEW ST_POINT(8.644072, 49.292910),
'meter')/1000, 1) as distFromSAP03
};
};

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

Create a View in CDS [page 240]


Create a View in CDS
CDS View Syntax Options [page 245]
CDS Entity Syntax Options [page 198]
CDS Primitive Data Types [page 222]

5.1.8 Modifications to CDS Artifacts

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.

● Removing an artifact from a CDS document [page 263]

SAP HANA Developer Guide


262 PUBLIC Setting up the Data Persistence Model in SAP HANA
● Changing the definition of an artifact in a CDS document [page 263]
● Modifying a catalog object generated by CDS [page 265]
● Transporting a DU that contains modified CDS documents [page 265]

Removing an Artifact from a CDS Document

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.

Changing the Definition of an Artifact in a CDS Document

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

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 263
You can add an element to (or remove it from) the primary key by adding or removing the “key” modifier.

 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.

● Column or row store (@[Link])


It is possible to change the [Link] annotation that defines the table type, for example, to
transform a table from the column store (#COLUMN) to row store (#ROW), and vice versa.
● Index types (@[Link])
Is is possible to change the “[Link]” annotation, as long as the modified index is valid for the
corresponding CDS entity.

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.

SAP HANA Developer Guide


264 PUBLIC Setting up the Data Persistence Model in SAP HANA
From the developer's perspective, the CDS entity Entity1 has been moved from context OuterCtx to
InnerCtx. From the compiler's perspective, however, the entity pack::OuterCtx.Entity1 has disappeared
and, as a result, will be deleted (and the corresponding generated table with all its content dropped), and a new
entity named pack::[Link].Entity1 has been defined.

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.

Modifying a Catalog Object Generated from CDS

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.

Transporting a DU that Contains Modified CDS Documents

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.

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 265
Related Information

SAP HANA to CDS Data-Type Mapping [page 210]


SAP HANA SQL Data Type Conversion

5.1.9 Tutorial: Get Started with CDS

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:

● You must have access to an SAP HANA system.


● You must have already created a development workspace and a project.
● You must have shared the project so that the newly created files can be committed to (and synchronized
with) the repository.
● You must have created a schema definition [Link].

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

1. Start the SAP HANA studio.


2. Open the SAP HANA Development perspective.
3. Open the Project Explorer view.

SAP HANA Developer Guide


266 PUBLIC Setting up the Data Persistence Model in SAP HANA
4. Create the CDS document that defines the entity you want to create.
Browse to the folder in your project workspace where you want to create the new CDS document (for
example, in a project you have already created and shared) and perform the following tasks:

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.

c. Choose Finish to save the new empty CDS document.

 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

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 267
entity keyword. In the example in this tutorial, you would save the entity definition “BOOK” in the
CDS document [Link].

5. Define the table entity.


To edit the CDS document, in the Project Explorer view double-click the file you created in the previous
step, for example, [Link], and add the entity-definition code:

 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);
};

6. Save the CDS document [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.

7. Activate the new CDS document in the repository.


a. In the Project Explorer view, locate the newly created artifact [Link].
b. Right-click [Link] and choose Team > Activate in the context-sensitive popup menu.
The CDS/DDL editor checks the syntax of the source file code, highlights the lines where an error
occurs, and provides details of the error in the Problems view.

SAP HANA Developer Guide


268 PUBLIC Setting up the Data Persistence Model in SAP HANA
The activation creates the following table in the schema MYSCHEMA, both of which are visible using the
SAP HANA studio:

"MYSCHEMA"."mycompany.myapp1::BOOK"

The following public synonym is also created, which can be referenced using the standard SQL query
notation:

"mycompany.myapp1::BOOK"

8. Add an entry to the BOOK entity using SQL.

INSERT INTO "mycompany.myapp1::BOOK" VALUES ( 'Shakespeare', 'Hamlet',


'1234567', 'Books Incorporated' );

9. Save and activate the modifications to the entity.


10. Check the new entry by running a simply SQL query.

SELECT COUNT(*) FROM "mycompany.myapp1::BOOK" WHERE Author = 'Shakespeare'

Related Information

Create a Schema [page 284]

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 269
5.1.10 Import Data with CDS Table-Import

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:

● An SAP HANA database instance is available.


● The SAP HANA database client is installed and configured.
● You have a database user account set up with the roles containing sufficient privileges to perform actions
in the repository, for example, add packages, add objects, and so on.
● The SAP HANA studio is installed and connected to the SAP HANA repository.
● You have a development environment including a repository workspace, a package structure for your
application, and a shared project to enable you to synchronize changes to the project files in the local file
system with the repository.

 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

1. Create a root package for your table-import application.


In SAP HANA studio, open the SAP HANA Development perspective and perform the following steps:
a. In the package hierarchy displayed in the Systems view, right-click the package where you want to
create the new package for your table-import configuration and choose New > Package... .
b. Enter a name for your package, for example TiTest. You must create the new TiTest package in your
own namespace, for example [Link]

SAP HANA Developer Guide


270 PUBLIC Setting up the Data Persistence Model in SAP HANA
 Note

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.

a. Choose OK to create the new package.


2. Create a set of table-import files.

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.

○ The table-import configuration file, for example, [Link]


Specifies the source file containing the data values to import and the target table in SAP HANA into
which the data must be inserted
○ A CSV file, for example, [Link]
Contains the data to be imported into the SAP HANA table during the table-import operation; values in
the .csv file can be separated either by a comma (,) or a semi-colon (;).
○ A target table.
The target table can be either a runtime table in the catalog or a table definition, for example, a table
defined using the .hdbtable syntax ([Link]) or the CDS-compliant .hdbdd syntax
([Link]).

 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.

○ The schema named AMT


Specifies the name of the schema in which the target import table resides
When all the necessary files are available, you can import data from a source file, such as a CSV file, into
the desired target table.
3. If it does not already exist, create a schema named AMT in the catalog; the AMT schema is where the target
table for the table-import operation resides.
4. Create or open the table-definition file for the target import table ([Link]) and enter the
following lines of text; this example uses the .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'

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 271
@[Link] : #COLUMN
entity inhabitants {
key ID : Integer;
surname : String(30);
name : String(30);
city : String(30);
};

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;
}
];

7. Deploy the table import.


a. Select the package that you created in the first step, for example, [Link].
b. Click the alternate mouse button and choose Commit.
c. Click the alternate mouse button and choose Activate.
This activates all the repository objects. The data specified in the CSV file [Link] is imported
into the SAP HANA table inhabitants using the data-import configuration defined in the
[Link] table-import configuration file.
8. Check the contents of the runtime table inhabitants in the catalog.
To ensure that the import operation completed as expected, use the SAP HANA studio to view the contents
of the runtime table inhabitants in the catalog. You need to confirm that the correct data was imported
into the correct columns.
a. In the SAP HANA Development perspective, open the Systems view.
b. Navigate to the catalog location where the inhabitants object resides, for example:
<SID> Catalog AMT Tables
c. Open a data preview for the updated object.
Right-click the updated object and choose Open Data Preview in the context-sensitive menu.

SAP HANA Developer Guide


272 PUBLIC Setting up the Data Persistence Model in SAP HANA
[Link] Data Provisioning Using Table Import

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].

CSV Data File Constraints

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

Table-Import Configuration [page 274]


Table-Import Configuration-File Syntax [page 276]

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 273
[Link] Table-Import Configuration

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:

● Public synonym (“[Link]::myTable”)


If you use the public synonym to reference a target table for the import operation, you must use either the
hdbtable or cdstable keyword, for example, hdbtable = "[Link]::myTable";
● Schema-qualified catalog name (“mySchema”.“MyTable”
If you use the schema-qualified catalog name to reference a target table for the import operation, you must
use the table keyword in combination with the schema keyword, for example, table = "myTable";
schema = "mySchema";

 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

SAP HANA Developer Guide


274 PUBLIC Setting up the Data Persistence Model in SAP HANA
activation of the configuration file, for example: Table import target table cannot be found. or
Schema could not be resolved.

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 (;).

● Comma (,) separated values

,,,BW_CUBE,,40000000,2,40000000,all

● Semi-colon (;) separated values

;;;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.

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 275
Related Information

Table-Import Configuration-File Syntax [page 276]

[Link] Table-Import Configuration-File Syntax

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";

SAP HANA Developer Guide


276 PUBLIC Setting up the Data Persistence Model in SAP HANA
 Note

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:

● Schema could not be resolved.


● If you import into a catalog table, please provide schema.

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";.

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 277
file

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

The useHeaderNames keyword only works if header is also set to “true”.

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 = ";";

SAP HANA Developer Guide


278 PUBLIC Setting up the Data Persistence Model in SAP HANA
 Note

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.

"Value 1, has a comma","Value 2 has, two, commas","Value3"

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.

#Value 1; has a semi-colon#;#Value 2 has; two; semi-colons#;#Value3#

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 279
distinguishEmptyFromNull

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

The default setting for distinguishEmptyFromNull is false.

If distinguishEmptyFromNull=false is used in combination with delimEnclosing, then an empty value


in the .CSV (with or without quotes “”) is interpreted as NULL.

"Value1",,"",Value2

The table-import process would add the values shown in the example .csv above into the target table as
follows:

Value1 | NULL | NULL | Value2

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.

keys = [ "GROUP_TYPE" : "BW_CUBE", "GROUP_TYPE" : "BW_DSO", "GROUP_TYPE" :


"BW_PSA"];

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

In the following example, the GROUP_TYPE column is specified as empty(“”).

keys = [ "GROUP_TYPE" : ""];

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

SAP HANA Developer Guide


280 PUBLIC Setting up the Data Persistence Model in SAP HANA
[Link] Table-Import Configuration Error Messages

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.

Table-Import Error Messages

Message Number Message Text Message Reason

40200 Invalid combination of table The table keyword is specified in a table-import


declarations found, you may only configuration that references a table defined
use [cdstable | hdbtable | table] using the .hdbtable (or .hdbdd) syntax.

The hdbtable keyword is specified in a table-im­


port configuration that references a table de­
fined using another table-definition syntax, for
example, the .hdbdd syntax.

The cdstable keyword is specified in a table-im­


port configuration that references a table de­
fined using another table-definition syntax, for
example, the .hdbtable syntax.

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).

The public synonym for an .hdbtable


or .hdbdd (CDS) table definition cannot be
resolved to a catalog table.

40203 Schema resolution error The schema specified with the schema key­
word does not exist or could not be found
(wrong name).

The database could not complete the schema-


resolution process for some reason - perhaps
unrelated to the table-import configuration
(.hdbti), for example, an inconsistent data­
base status.

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.

SAP HANA Developer Guide


Setting up the Data Persistence Model in SAP HANA PUBLIC 281
Message Number Message Text Message Reason

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.

If keys are specified for an import in a table-im­


port configuration, multiple imports into the
same target table are checked for potential
data collisions.

40212 Importing data into table failed Either duplicate keys were written (due to du­
plicates in the .CSV source file) or

An (unexpected) error occurred on the SQL


level.

40213 CSV table column count mismatch Either the number of columns in the .