PUBLIC
SAP HANA Platform 2.0 SPS 04
Document Version: 1.1 – 2019-10-31
SAP HANA XS JavaScript Reference
© 2019 SAP SE or an SAP aliate company. All rights reserved.
THE BEST RUN
Content
1 SAP HANA XS JavaScript Reference..............................................4
2 Getting Started with XS JavaScript..............................................5
2.1 Developing Native SAP HANA Applications...........................................5
2.2 Roles and Permissions for XS Development...........................................7
2.3 Developer Information Map.....................................................10
SAP HANA Developer Information by Guide.......................................10
SAP HANA Developer Information by Task........................................ 11
SAP HANA Developer Information by Scenario.....................................12
3 Writing Server-Side JavaScript Code............................................ 16
3.1 Data Access with JavaScript in SAP HANA XS........................................16
3.2 Using Server-Side JavaScript in SAP HANA XS........................................17
Tutorial: Write Server-Side JavaScript Application Code...............................17
3.3 Using Server-Side JavaScript Libraries.............................................31
Import Server-Side JavaScript Libraries..........................................33
Write Server-Side JavaScript Libraries...........................................34
3.4 Using the Server-Side JavaScript APIs............................................. 35
Tutorial: Use the XSJS Outbound API............................................47
Tutorial: Call an XS Procedure with Table-Value Arguments.............................51
Tutorial: Query a CDS Entity using XS Data Services.................................56
Tutorial: Update a CDS Entity Using XS Data Services................................61
3.5 Creating Custom XS SQL Connections.............................................64
Create an XS SQL Connection Conguration...................................... 66
3.6 Setting the Connection Language in SAP HANA XS.................................... 72
3.7 Scheduling XS Jobs...........................................................74
Tutorial: Schedule an XS Job..................................................75
Add or Delete a Job Schedule during Runtime..................................... 84
3.8 Tracing Server-Side JavaScript.................................................. 86
Trace Server-Side JavaScript Applications........................................86
View XS JavaScript Application Trace Files........................................88
3.9 Debugging Server-Side JavaScript................................................88
Create a Debug Conguration.................................................92
Execute XS JavaScript Debugging..............................................93
Troubleshoot Server-Side JavaScript Debugging....................................98
3.10 Testing XS JavaScript Applications...............................................100
Automated Tests with XSUnit in SAP HANA.......................................101
2
P U B L I C
SAP HANA XS JavaScript Reference
Content
Application Development Testing Roles......................................... 102
Test an SAP HANA XS Application with XSUnit.................................... 102
Testing JavaScript with XSUnit................................................116
SAP HANA XS JavaScript Reference
Content
P U B L I C 3
1 SAP HANA XS JavaScript Reference
This guide explains how to use server-side JavaScript (XSJS) to build applications that run in SAP HANA
Extended Application Services (XS). The XSJS applications dene the business logic required to serve client
requests for data via HTTP.
The SAP HANA XS JavaScript Reference explains how to use SAP HANA server-side JavaScript to build the
application logic for your XSJS applications running either in XS classic or the compatibility layer of the XS
advanced JavaScript run-time environment. The information in this guide is organized as follows:
Getting started
An overview of the architecture and components in an XSJS application; some information about required
roles and permissions; and a map to help you nd additional information resources.
Writing server-side JavaScript code
Step-by-step information that shows in detail how to develop the various elements that make up an XS
JavaScript application, including the libraries and application programming interfaces (APIs). The
information provided uses tasks and tutorials to explain how to develop the SAP HANA development
objects. Where appropriate, you can also nd 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.
Note
You can nd details of the individual XS JavaScript APIs and additional information about recommended
usage in the SAP HANA XS JavaScript API Reference on the SAP Help Portal.
4
P U B L I C
SAP HANA XS JavaScript Reference
SAP HANA XS JavaScript Reference
2 Getting Started with XS JavaScript
SAP HANA XS Javascript (XSJS) is a language that can be used by application developers to create native SAP
HANA applications that expose data to UI clients on request.
The application developer denes the business logic that is used to expose data in response to client requests
via HTTP. This guide takes you through the tasks required to use the XS JavaScript syntax to dene the
services that comprise your business logic, for example:
Create applications using XS JavaScript
Create reusable XS JavaScript libraries
Make use of the XS JavaScript application programming interface (API)
Debug XS JavaScript
Trace XS JavaScript applications
This SAP HANA XS JavaScript Reference also provides code examples that illustrate how to use the XS
JavaScript classes and methods.
Building the data model is the rst step in the overall process of developing applications that provide access to
the SAP HANA database. When you have created the underlying data persistence model, application
developers can build the application services that expose selected elements of the data model to client
application by means of so-called “data end-points”. The client applications bind UI controls such as buttons or
charts and graphs to the application services which in turn retrieve and display the requested data.
Prerequisites
Before you can start using XS JavaScript to dene the applications that represent your business logic, you
need to ensure that the following prerequisites are met:
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 XS JavaScript artifacts so that the newly created les can be
committed to (and synchronized with) the repository.
2.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.
SAP HANA XS JavaScript Reference
Getting Started with XS JavaScript
P U B L I C 5
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 dened in server-side (XS) JavaScript or SQLScript
UI rendering occurs completely in the client (browser, mobile applications)
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-ow logic with SAP HANA XS:
OData
Validation models for OData services can be written in XS JavaScript or SQLScript
6
P U B L I C
SAP HANA XS JavaScript Reference
Getting Started with XS JavaScript
Server-Side JavaScript (XSJS)
HTTP requests are implemented directly in XS JavaScript
XMLA
Client UI/Front-end technology:
HTML5 / SAPUI5
Client-side JavaScript
The development scenarios for native application development are aimed at the following broadly dened
audiences:
Target Development Audience for Native SAP HANA Applications
Audience
Language Tools Development Artifacts
Database developers SQLScript, CDS, hdb*
SAP
SAP HANA studio
SAP HANA Web-
based Workbench
Database tables, views, procedures;
user-dened functions (UDF) and trig
gers; analytic objects; data authoriza
tion…
Application developers:
Professional (XS JS)
Casual/business
XS JavaScript, OData,
SQLScript, …
SAP HANA studio
SAP HANA Web-
based Workbench
Control-ow logic, data services, calcula
tion logic…
UI/client developers SAPUI5, JavaScript, …
SAP HANA studio
SAP HANA Web-
based Workbench
UI shell, navigation, themes (look/feel),
controls, events, …
Related Information
Database Development Scenarios
Professional Application Development Scenarios [page 14]
UI Client-Application Development Scenarios
2.2 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 8]
SAP HANA XS Advanced Model [page 9]
SAP HANA XS JavaScript Reference
Getting Started with XS JavaScript
P U B L I C 7
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
Note
To provide access to the repository for application developers, you can use a predened 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 denes 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 predened 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.
8
P U B L I C
SAP HANA XS JavaScript Reference
Getting Started with XS JavaScript
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 sap.hana.xs.ide.roles::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
sap.hana.xs.debugger::Debugger. In addition, the section debugger with the parameter enabled and the
value true must be added to the le xsengine.inile, 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)
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 dene 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
Assign Repository Package Privileges
SAP HANA Web-Based Development Workbench
SAP HANA XS JavaScript Reference
Getting Started with XS JavaScript
P U B L I C 9
2.3 Developer Information Map
The developer information road map is designed to help developers nd the information they need in the
extensive library of user and reference documentation currently available for development projects in SAP
HANA extended application services (SAP HANA XS).
With such a wide variety of people needing to nd such a broad range of information about so many dierent
tasks, it is sometimes not easy to know what information is available or where to look to nd it. This guide
provides a map to help you locate information about a particular application-development topic; the guide is
designed to help you navigate the SAP HANA XS documentation landscape by looking at the information
available for the SAP HANA developer from the following perspectives:
The application development life cycle
The application-development process
SAP HANA developer library
Application development tasks in SAP HANA
Application development scenarios
Tip
For more information, see the Related Information below.
Related Information
Application Development in SAP HANA XS
The SAP HANA XS Application-Development Journey
SAP HANA Developer Information by Guide [page 10]
SAP HANA Developer Information by Task [page 11]
SAP HANA Developer Information by Scenario [page 12]
2.3.1 SAP HANA Developer Information by Guide
The design and organization of the SAP HANA developer library makes it easy to use the name of a guide to
nd the relevant information.
The SAP HANA developer library includes a selection of guides that describe the complete application-
development process, from dening user roles, privileges, and data models through application setup to UI
design and testing; the information available covers background and concepts, task-based tutorials, and
detailed reference material.
The SAP HANA developer library also includes a selection of reference guides that describe the various
languages that application developers can use to dene the underlying data model (SQL, CDS), the application
business logic (Java, JavaScript, Python), or the client interface (SAPIU5).
The high-level steps required to complete the process of developing an application for SAP HANA extended
application services depend on the target SAP HANA XS run-time platform to which you want to deploy the
10
P U B L I C
SAP HANA XS JavaScript Reference
Getting Started with XS JavaScript
application, for example, XS classic or XS advanced. The listed topics include graphics with links to much more
information about each of the steps in the development process for the following application-development
platforms:
The XS Advanced Application-Development Process
The XS Classic Application-Development Process
Related Information
SAP HANA Application Development Guides
SAP HANA Developer Language Reference Guides
2.3.2 SAP HANA Developer Information by Task
The design and organization of the SAP HANA developer documentation library enables easy access to
information according to the particular development task to be performed, for example, creating a view or
procedure, or setting up an application project.
The SAP HANA developer can make use of a large number of guides that include information describing the
complete application-development process. There is also a huge amount of reference material available, for
example, describing the SQL and SQLScript language and syntax or the options available for coding Core Data
Services (CDS).
The topics in this section include graphics that make it easy to nd information about how to perform a specic
task in a particular development area, for example, setting up the persistence model; creating an XS JavaScript
or OData service, building client user interfaces, or managing the development life cycle. The graphics are
interactive; you can use them to jump directly to the information describing the task you want to perform. The
tasks are split according to the following development areas:
Common database-development tasks
Build data-persistence and analytic models; create procedures, synonyms, and user-dened functions
(UDF), etc.
SAP HANA Analytic-Modeling Development Tasks
Create artifacts for use in the analytic model, for example, calculation views, analytic privileges,
hierarchies, and so on.
Common application-development tasks
Create OData services; build Java, JavaScript, Python, or other custom-language modules; maintain
application business-logic code; set up security artifacts, etc.
Client (front-end) user-interface development tasks
Build SAPUI5 applications; create UI views; bind data to UI event handlers; consume data and services with
SAPUI5, etc.
Related Information
SAP HANA Database-Artifact Development Tasks
SAP HANA XS JavaScript Reference
Getting Started with XS JavaScript
P U B L I C 11
SAP HANA Analytic-Modeling Development Tasks
SAP HANA XS Application Artifact-Development Tasks
SAP HANA XS Client User-Interface-Artifact Development Tasks
2.3.3 SAP HANA Developer Information by Scenario
The SAP HANA developer documentation library enables easy access to information according to the
underlying development scenario, for example, database development or coding the application business-
logic.
The SAP HANA developer can make use of a large number of guides that include information describing the
complete application-development process from the perspective of the development scenario, for example,
database development, application development, client UI design and testing, or security considerations; the
information available covers background and concepts, task-based tutorials, and detailed reference material.
Tip
The particular scenario you select can be based on the underlying development area you are assigned to,
the choice of programing language, the required development objects, or the tools you want to use.
The information in this section indicates where to nd information based on the development scenario you
choose, for example:
Database development
Application business-logic development
Client user-interface design
Application security conguration and maintenance
Related Information
SAP HANA Database Development Scenarios
SAP HANA Application-Development Scenarios
SAP HANA Client User-Interface Development Scenarios
SAP HANA Application Security Scenarios
2.3.3.1 Developer Scenarios
The possibility to run application specic 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
12
P U B L I C
SAP HANA XS JavaScript Reference
Getting Started with XS JavaScript
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)
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 XS JavaScript Reference
Getting Started with XS JavaScript
P U B L I C 13
SAP HANA Applications and Development Languages
2.3.3.2 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 dene 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 nd the information that is required to perform the task.
Typical Application-Development Tasks
Task
Details Information Source
Create an XSJS service:
Extract data from SAP HANA
Control application response
Bind to a UI control/event
Context, examples, libraries, debug
ging, implementation, …
SAP HANA Developer Guide for SAP
HANA Studio (XS classic)
Function code, syntax… SAP HANA XS JavaScript Reference (XS
classic)
SQL code, syntax, … SAP HANA SQLScript Reference
UI controls, events… SAPUI5 Demo Kit (version 1.28)
14 P U B L I C
SAP HANA XS JavaScript Reference
Getting Started with XS JavaScript
Task Details Information Source
Create an OData service (for example,
to bind a UI control/event to existing
data tables or views)
Context, service syntax, examples, li
braries, debugging, implementation, …
SAP HANA Developer Guide for SAP
HANA Studio
Query options, syntax…
OData Reference
UI controls, events… SAPUI5 Demo Kit (version 1.28)
SAP HANA XS JavaScript Reference
Getting Started with XS JavaScript
P U B L I C 15
3 Writing Server-Side JavaScript Code
SAP HANA Extended Application Services (SAP HANA XS) provide applications and application developers
with access to the SAP HANA database using a consumption model that is exposed via HTTP.
In addition to providing application-specic consumption models, SAP HANA XS also host system services that
are part of the SAP HANA database, for example: search services and a built-in Web server that provides
access to static content stored in the SAP HANA repository.
The consumption model provided by SAP HANA XS focuses on server-side applications written in JavaScript.
Applications written in server-side JavaScript can make use of a powerful set of specially developed API
functions, for example, to enable access to the current request session or the database. This section describes
how to write server-side JavaScript code that enables you to expose data, for example, using a Web Browser or
any other HTTP client.
3.1 Data Access with JavaScript in SAP HANA XS
In SAP HANA Extended Application Services, the persistence model (for example, tables, views and stored
procedures) is mapped to the consumption model that is exposed via HTTP to clients - the applications you
write to extract data from SAP HANA.
You can map the persistence and consumption models in the following way:
Application-specic code
Write code that runs in SAP HANA application services. Application-specic code (for example, server-side
JavaScript) is used in SAP HANA application services to provide the consumption model for client
applications.
Applications running in SAP HANA XS enable you to accurately control the ow of data between the
presentational layer, for example, in the Browser, and the data-processing layer in SAP HANA itself, where the
calculations are performed, for example in SQL or SQLScript. If you develop and deploy a server-side
JavaScript application running in SAP HANA XS, you can take advantage of the embedded access to SAP
HANA that SAP HANA XS provides; the embedded access greatly improves end-to-end performance.
16
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
3.2 Using Server-Side JavaScript in SAP HANA XS
SAP HANA application services (XS server) supports server-side application programming in JavaScript. The
server-side application you develop can use a collection of JavaScript APIs to expose authorized data to client
requests, for example, to be consumed by a client GUI such as a Web browser or any other HTTP client.
The functions provided by the JavaScript APIs enable server-side JavaScript applications not only to expose
data but to update, insert, and delete data, too. You can use the JavaScript APIs to perform the following
actions:
Interact with the SAP HANA XS runtime environment
Directly access SAP HANA database capabilities
Interact with services on dened HTTP destinations.
JavaScript programs are stored in the repository along with all the other development resources. When the
programs are activated, the code is stored in the repository as a runtime object.
Tip
To enable the Web Browser to display more helpful information if your JavaScript code causes an HTTP
500 exception on the SAP HANA XS Web server, ask someone with administrator privileges to start the
SAP HANA studio's Administration Console perspective and add the parameter developer_mode to the
xsengine.ini httpserver section of the Conguration tab and set it to true.
Related Information
Write XS Server-Side JavaScript [page 17]
JavaScript Security Considerations [page 20]
3.2.1 Tutorial: Write Server-Side JavaScript Application Code
SAP HANA Extended Application Services (SAP HANA XS) supports server-side application programming in
JavaScript. The server-side application you develop uses JavaScript APIs to expose authorized data to client
requests, for example, for consumption by a client GUI such as a Web browser, SAPUI5 applications, or mobile
clients.
Prerequisites
Access to a running SAP HANA system.
Access to SAP HANA studio
Access to an SAP HANA Repository workspace
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 17
Access to a shared project in the SAP HANA Repository where you can create the artifacts required for this
tutorial.
Context
Since JavaScript programs are stored in the SAP HANA Repository, the steps in this task description assume
that you have already created a workspace and a project (of type XS Project), and that you have shared the
project with other members of the development team. To write a server-side JavaScript application, you must
perform the following high-level steps.
Tip
File extensions are important. If you are using SAP HANA studio to create artifacts in the SAP HANA
Repository, the le-creation wizard adds the required le extension automatically and, if appropriate,
enables direct editing of the new le in the corresponding editor.
Procedure
1. Create a root package for your application, for example, helloxsjs.
2. Create an application descriptor for your application and place it in the root package you created in the
previous step.
The application descriptor is the core le that you use to describe an application's availability within SAP
HANA XS. The application-descriptor le has no contents and no name; it only has the le
extension .xsapp.
Note
For backward compatibility, content is allowed in the .xsapp le but ignored.
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.
b. Save the application-descriptor le.
Note
Saving a le in a shared project automatically commits the saved version of the le to the
repository, To explicitly commit a le to the repository, right-click the le (or the project containing
the le) and choose Team Commit from the context-sensitive popup menu.
c. Activate the application-descriptor le in the repository.
Locate and right-click the new application-descriptor le in the Project Explorer view. In the context-
sensitive pop-up menu, choose Team Activate .
3. Create an application-access le and place it in the package to which you want to grant access.
18
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
The application-access le does not have a name; it only has the le extension .xsaccess. The contents
of the .xsaccess le must be formatted according to JavaScript Object Notation (JSON) rules and
associated with the package the le belongs to. The rules dened in the
.xsaccess le apply to the
package it resides in as well as any subpackages lower in the package hierarchy.
a. In the Project Explorer view, right-click the folder where you want to create the new application-access
le 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 le for your new XSJS application:
{
"exposed" : true,
"authentication" : { "method": "Form" },
"prevent_xsrf" : true,
}
Note
These settings allows data to be exposed, require logon authentication to access the exposed data,
and help protect against cross-site request-forgery (XSRF) attacks.
c. Save and activate the application-access le in the repository.
4. Create the server-side JavaScript (XSJS) les that contain the application logic.
Server-side JavaScript les have the le sux .xsjs, for example, hello.xsjs and contain the code that
is executed when SAP HANA XS handles a URL request.
a. In the Project Explorer view, right-click the folder where you want to create the new XSJS le and
choose
New Other SAP HANA Application Development XS JavaScript File in the context-
sensitive popup menu.
b. Using the wizard, enter the following content in the .xsjs le for your new XSJS application:
$.response.contentType = "text/plain";
$.response.setBody( "Hello, World!");
c. Save and activate the XSJS le in the repository.
5. Check the layout workspace.
Your application package structure should have a structure that looks like the following example:
.
\
helloxsjs
\
.xsapp
.xsaccess
.xsprivileges // optional
hello.xsjs
6. Save and activate the changes and additions you made.
7. View the results in a Web browser.
The SAP HANA XS Web server enables you to view the results immediately after activation in the
repository, for example: http://<SAPHANA_hostname>:80<DB_Instance_Number>/helloxsjs/
hello.xsjs
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 19
3.2.1.1 JavaScript Editor
You can write server-side JavaScript using the SAP HANA studio JavaScript editor, which provides syntax
validation, code highlighting and code completion.
The SAP HANA studio's JavaScript editor includes the JSLint open-source library, which helps to validate
JavaScript code. The editor highlights any code that does not conform to the JSLint standards.
To congure the JSLint library and determine which validations are performed, go to: Window Preferences
SAP HANA Application Development JSLint . In the preferences window, each JSLint setting is followed
by the corresponding JSLint command name, which you can use to lookup more information on the JSLint Web
site.
Tip
To disable all JSLint validations for les in a specic project, right-click the project and choose Disable
JSLint.
Related Information
http://www.jslint.com/lint.html
3.2.1.2 Server-Side JavaScript Security Considerations
If you choose to use server-side JavaScript to write your application code, you need to bear in mind the
potential for (and risk of) external attacks such as cross-site scripting and forgery, and insucient
authentication.
The following list illustrates the areas where special attention is required to avoid security-related problems
when writing server-side JavaScript. Each of the problems highlighted in the list is described in detail in its own
dedicated section:
SSL/HTTPS
Enable secure HTTP (HTTPS) for inbound communication required by an SAP HANA application.
Injection aws
In the context of SAP HANA Extended Application Services (SAP HANA XS) injection aws concern SQL
injection that modies the URL to expand the scope of the original request.
Cross-site scripting (XSS)
Web-based vulnerability that involves an attacker injecting JavaScript into a link with the intention of
running the injected code on the target computer.
Broken authentication and session management
Leaks or aws in the authentication or session management functions allow attackers to impersonate
users and gain access to unauthorized systems and data.
Insecure direct object references
An application lacks the proper authentication mechanism for target objects.
20
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
Cross-site request forgery (XSRF)
Exploits the trust boundaries that exist between dierent Web sites running in the same web browser
session.
Incorrect security conguration
Attacks against the security conguration in place, for example, authentication mechanisms and
authorization processes.
Insecure cryptographic storage
Sensitive information such as logon credentials is not securely stored, for example, with encryption tools.
Missing restrictions on URL Access
Sensitive information such as logon credentials is exposed.
Insucient transport layer protection
Network trac can be monitored, and attackers can steal sensitive information such as logon credentials
or credit-card data.
Invalid redirects and forwards
Web applications redirect users to other pages or use internal forwards in a similar manner.
XML processing issues
Potential security issues related to processing XML as input or to generating XML as output
Related Information
SSL/HTTPS [page 22]
Injection aws [page 22]
Cross-site scripting (XSS) [page 24]
Broken authentication and session management [page 24]
Insecure direct object references [page 25]
Cross-site request forgery (XSRF) [page 25]
Incorrect security conguration [page 27]
Insecure cryptographic storage [page 28]
Missing restrictions on URL Access [page 28]
Insucient transport layer protection [page 29]
XML processing issues [page 31]
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 21
3.2.1.2.1 Server-Side JavaScript: SSL/HTTPS
If you choose to use server-side JavaScript to write your application code, you need to bear in mind the
potential for (and risk of) external attacks such as cross-site scripting and forgery, and insucient
authentication. You can set up SAP HANA to use secure HTTP (HTTPS).
SSL/HTTPS Problem
Incoming requests for data from client applications use secure HTTP (HTTPS), but the SAP HANA system is
not congured to accept the HTTPS requests.
SSL/HTTPS Recommendation
Ensure the SAP Web Dispatcher is congured to accept incoming HTTPS requests. For more information, see
the SAP HANA Security Guide.
Note
The HTTPS requests are forwarded internally from the SAP Web Dispatcher to SAP HANA XS as HTTP
(clear text).
Tip
For more information about security in SAP HANA, see the SAP HANA Security Guide.
3.2.1.2.2 Server-Side JavaScript: Injection Flaws
If you choose to use server-side JavaScript to write your application code, you need to bear in mind the
potential for (and risk of) injection aws. Typically, injection aws concern SQL injection and involve modifying
the URL to expand the scope of the original request.
The XS JavaScript API provides a number of dierent ways to interact with the SAP HANA database by using
SQL commands. By default, these APIs allow you to read data, but they can also be used to update or delete
data, and even to grant (or revoke) access rights at runtime. As a general rule, it is recommended to write a
query which is either a call to an SQLScript procedure or a prepared statement where all parameters specied
in the procedure or statement are escaped by using either setString or setInt, as illustrated in the
examples provided in this section. Avoid using dynamic SQL commands with parameters that are not escaped.
22
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
Injection Flaws Problem
In the context of SAP HANA XS, injection aws mostly concern SQL injection, which can occur in the SAP
HANA XS JavaScript API or SQL script itself (both standard and dynamic). For example, the URL http://
xsengine/customer.xsjs?id=3 runs the code in the JavaScript le customer.xsjs shown below:
var conn = $.db.getConnection();
var pstmt = conn.prepareStatement( " SELECT * FROM accounts WHERE custID='" +
$.request.parameters.get("id"));
var rs = pstmt.executeQuery();
By modifying the URL, for example, to http://xsengine/customer.xsjs?id=3 'OR 1=1', an attacker
can view not just one account but all the accounts in the database.
Note
SAP HANA XS applications rely on the authorization provided by the underlying SAP HANA database.
Users accessing an SAP HANA XS based application require the appropriate privileges on the database objects
to execute database queries. The SAP HANA authorization system will enforce the appropriate authorizations.
This means that in those cases, even if the user can manipulate a query, he will not gain more access than is
assigned to him through roles or privileges. Dener mode SQL script procedures are an exception to this rule
that you need to take into consideration.
Injection Flaws Recommendation
To prevent injection aws in the JavaScript API, use prepared statements to create a query and place-holders
to ll with results of function calls to the prepared-statement object; to prevent injection aws in standard SQL
Script, use stored procedures that run in caller mode; in caller mode, the stored procedures are executed with
the credentials of the logged-on HANA user. Avoid using dynamic SQL if possible. For example, to guard against
the SQL-injection attack illustrated in the problem example, you could use the following code:
var conn = $.db.getConnection();
var pstmt = conn.prepareStatement( " SELECT * FROM accounts WHERE custID=?' );
pstmt.setInt(1, $.request.parameters.get("id"), 10);
var rs = pstmt.executeQuery();
Prepared statements enable you to create the actual query you want to run and then create several
placeholders for the query parameters. The placeholders are replaced with the proper function calls to the
prepared statement object. The calls are specic for each type in such a way that the SAP HANA XS JavaScript
API is able to properly escape the input data. For example, to escape a string, you can use the setString
function.
Tip
For more information about security in SAP HANA, see the SAP HANA Security Guide and the SAP HANA
SQL System Views and Reference.
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 23
3.2.1.2.3 Server-Side JavaScript: Cross-Site Scripting
If you use server-side JavaScript to write your application code, bear in mind the potential for (and risk of)
cross-site scripting (XSS) attacks. Cross-site scripting is a Web-based vulnerability that involves an attacker
injecting JavaScript into a link with the intention of running the injected code on the target computer.
Cross-Site Scripting Problem
The vulnerability to cross-site scripting attacks comes in the following forms:
Reected (non-persistent)
Code aects individual users in their local Web browser
Stored (persistent)
Code is stored on a server and aects all users who visit the served page
A successful cross-site scripting attack could result in a user obtaining elevated privileges or access to
information that should not be exposed.
Cross-Site Scripting Recommendation
Since there are currently no libraries provided by the standard SAP HANA XS JavaScript API to provide proper
escaping, we recommend not to write custom interfaces but to rely on well-tested technologies supplied by
SAP, for example, OData or JSON together with SAPUI5 libraries.
Tip
For more information about security in SAP HANA, see the SAP HANA Security Guide.
3.2.1.2.4 Server-Side JavaScript: Broken Authentication
If you choose to use server-side JavaScript to write your application code, you need to bear in mind the
potential for (and risk of) attack against authentication infrastructure. Leaks or aws in the authentication or
session management functions allow attackers to impersonate users and gain access to unauthorized systems
and data.
Authentication Problem
Leaks or aws in the authentication or session management functions allow attackers to impersonate users;
the attackers can be external as well as users with their own accounts to obtain the privileges of those users
they impersonate.
24
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
Authentication Recommendation
Use the built-in SAP HANA XS authentication mechanism and session management (cookies). For example,
use the "authentication" keyword to enable an authentication method and set it according to the
authentication method you want implement, for example: SAP logon ticket, form-based, or basic (user name
and password) in the application's .xsaccess le, which ensures that all objects in the application path are
available only to authenticated users.
Tip
For more information about security in SAP HANA, see the SAP HANA Security Guide.
3.2.1.2.5 Server-Side JavaScript: Insecure Object
Reference
If you choose to use server-side JavaScript to write your application code, you need to bear in mind the
potential for (and risk of) attacks using insecure references to objects.
Object Reference Problem
An SAP HANA XS application is vulnerable to insecure direct object reference if the application lacks the proper
authentication mechanism for target objects.
Object Reference Recommendation
Make sure that only authenticated users are allowed to access a particular object. In the context of SAP HANA
XS, use the "authentication" keyword to enable an authentication method and set it according to the
authentication method you implement, for example: SAP logon ticket, form-based, or basic (user name and
password) in the application's .xsaccess le, which ensures that all objects in the application path are
available only to authenticated users.
Tip
For more information about security in SAP HANA, see the SAP HANA Security Guide.
3.2.1.2.6 Server-Side JavaScript: Cross-Site Request
Forgery
If you choose to use server-side JavaScript to write your application code, you need to bear in mind the
potential for (and risk of) cross-site request forgery (XSRF). Cross-site scripting is a web-based vulnerability
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 25
that exploits the trust boundaries that exist between dierent websites running in the same web browser
session.
Cross-Site Request-Forgery Problem
Since there are no clear trust boundaries between dierent Web sites running in the same Web-browser
session, an attacker can trick users (for example, by luring them to a popular Web site that is under the
attacker's control) into clicking a specic hyperlink. The hyperlink displays a Web site that performs actions on
the visitor's behalf, for example, in a hidden iframe. If the targeted end user is logged in and browsing using an
account with elevated privileges, the XSRF attack can compromise the entire Web application.
Cross-Site Request-Forgery Recommendation
SAP HANA XS provides a way to include a random token in the POST submission which is validated on the
server-side. Only if this token is non-predictable for attackers can one prevent cross-site, request-forgery
attacks. The easiest way to prevent cross-site, request-forgery attacks is by using the standard SAP HANA XS
cookie. This cookie is randomly and securely generated and provides a good random token which is
unpredictable by an attacker ($.session.getSecurityToken()).
To protect SAP HANA XS applications from cross-site request-forgery (XSRF) attacks, make sure you always
set the prevent_xsrf keyword in the application-access (.xsaccess) le to true, as illustrated in the following
example:
{
"prevent_xsrf" : true
}
The prevent_xsrf keyword prevents the XSRF attacks by ensuring that checks are performed to establish that a
valid security token is available for given Browser session. The existence of a valid security token determines if
an application responds to the client's request to display content. A security token is considered to be valid if it
matches the token that SAP HANA XS generates in the backend 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.
The following client-side JavaScript code snippet show how to use the HTTP request header to fetch, check,
and apply the XSRF security token required to protect against XSRF attacks.
<html>
<head>
<title>Example</title>
<script id="sap-ui-bootstrap" type="text/javascript"
src="/sap/ui5/1/resources/sap-ui-core.js"
data-sap-ui-language="en"
data-sap-ui-theme="sap_goldreflection"
data-sap-ui-libs="sap.ui.core,sap.ui.commons,sap.ui.ux3,sap.ui.table">
</script>
26
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
<script type="text/javascript" src="/sap/ui5/1/resources/jquery-sap.js"></
script>
<script>
function doSomething() {
$.ajax({
url: "logic.xsjs",
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRF-Token", "Fetch");
},
success: function(data, textStatus, XMLHttpRequest) {
var token = XMLHttpRequest.getResponseHeader('X-CSRF-Token');
var data = "somePayLoad";
$.ajax({
url: "logic.xsjs",
type: "POST",
data: data,
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRF-Token", token);
},
success: function() {
alert("works");
},
error: function() {
alert("works not");
}
});
}
});
}
</script>
</head>
<body>
<div>
<a href="#" onClick="doSomething();">Do something</a>
</div>
</body>
</html>
Tip
For more information about security in SAP HANA, see the SAP HANA Security Guide.
3.2.1.2.7 Server-Side JavaScript: Security Misconguration
If you choose to use server-side JavaScript to write your application code, you need to bear in mind the
potential for (and risk of) attacks against the security conguration in place, for example, authentication
mechanisms and authorization processes.
Insecure Conguration Problem
No or an inadequate authentication mechanism has been implemented.
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 27
Insecure Conguration Recommendation
Applications should have proper authentication in place, for example, by using SAP HANA built-in
authentication mechanisms and, in addition, the SAP HANA XS cookie and session handling features.
Application developers must also consider and control which paths are exposed by HTTP to the outside world
and which of these paths require authentication.
Tip
For more information about security in SAP HANA, see the SAP HANA Security Guide.
3.2.1.2.8 Server-Side JavaScript: Insecure Storage
If you choose to use server-side JavaScript to write your application code, you need to bear in mind the
potential for (and risk of) attacks against the insecure or lack of encryption of data assets.
Storage-Encryption Problem
Sensitive information such as logon credentials is exposed.
Storage-Encryption Recommendation
To prevent unauthorized access, for example, in the event of a system break-in, data such as user logon
credentials must be stored in an encrypted state.
Tip
For more information about security in SAP HANA, see the SAP HANA Security Guide.
3.2.1.2.9 Server-Side JavaScript: Missing URL Restrictions
If you choose to use server-side JavaScript to write your application code, you need to bear in mind the
potential for (and risk of) unauthorized access to URLs.
URL Access Problem
Unauthenticated users have access to URLs that expose condential (unauthorized) data.
28
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
URL Access Recommendation
Make sure you have addressed the issues described in "Broken Authentication and Session Management" and
"Insecure Direct Object References". In addition, check if a user is allowed to access a specic URL before
actually executing the code behind that requested URL. Consider putting an authentication check in place for
each JavaScript le before continuing to send any data back to the client's Web browser.
Tip
For more information about Security in SAP HANA, see the SAP HANA Security Guide.
3.2.1.2.10 Server-Side JavaScript: Transport Layer Protection
If you choose to use server-side JavaScript to write your application code, you need to bear in mind the
potential for (and risk of) insucient protection of the transport layer.
Transport Layer Protection Problem
Without transport-layer protection, the user's network trac can be monitored, and attackers can steal
sensitive information such as logon credentials or credit-card data.
Transport Layer Protection Recommendation
Turn on transport-layer protection in SAP HANA XS; the procedure is described in the SAP HANA security
guide.
Tip
For more information about security in SAP HANA, see the SAP HANA Security Guide.
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 29
3.2.1.2.11 Server-Side JavaScript: Invalid Redirection
If you use server-side JavaScript to write your application code, bear in mind the potential for (and risk of)
redirection and internal fowarding from the requested Web page.
Invalid Redirection Problem
Web applications frequently redirect users to other pages or use internal forwards in a similar manner.
Sometimes the target page is specied in an invalid (not permitted) parameter. This enables an attacker to
choose a destination page leading to the possibility of phishing attacks or the spamming of search engines.
Invalid Redirection Recommendation
To prevent invalidated redirects or forwards, application developers should validate the requested destination
before forwarding, for example, by checking if the destination is present in a white list. If the destination URL
specied in the redirection request is not present in the white list, the redirection is refused.
Tip
Avoid using redirection if you cannot control the nal destination.
Alternatively, you can refuse to allow any direct user input; instead, the input can be used to determine the nal
destination for the redirection, as illustrated in the following example:
var destination = $.request.parameters.get("dest");
switch (destination) {
case "1": $.response.headers.set("location", "http://
FirstWhitelistedURL.com"); break;
case "2": $.response.headers.set("location", "http://
SecondWhitelistedURL.com"); break;
default: $.response.headers.set("location", "http://
DefaultWhitelistedURL.com");
}
Tip
For more information about security in SAP HANA, see the SAP HANA Security Guide.
30
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
3.2.1.2.12 Server-Side JavaScript: XML Processing Issues
If you choose to use server-side JavaScript to write your application code, you need to bear in mind the
potential for (and risk of) attacks aimed at the process used to parse XML input and generate the XML output.
XML Processing Problem
There are several potential security issues related to processing XML as input or to generating XML as output.
In addition, problems with related technologies (for example, XSL Transformations or XSLT) can enable the
inclusion of other (unwanted) les.
XML Processing Recommendation
Turn on transport-layer protection in SAP HANA XS; the procedure is described in the SAP HANA security
guide.
Bear in mind the following rules and suggestions when processing or generating XML output:
When processing XML that originates from an untrusted source, disable DTD processing and entity
expansion unless strictly required. This helps prevent Billion Laugh Attacks (Cross-Site Request Forgery),
which can bring down the processing code and, depending on the conguration of the machine, an entire
server.
To prevent the inclusion (insertion) of unwanted and unauthorized les, restrict the ability to open les or
URLs even in requests included in XML input that comes from a trusted source. In this way, you prevent the
disclosure of internal le paths and internal machines.
Ensure proper limits are in place on the maximum amount of memory that the XML processing engine can
use, the amount of nested entities that the XML code can have, and the maximum length of entity names,
attribute names, and so on. This practice helps prevent the triggering of potential issues.
Tip
For more information about security in SAP HANA, see the SAP HANA Security Guide.
3.3 Using Server-Side JavaScript Libraries
The elements dened in normal server-side JavaScript programs cannot be accessed from other JavaScript
programs. To enable the reuse of program elements, SAP HANA Extended Application Services support server-
side JavaScript libraries.
Server-side JavaScript libraries are a special type of JavaScript program that can be imported and called in
other JavaScript programs. You can use JavaScript libraries to perform simple, repetitive tasks, for example, to
handle forms and form date, to manipulate date and time strings, to parse URLs, and so on.
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 31
Note
JavaScript libraries are internally developed extensions for SAP HANA.
The following example shows how to import a JavaScript mathematics library using the import function:
// import math lib
$.import("sap.myapp.lib","math");
// use math lib
var max_res = $.sap.myapp.lib.math.max(3, 7);
The import function requires the following parameters:
Package name
Full name of the package containing the library object you want to import, for example, sap.myapp.lib
Library name
Name of the library object you want to import, for example, math
Note
Restrictions apply to the characters you can use in the names of JavaScript libraries and application
packages. Permitted characters are: upper- and lower-case letters (Aa-Zz), digits 0-9, and the dollar sign
($).
The standard JavaScript limitations apply to the characters you can use in either the name of the XSJS library
you create or the name of the package where the library is deployed. For example, you cannot use the hyphen
(-) in the name of an XSJS library or, if you are referencing the library, the name of a package in the application
package path. To prevent problems with activation of the object in the SAP HANA repository, you must follow
the standard rules for accessing JavaScript property objects by name. The following example, shows how to
use square brackets and quotes (["<STRING>"]) to access an object whose name uses non-permitted
characters such as a hyphen (-):
// import math lib
$.import("sap.myapp.lib.XS-QGP-SPS7","math");
// use math lib
var max_res = $.sap.myapp.lib["XS-QGP-SPS7"].math.max(3, 7);
Related Information
Import Server-Side JavaScript Libraries [page 33]
Write Server-Side JavaScript Libraries [page 34]
32
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
3.3.1 Import Server-Side JavaScript Libraries
Server-side JavaScript libraries are a special type of JavaScript program that can be imported and called in
other JavaScript programs. You can use JavaScript libraries to perform simple, repetitive tasks, for example:
handle forms and form date, manipulate date and time strings, parse URLs, and so on.
Context
JavaScript libraries are internally developed extensions for SAP HANA. The libraries exist in the context of a
package, which is referenced when you import the library. The following example of a JavaScript library
displays the word "Hello" along with a name and an exclamation mark as a sux.
var greetingPrefix = "Hello, ";
var greetingSuffix = "!";
function greet (name) {
return greetingPrefix + name + greetingSuffix;
}
Note
This procedure uses the illustrated example JavaScript library to explain what happens when you import a
JavaScript library, for example, which objects are created, when, and where. If you have your own library to
import, substitute the library names and paths shown in the steps below as required.
To import a JavaScript library for use in your server-side JavaScript application, perform the following tasks
Procedure
1. Import the JavaScript library into a JavaScript application.
Open the server-side JavaScript le into which you want to import the JavaScript library.
Use the $.import function, as follows:
$.import("<path.to.your.library.filename>","greetLib");
var greeting = $.<path.to.your.library.filename>.greet("World");
$.response.setBody(greeting);
2. Save and activate the changes to the JavaScript le.
Although the operation is simple, bear in mind the following points:
Additional objects in the package hierarchy
The import operation generates a hierarchy of objects below $ that resemble the library's location in
the repository, for example, for the library path/to/your/library/greetLib.xsjslib, you would
see the following additional object:
$.path.to.your.library.greetLib
Additional properties for the newly generated library object:
$.path.to.your.library.greetLib.greet()
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 33
$.path.to.your.library.greetLib.greetingSuffix
$.path.to.your.library.greetLib.greetingPrefix
Pre-import checks:
It is not possible to import the referenced library if the import operation would override any
predened runtime objects.
Do not import the referenced library if it is already present in the package.
Library context
Imported libraries exist in the context dened by their repository location.
3.3.2 Write Server-Side JavaScript Libraries
Server-side JavaScript libraries are a special type of JavaScript program that can be imported and called in
other JavaScript programs. You can use JavaScript libraries to perform simple, repetitive tasks, for example, to
handle forms and form date, to manipulate date and time strings, to parse URLs, and so on.
Context
JavaScript libraries are internally developed extensions for SAP HANA. However, you can write your own
libraries, too. JavaScript libraries exist in the context of a package, which is referenced when you import the
library. To write a JavaScript library to use in your server-side JavaScript application, perform the following
steps:
Procedure
1. Create the le that contains the JavaScript library you want to add to the package and make available for
import.
In SAP HANA XS, server-side JavaScript libraries have the le extension .xsjslib, for example
greetLib.xsjslib.
a. In the Project Explorer view, right-click the folder where you want to create the new XSJS le and
choose
New Other SAP HANA Application Development XS JavaScript Library File in the
context-sensitive popup menu.
b. Type a name for the new XS JavaScript library le, for example greetLib and choose Finish.
If you are using SAP HANA studio to create artifacts in the SAP HANA Repository, the le creation
wizard adds a separator (.) and the required le extension automatically, for example, .xsjslib.
c. Enter the following content in the greetLib.xsjslibXSJS library le for your new XSJS application.
The following example creates a simple library that displays the word “Hello” along with a supplied
name and adds an exclamation point (!) as a sux.
var greetingPrefix = "Hello, ";
var greetingSuffix = "!";
function greet (name) {
return greetingPrefix + name + greetingSuffix;
34
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
}
2. Save the new JavaScript library.
It is important to remember where the JavaScript library is located; you have to reference the package path
when you import the library.
3. Activate your new library in the repository so that it is available for import by other JavaScript applications.
3.4 Using the Server-Side JavaScript APIs
SAP HANA Extended Application Services (SAP HANA XS) provides a set of server-side JavaScript application
programming interfaces (API) that enable you to congure your applications to interact with SAP HANA.
The SAP HANA XS JavaScript Reference lists all the functions that are available for use when programing
interaction between your application and SAP HANA. For example, you can use the database API to invoke SQL
statements from inside your application, or access details of the current HTTP request for SAP HANA data with
the request-processing API.SAP HANA XS includes the following set of server-side JavaScript APIs:
XS JavaScript Application Programming Interfaces
API
Description
Database Enables access to the SAP HANA by means of SQL statements. For example, you can open a
connection to commit or rollback changes in SAP HANA, to prepare stored procedures (or SQL
statements) for execution or to return details of a result set or a result set's metadata.
Outbound connectivity Enables outbound access to a dened HTTP destination that provides services which an applica
tion can use. For example, you can read the connection details for an HTTP destination, request
data, and set details of the response body. You can also set up an SMTP connection for use by
outgoing multipart e-mails.
Request processing
Enables access to the context of the current HTTP request, for example, for read requests and
write responses. You can use the functions provided by this API to manipulate the content of the
request and the response.
Session Enables access to the SAP HANA XS session, for example, to determine the language used in the
session or if a user has the privileges required to run an application.
Job Schedule Enables access to the job-scheduling interface which allows you to dene and trigger recurring
tasks that run in the background. The XS jobs API allows you to add and remove schedules from
jobs.
Security
Enables access to the $.security.crypto namespace and the classes AntiVirus and
Store, which provide tools that allow you to congure a secure store, set up anti-virus scans,
and generate hashes..
Trace Enables access to the various trace levels you can use to generate and log information about ap
plication activity. You can view trace les in the diagnosis Files tab of the SAP HANA studio's
Administration perspective.
Utilities Enables access to utilities that you can use to parse XML and manipulate Zip archives, for exam
ple, to zip and unzip les, add and remove entries from Zip archives, and encrypt Zip archives
with password protection.
XS Data Services Provides access to a library of JavaScript utilities, which can be used to enable server-side Java
Script applications to consume data models that are dened using Core Data Services.
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 35
API Description
XS Procedures Provides access to a library of JavaScript utilities, which can be used to enable server-side Java
Script applications to call SAP HANA stored procedures as if the procedures were JavaScript
functions.
Restriction
XSProc is intended only for use with database connections made with the old $.db API. It
is not recommended to use
XSProc with $.hdb connections. For $.hdb connections, use
$hdb.loadProcedure instead.
Database API
The SAP HANA XS Database API ($.hdb) provides tools that enable simple and convenient access to the
database.
Caution
The $.hdb namespace is intended as a replacement for the older $.db namespace. Since dierent
database connections are used for the $.hdb and $.db APIs, avoid using both APIs in a single http-
request, for example, to update the same tables as this can lead to problems, including deadlocks.
You can use the Database API for the following operations
$.hdb.Connection
Establish a connection to the SAP HANA database
$.hdb.ProcedureResult
Represents the result of a stored procedure call to the SAP HANA database
$.hdb.ResultSet
Represents the result of a database query
The following example shows how to use the database API to connect to the SAP HANA database, commit
some changes, and end the current transaction.
Note
By default, auto-commit mode is disabled, which means that all database changes must be explicitly
committed.
var connection = $.hdb.getConnection();
connection.executeUpdate('UPDATE "DB_EXAMPLE"."ICECREAM" SET QUANTITY=? WHERE
FLAVOR=?', 9, 'CHOCOLATE');
connection.commit();
The following example of usage of the SAP HANA XS database API shows how to establish a connection with
SAP HANA and return a result set from the specied procedure call. The example code assumes that a
procedure exists with the following signature:
PROCEDURE 'DB_EXAMPLE'.icecream.shop::sell(
IN flavor VARCHAR,
36
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
IN quantity INTEGER,
IN payment DECIMAL,
OUT change DECIMAL)
Note that the result can be accessed as if it were a JSON object with a structure similar to the following
example: {change: 1.50, $resultSets:[....]} .
Tip
$resultSets is not enumerable; it does not show up in a for-each loop.
var fnSell = connection.loadProcedure('DB_EXAMPLE', 'icecream.shop::sell');
var result = fnSell('CHOCOLATE', 3, 30.0);
// value of output parameter 'change'
var change = result['change'];
// array of $.hdb.ResultSet returned by the stored procedure
var resultSets = result['$resultSets'];
// iterate over all output parameters.
var params;
for (var outputParam in result) {
params += outputParam + ' ';
}
Outbound API
The Outbound API ($.net) provides tools that you can use to perform the following actions:
$.net.SMTPConnection
For sending $.net.Mail objects by means of an SMTP connection
$.net.Mail
For constructing and sending multipart e-mails
$.net.http
HTTP(s) client (and request) classes for outbound connectivity and an HTTP(s) destination class that hold
metadata, for example: host, port, useSSL.
The following example shows how to use the $.net.SMTPConnection class to send e-mail objects
($.net.Mail) by means of an SMTP connection object:
smtpConnection = new SMTPConnection();
var mail = new $.net.Mail({ sender: "[email protected]",
subject: "Promotion Notice",
subjectEncoding: "UTF-8",
parts: [new $.net.Mail.Part({
type: $.net.Mail.Part.TYPE_TEXT,
contentType: "text/html",
encoding: "UTF-8"
})]
});
for (var i = 0; i < subscribers.length; ++i) {
mail.to = subscribers[i];
mail.parts[0].text = "Dear " + subscribers[i].split("@")[0] + ", \
you have been promoted. Congratulations!";
smtpConnection.send(mail);
}
smtpConnection.close();
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 37
The following example shows how to use the $.net.Mail class to create an e-mail from an XS JavaScript
object and send it to the named recipients:
Note
If mandatory information is missing or an error occurs during the send operation, the mail.send() call
fails and returns an error.
var mail = new $.net.Mail({
sender: {address: "[email protected]"},
to: [{ name: "John Doe", address: "[email protected]", nameEncoding: "US-
ASCII"}, \
{name: "Jane Doe", address: "[email protected]"}],
cc: ["[email protected]", {address: "[email protected]"}],
bcc: [{ name: "Jonnie Doe", address: "[email protected]"}],
subject: "subject",
subjectEncoding: "UTF-8",
parts: [ new $.net.Mail.Part({
type: $.net.Mail.Part.TYPE_TEXT,
text: "The body of the mail.",
contentType: "text/plain",
encoding: "UTF-8",
})]
});
var returnValue = mail.send();
var response = "MessageId = " + returnValue.messageId + ", final reply = " +
returnValue.finalReply;
$.response.status = $.net.http.OK;
$.response.contentType = "text/html";
$.response.setBody(response);
The following example of server-side JavaScript shows how to use the outbound API to get (read) an HTTP
destination. You can also set the contents of the response, for example, to include details of the header, body,
and any cookies. For HTTPs connections you need to maintain a certicate (CA or explicit server certicate) in
a Trust Store; you use the certicate to check the connection against.
var dest = $.net.http.readDestination("inject", "ipsec");
var client = new $.net.http.Client();
var req = new $.web.WebRequest($.net.http.GET, "");
client.request(req, dest);
var response = client.getResponse();
var co = [], he = [];
for(var c in response.cookies) {
co.push(response.cookies[c]);
}
for(var c in response.headers) {
he.push(response.headers[c]);
}
var body = undefined;
if(response.body)
var body = response.body.asString();
$.response.contentType = "application/json";
Tip
You dene the HTTP destination in a text le using keyword=value pairs. You must activate the HTTP
destination in the SAP HANA repository. After activation, you can view details of the HTTP destination in
the SAP HANA XS Administration tool.
38
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
Request-Processing API
The Request-Processing API ($.web) provides access to the body of HTTP request and response entities. For
example, you can use the following classes:
$.web.Body
Represents the body of an HTTP request entity and provides access to the data included in the body of the
HTTP request entity
$.web.EntityList
Represents a list of request or response entities; the EntityList holds WebEntityRequest or
WebEntityResponse objects.
$.web.TupelList
Represents a list of name-value pairs. The TupelList is a container that provides tuples for cookies,
headers, and parameters. A “tuple” is a JavaScript object with the properties “name” and “value”.
$.web.WebRequest
Enables access to the client HTTP request currently being processed
$.web.WebResponse
Enables access to the client HTTP response currently being processed for the corresponding request
object (
$.web.WebEntityRequest
Represents an HTTP request entity and provides access to the entity's metadata and (body) content.
$.web.WebEntityResponse
Represents the HTTP response currently being populated
The following example shows how to use the request-processing API to display the message “Hello World” in a
browser.
$.response.contentType = "text/plain";
$.response.setBody( "Hello, World !");
In the following example, you can see how to use the request-processing API to get the value of parameters
describing the name and vendor ID of a delivery unit (DU) and return the result set in JSON-compliant form.
var duName = $.request.parameters.get("du_name");
var duVendor = $.request.parameters.get("du_vendor");
result = {
content_id : contentId.toString()
};
$.response.status = $.net.http.OK;
$.response.contentType = 'application/json';
$.response.setBody(JSON.stringify(result));
In the following example of use of the request-processing API, we show how to access to the request's meta
data (and body) and, in addition, how to set and send the response.
if($.request.method === $.net.http.GET) {
// get query parameter named id
var qpId = $.request.parameters.get("id");
// handle request for the given id parameter...
var result = handleRequest(qpId);
// send response
$.response.contentType = "plain/test";
$.response.setBody("result: " + result);
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 39
$.response.status = $.net.http.OK;
} else {
// unsupported method
$.response.status = $.net.http.INTERNAL_SERVER_ERROR;
}
Session API
Enables access to the SAP HANA XS session, for example, to determine the language used in the session or
check if a user has the privileges required to run an application.
You can use the XS JavaScript $.session API to request and check information about the currently open
sessions. For example, you can nd out the name of a user who is currently logged on to the database or get
the session-specic security token. The $.session API also enables you to check if a user has sucient
privileges to call an application. The following example checks if the user has the execute privilege that is
required to run an application. If the check reveals that the user does not have the required privilege, an error
message is generated indicating the name of the missing privilege.
if (!$.session.hasAppPrivilege("sap.xse.test::Execute")) {
$.response.setBody("Privilege sap.xse.test::Execute is missing");
$.response.status = $.net.http.INTERNAL_SERVER_ERROR;
}
Job Schedule API
In SAP HANA XS, a scheduled job is created by means of an .xsjob le, a design-time le you commit to (and
activate in) the SAP HANA repository. The .xsjob le can be used to dene recurring tasks that run in the
background; the Job Schedule API allows developers to add and remove schedules from such jobs.
The Job Schedule API provides the following tools:
Job
$.jobs.Job represents a scheduled XS job
JobLog
$.jobs.JobLog provide access to the log entries of a scheduled job
JobSchedules
$.jobs.JobSchedules enables control of an XS job's schedules.
Note
It is not possible to call the $.request and $.response objects as part of an XS job.
The XS jobs API $.jobs.Job enables you to add schedules to (and remove schedules from) jobs dened in
an .xsjob le.
The following example of server-side JavaScript shows how to use the Job Schedule API to add a schedule to a
existing job and delete a schedule from an existing job.
var myjob = new $.jobs.Job({uri:"myJob.xsjob", sqlcc:"sqlcc/otheruser.xssqlcc"});
40
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
// add schedule to a job
var id = myjob.schedules.add({
description: "Added at runtime, run every 10 minutes",
xscron: "* * * * * */10 0",
parameter: {
a: "c"
}
});
// delete a schedule from a job
myjob.schedules.delete({id: id});
If the XS job le referred to in the URI is not in the same package as the XS JavaScript or SQLScript function
being called, you must add the full package path to the XS job le specied in the URI illustrated in line 1 of the
example above, for example, </path/to/package.>MyXSjob.xsjob.
Note
The path specied in </path/to/package.> can be either absolute or relative.
In addition, the SQL connection dened in sqlcc/otheruser.xssqlcc is used to modify the job; it is not
used to execute the job specied in myJob.xsjob.
To understand the cron-like syntax required by the xscron job scheduler, use the following examples:
2013 * * fri 12 0 0
Run the job every Friday in 2013 at 12:00.
* * 3:-2 * 12:14 0 0
Run every hour between 12:00 and 14:00 every day between the third and second-to-last day of the month.
* * * -1.sun 9 0 0
Run the job on the last Sunday of every month at 09:00.
Security API
The SAP HANA XS JavaScript security API $.security includes the $.security.crypto namespace and
the following classes:
$.security.AntiVirus
Scan data with a supported external anti-virus engine
$.security.Store
Store data securely in name-value form
The $.security.crypto namespace includes methods (for example, md5(), sha1(), and sha256()) that
enable you to compute an MD5 or SHA1/256 hash (or HMAC-MD5, HMAC-SHA1, and HMAC-SHA256).
The AntiVirus class includes a method scan() that enables you to set up a scan instance using one of the
supported anti-virus engines. The Store class enables you to set up a secure store for an SAP HANA XS
application; the secure store can be used to store sensitive information either at the application level
(store()) or per user (storeForUser()).
The following code example shows how to use the SAP HANA XS virus-scan interface (VSI) to scan a specic
object type: a Microsoft Word document.
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 41
Note
For more information about which antivirus engines SAP HANA supports, see SAP Note 786179.
var data = //Some data to be checked
var av = new $.security.AntiVirus();
//AV scan data as Word document
av.scan(data, "myDocument.docx");
The following code example shows how to set up a simple scan for data uploads using the SAP HANA XS virus-
scan interface.
//scan a buffer with own "upload" profile
var av = new $.security.AntiVirus("upload");
av.scan(buffer);
The SAP HANA XS $.security.Store API can be used to store data safely and securely in name-value form.
The security API enables you to dene a secure store (in a design-time artifact) for each application and refer
to this design time object in the application coding.
Note
The design-time secure store is a le with the le extension “.xssecurestore”, for example,
localStore.xssecurestore; the secure-store le must include only the following mandatory content:
{}.
SAP HANA XS looks after the encryption and decryption of data and also ensures the persistency of the data.
For the stored data, you can choose between the following visibility options:
Application-wide data visibility
Use store(<parameters>) to ensure that all users of the corresponding application have access to one
secure store where they can share the same data and can decrypt or encrypt data, for example, passwords
for a remote system.
Application-wide data visibility but with user-specic stores separation
Use storeForUser(<parameters>) to ensures that each user of the corresponding application has a
separate container to securely store personal, encrypted data, for example, credit card numbers or
personal-information-number (PIN) codes; the encrypted data can only be decrypted by the owner of the
secure store; the user who encrypted it.
function store() {
var config = {
name: “foo”,
value: “bar”
};
var aStore = new $.security.Store("localStore.xssecurestore");
aStore.store(config);
}
function read() {
var config = {
name: “foo”
};
try {
var store = new $.security.Store("localStore.xssecurestore");
var value = store.read(config);
}
catch(ex) {
//do some error handling
}
42
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
}
Trace API
Enables access to the various trace levels you can use to generate and log information about application
activity. The specied error message is written to the appropriate trace le.
$.trace.error("This is an error message")
You can set the following trace levels:
$.trace.debug(message)
Writes the string dened in (message) to the application trace with debug level
$.trace.error(message)
Writes the string dened in (message) to the application trace with error level
$.trace.fatal(message)
Writes the string dened in (message) to the application trace with fatal level
$.trace.info(message)
Writes the string dened in (message) to the application trace with info level
$.trace.warning(message)
Writes the string dened in (message) to the application trace with warning level
Note
If tracing is enable, messages generated by the $.trace API are logged in the SAP HANA trace le
xsengine_<host>_<Instance>_<#>.trc on the SAP HANA server, for example, in
<installation_path>/<SID>/HDB<nn>/<hostname>/trace. Trace messages with severity status
“warning”, “error” and “fatal” are also written to a similarly named alert le, for example,
xsengine_alert_<host>.trc.
Utilities API
The SAP HANA XS JavaScript Utilities API includes the $.util namespace, which contains the following
classes
$.util.SAXParser
Tools for parsing XML content (for example, strings, array buers, and the content of Web response body
objects)
$.util.Zip
Compression tools for building, modifying, extracting, and encrypting archives
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 43
With the XS JavaScript Utilities API$.util.SAXParser class, you can create a new parser object and parse
the XML content of an XMLstring, an XML array buer, or a $.web.Body object. The following example shows
how to use the XML parsing capabilities of the
$.util.SAXParser class:
Note
You can stop, reset, and resume a parsing operation. If the content to be parsed does not contain XML, the
parser throws an error.
var parser = new $.util.SAXParser();
var xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n\
<!-- this is a note -->\n\
<note noteName='NoteName'>\n\
<to>To</to>\n\
<from>From</from>\n\
<heading>Note heading</heading>\n\
<body>Note body</body>\n\
<note>\n";
var startElementHandlerConcat = "";
var endElementHandlerConcat = "";
var characterDataHandlerConcat = "";
parser.startElementHandler = function(name, atts) {
startElementHandlerConcat += name;
if (name === "note") {
startElementHandlerConcat += " noteName = '" + atts.noteName + "'";
}
startElementHandlerConcat += "\n";
};
parser.endElementHandler = function(name) {
endElementHandlerConcat += name + "\n";
};
parser.characterDataHandler = function(s) {
characterDataHandlerConcat += s;
};
parser.parse(xml);
...
The following code snippet shows how to use the $.util.SAXParser tools to parse the content of a
$.web.Body object.
var body = $.request.body
var parser = new $.util.SAXParser()
//... set handlers
parser.parse(body);
The following encodings are supported:
UTF-8 (default)
UTF-16
US-ASCII
The SAP HANA XS JavaScript Utilities API also includes the$.util.Zip tool, which enables you to perform a
series of actions on Zip archives, for example:
Compress les into (zip) and extract les from (unzip) a Zip archive
Add new entries to, update existing entries in, and remove entries from a Zip archive
Encrypt Zip archives with password protection
The following code illustrates a simple usage of the Zip tool:
var zip = new $.util.Zip("myPassword");
44
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
zip["entry.txt"] = "Two fish are in a tank. One turns to the other and asks 'How
do you drive this thing?'";
$.response.status = $.net.http.OK;
$.response.contentType = "application/zip";
$.response.headers.set("Content-Disposition", "attachment; filename =
Encrypted.zip");
$.response.setBody(zip.asArrayBuffer());
The following code snippets show how to use the $.util.Zip tools to work with Zip le content, for example,
by adding, updating, extracting, and deleting entries. When modeling folder hierarchies, the Zip object behaves
like an associative array; the entry names are the keys (the full paths to the indicated les). In the following
example, we add an entry to a Zip le:
Note
zip["entry1"]” is equivalent to “zip.entry1”.
var zip = new $.util.Zip();
zip["entry1"] = "old entry";
In the following example, we update an entry in a Zip le:
var zip = new $.util.Zip();
zip["entry1"] = "new entry";
In the following example, we extract an entry from a Zip le: if the entry does not exist, this returns undened.
var zip = new $.util.Zip();
var content = zip["entry1"];
In the following example, we delete an entry from a Zip le: if the entry does not exist, nothing happens.
var zip = new $.util.Zip();
delete zip["entry1"];
Note
There is a restriction on the amount of uncompressed data that can be extracted from a Zip archive using
the XS JS utilities API.
When using the XS JS utilities API to extract data from a Zip archive, the maximum amount of uncompressed
data allowed during the extraction process is dened with the parameter
max_uncompressed_size_in_bytes, which you can set in the zip section of the xsengine.ini
conguration le for a given SAP HANA system. If the zip section does not already exist, you must create it
and add the parameter to it, for example, using the SAP HANA Administration Console in SAP HANA studio. If
the parameter max_uncompressed_size_in_bytes is not set, a default value is assumed. The default value
is the value assigned to the property max_runtime_bytes in section jsvm section of the xsengine.ini le.
You can deactivate the global check on the amount of uncompressed data. If the global system
parametermax_uncompressed_size_in_bytes is set to -1, no check is performed on the amount of
uncompressed data generated by an extraction process using the Utilities API, unless there is a specic user
limitation in the XS JavaScript code, for example, with the
maxUncompressedSizeInBytes parameter.
With the $.util.Zip class or the $.util.compression namespace, you can use the property
maxUncompressedSizeInBytes to override the global setting and reduce the amount of uncompressed data
allowed.
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 45
Note
Note that the parameter max_uncompressed_size_in_bytes cannot be used to increase the amount of
uncompressed data allowed beyond the value specied in the global setting.
XS Data Services API
SAP HANA XS Data Services (XSDS) is a collection of tools that includes a native client for Core Data Services
(CDS) and a query builder for SAP HANA Extended Application Services (SAP HANA XS) JavaScript. The XSDS
API provides a high-level abstraction of the database API ($.db, $.hdb) and gives access to SAP HANA
artifacts such as CDS entities or stored procedures. XSDS enables server-side JavaScript applications to
consume data models that are dened using Core Data Services more eciently.
The following example shows how to import a CDS entity and how to update a given entity instance in XSDS
managed mode.
// import CDS client library
var XSDS = $.import("sap.hana.xs.libs.dbutils", "xsds");
// import CDS entity
var MyEntity = XSDS.$importEntity("cds.namespace", "cds_context.cds_entity");
// retrieve entity instance
var instance = MyEntity.$get({ id: 69 });
// update instance
instance.stringProp = "new value";
instance.intProp++;
instance.assocProp.dateProp = new Date();
// persist changes
instance.$save();
The following example shows how to query the database using CDS model data in XSDS unmanaged mode.
// import CDS client library
var XSDS = $.import("sap.hana.xs.libs.dbutils", "xsds");
// import CDS entity
var MyEntity = XSDS.$importEntity("cds.namespace", "cds_context.cds_entity");
// build query
var query = MyEntity.$query();
var projection = query.$project({
stringProp: true,
aliasProp: "aliasName",
assocProp: { dateProp: true }
});
var filter = query.$where({ stringProp: { $like: "A%" } });
// retrieve result
var result = projection.$execute();
// process result
for (var i = 0; i < result.length; i++) {
var diff = result[i].assocProp.dateProp – Date.now();
// ...
}
46
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
XS Procedures API
SAP HANA XS Procedures is a library of JavaScript tools which enable you to call SAP HANA stored procedures
from server-side JavaScript (XS JS) as if the stored procedures were native JavaScript functions.
Restriction
XSProc is intended only for use with database connections made with the old $.db API. It is not
recommended to use XSProc with $.hdb connections. For $.hdb connections, use
$hdb.loadProcedure instead.
The following example shows how to consume a stored procedure using the XS Procedures API.
// import XS Procedures library
var XSProc = $.import("sap.hana.xs.libs.dbutils", "procedures");
// set a schema where temporary tables can be created for passing table-valued
parameters to the procedure
XSProc.setTempSchema($.session.getUsername().toUpperCase());
// load the procedure
var proc = XSProc.procedure("schema", "namespace", "procedureName”);
// call the procedure
var result = proc(1, [{col1: 0, col2:1}, {col1: 1, col2:2}]);
// result is a JavaScript object
Related Information
SAP HANA XS JavaScript API Reference
Maintaining HTTP Destinations
XS Job File Keyword Options [page 80]
SAP Note SAP Note 786179
3.4.1 Tutorial: Use the XSJS Outbound API
The application package you put together in this tutorial includes all the artifacts you need to enable your
server-side JavaScript application to use the Outbound Connectivity API to request and obtain data via HTTP
from a service running on a remote host.
Prerequisites
Since the artifacts required to get the JavaScript 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 XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 47
Share the new project
The HTTPDestViewer SAP HANA user role
Context
SAP HANA Extended Application Services (SAP HANA XS) includes a server-side JavaScript API that enables
outbound access to a dened HTTP destination. The HTTP destination provides services which an application
can use, for example, to read live data. In this tutorial, you create a JavaScript application that queries nancial
services to display the latest stock values. The nancial services are available on a remote server, whose details
are specied in an HTTP destination conguration.
Procedure
1. Create a package for the SAP HANA XS application that will use the HTTP destination you dene 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 SAP HANA 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. Dene the details of the HTTP destination.
You dene the details of an HTTP destination in a conguration le that requires a specic syntax. The
conguration le containing the details of the HTTP destination must have the le
extension .xshttpdest.
Caution
Place the HTTP destination conguration in the same package as the application that uses it. An
application cannot reference an HTTP destination conguration that is located in another application
package.
a. Create a plain-text le called yahoo.xshttpdest and open it in a text editor.
You can use the le-creation wizard in the Project Explorer view to create this le, for example, New
Other XS HTTP Destination Conguration .
b. Enter the following code in the new le yahoo.xshttpdest.
host = "download.finance.yahoo.com";
port = 80;
description = "my stock-price checker";
useSSL = false;
pathPrefix = "/d/quotes.csv?f=a";
authType = none;
useProxy = false;
proxyHost = "";
48
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
proxyPort = 0;
timeout = 0;
c. Save and activate the le.
Note
Saving a le in a shared project automatically commits the saved version of the le to the
repository.
3. View the activated HTTP destination.
You can use the SAP HANA XS Administration Tool to check the contents of an HTTP destination
conguration.
Note
To make changes to the HTTP Destination conguration, you must use a text editor, save the changes
and reactivate the le.
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: http://<WebServerHost>:80<SAPHANAinstance>/sap/hana/xs/admin/.
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
c. In the XS Artifact Administration screen, expand the nodes in the Application Objects tree to locate the
application testApp.
d. Choose yahoo.xshttpdest to display details of the HTTP destination .
e. Check the details displayed and modify if required.
4. Create a server-side JavaScript application that uses the HTTP destination you have dened.
The XSJS le must have the le extension .xsjs, for example, sapStock.xsjs.
Caution
You must place the XSJS application and the HTTP destination conguration it references in the same
application package. An application cannot use an HTTP destination conguration that is located in
another application package.
a. Create a plain-text le called sapStock.xsjs and open it in a text editor.
b. Enter the following code in the new le sapStock.xsjs.
In this example, you dene the following:
A variable (<stock>) that denes the name of the stock, whose value you want to check, for
example SAP.DE
A variable (<amount>) that denes the number of stocks you want to check, for example, 100
A variable (<dest>) that retrieves metadata dened for the specied HTTP(S) destination, for
example: host, port, useSSL...
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 49
A variable (<client>) that creates the client for the outbound connection
A variable (<req>) that enables you to add details to the request URL
A variable (<res>) that calculates the value of the stock/amount
The format and content of the response body displayed in the browser
var stock = $.request.parameters.get("stock");
var amount = $.request.parameters.get("amount");
var dest = $.net.http.readDestination("testApp", "yahoo");
var client = new $.net.http.Client();
var req = new $.web.WebRequest($.net.http.GET, "&s=" + stock);
client.request(req, dest);
var response = client.getResponse();
var co = [], he = [];
for(var c in response.cookies) {
co.push(response.cookies[c]);
}
for(var c in response.headers) {
he.push(response.headers[c]);
}
var body = undefined;
if(response.body)
var body = response.body.asString();
$.response.contentType = "application/json";
var res = parseInt(response.body.asString()) * amount;
$.response.setBody(amount + " of your " + stock + " are worth: " + res);
c. Save and activate the le.
5. Call the service provided by the application sapStock.xsjs.
a. Open a Web browser.
b. Enter the URL that calls your sapStock.xsjs application.
http://<XS_Webserver>:80<SAPHANA_InstanceNr>/testApp/sapStock.xsjs?
amount=100&stock=SAP.DE
<XS_Webserver>
Name of the system hosting the Web server for the SAP HANA XS instance where your
sapStock.xsjs application is located.
<SAPHANA_InstanceNr>
Number of the SAP HANA instance where the SAP HANA XS Web server is running, for example,
00
50
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
6. Change the details specied in the URL used to run the application.
You can enter dierent values for the parameters &amount and &stock in the URL:
amount=250
Change the number of stocks to check from 100 to 250
&stock=SAP.DE
Change the name of stock to check from SAP.DE to MCRO.L
Related Information
Maintaining HTTP Destinations
SAP HANA XS JavaScript API Reference
3.4.2 Tutorial: Call an XS Procedure with Table-Value
Arguments
You can use the XS Procedures library to call stored procedures as if they were JavaScript functions.
Prerequisites
The delivery unit HANA_XS_DBUTILS contains the XS procedures library. The content is available in the
package sap.hana.xs.libs.dbutils.
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 51
Restriction
XSProc is intended only for use with database connections made with the old $.db API. It is not
recommended to use XSProc with $.hdb connections. For $.hdb connections, use
$hdb.loadProcedure instead.
Create a new (or use an existing) development workspace in the SAP HANA repository.
Create a new (or use an existing) shared project in the workspace.
Create a new (or use an existing) stored procedure.
This tutorial refers to the stored procedure get_product_sales_price, which is 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.
Context
You can call stored procedures by using the contents of the XS Procedures library as if they were JavaScript
functions. For example, the library allows you to pass arguments as a JavaScript object to a stored procedure
that expects table arguments; XS Procedures manages the creation and use of the temporary tables needed to
pass arguments to a table-valued procedure. You can use the functions provided with the XS procedures library
to enable programmatic access to stored procedures in the SAP HANA database from an XS JavaScript
service; the access is provided by binding the stored procedure to a JavaScript function. The result of the call to
the bound function is a JavaScript object, whose properties are the outbound parameters of the procedure.
Procedure
1. Import the XS procedures library.
In your server-side (XS) JavaScript code, ensure that the XS procedures are made available.
var XSProc = $.import("sap.hana.xs.libs.dbutils", "procedures");
2. Specify a schema where temporary tables can be created and lled with the values that are passed as
arguments to the stored procedure.
XS procedures use temporary tables to pass table-valued parameters. As a user of XS procedures you
must specify the name of a schema where these temporary tables reside, for example, a user's own
schema.
52
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
Note
The application code using XS procedures must ensure that the necessary privileges have been
granted to enable the creation and update of (and selection from) temporary tables in the specied
schema.
XSProc.setTempSchema($.session.getUsername().toUpperCase());
3. Bind the stored procedure to a JavaScript function.
This step creates one or more JavaScript functions which can later be used to call the stored procedure.
You can also dene functions which map your call arguments to the parameters of the stored procedure.
var createPurchaseOrder = XSProc.procedure("SAP_HANA_DEMO",
"sap.hana.democontent.epm.Procedures", "poCreate", {connection: conn});
Note
XS procedures uses the connection {connection: conn} passed in a conguration object as a
parameter. If no connection object is passed, the XS procedure library opens a separate connection for
the call and closes the connection after the call completes.
4. Call the procedure.
Use the imported procedure like a normal JavaScript function using JavaScript object argument lists.
var result = createPurchaseOrder([{
"PURCHASEORDERID": '0300009001',
"HISTORY.CREATEDBY": '0000000044',
"HISTORY.CREATEDAT": new Date(),
"HISTORY.CHANGEDBY": '0000000044',
"HISTORY.CHANGEDAT": new Date()
}]);
Table-valued input arguments are passed to the stored procedure using a Javascript array that
corresponds to the rows of the table containing the values to pass. The row objects should contain the
properties of the name of the columns. Skipped columns are lled with NULL; properties without a same-
named column are ignored.
Example
var XSProc = $.import("sap.hana.xs.libs.dbutils", "procedures");
XSProc.setTempSchema($.session.getUsername().toUpperCase());
var conn = $.db.getConnection();
var createPurchaseOrder = XSProc.procedure(
"SAP_HANA_DEMO", "sap.hana.democontent.epm.Procedures",
"poCreate", {connection: conn}
);
var result = createPurchaseOrder([{
"PURCHASEORDERID": '0300009001',
"HISTORY.CREATEDBY": '0000000044',
"HISTORY.CREATEDAT": new Date(),
"HISTORY.CHANGEDBY": '0000000044',
"HISTORY.CHANGEDAT": new Date()
}]);
if (result && result.ERROR.length > 0) {
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 53
$.response.setBody(result.ERROR.length + " errors occurred.");
} else {
$.response.setBody("no error occurred");
}
Related Information
http://help.sap.com/hana/SAP_HANA_XS_DBUTILS_JavaScript_API_Reference_en/index.html
3.4.2.1 Accessing Stored Procedures from XS JavaScript
Call stored SAP HANA procedures from XS server-side JavaScript (XSJS) and process the results of the calls in
JavaScript.
XS procedures provide a convenient way to call stored procedures in SAP HANA from XS server-side Javascript
(XSJS) and process the results of the calls in JavaScript. The XS procedures library extends the features
already available with the SAP HANA XS JavaScript database API. Using XS procedures, SAP HANA stored
procedures can be considered as simple XS JavaScript functions for anyone developing XS JavaScript services.
For example, where an SAP HANA stored procedure uses a table as input parameter and a table as output, XS
Procedures use JavaScript objects (or an array of objects) which can be passed to the procedure. Similarly, the
result of the procedure call is provided as an array of JavaScript objects. You declare a stored procedure as an
XS JavaScript function and then call the stored procedure as if it were a JavaScript function delivering a
JavaScript object.
To use a stored procedure as an XS JavaScript function, the following steps are required:
Step
Action Description
1 Import the XS Procedures library Provide access to the XS procedures
Restriction
XSProc is intended only for use with database connec
tions made with the old $.db API. It is not recom
mended to use
XSProc with $.hdb connections. For
$.hdb connections, use $hdb.loadProcedure in
stead.
2 Specify a schema for temporary tables Temporary tables are used to store the JavaScript arguments
provided for the function.
3 Import the procedure Create the XS JavaScript functions, which can later be used
to call the stored SAP HANA procedure. You can dene func
tions which map your call arguments to the parameters of
the stored procedure.
54 P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
Step Action Description
4 Call the procedure Use the imported procedure in the same way as any normal
JavaScript function, for example, using JavaScript object ar
gument lists.
Restriction
XSProc is intended only for use with database connec
tions made with the old $.db API. For $.hdb connec
tions, use
$hdb.loadProcedure instead.
Use Arguments that Reference an Exist
ing Table [page 55]
(Optional) Write the results or a procedure call into a physical
table and pass the table as an argument rather than a Java
Script object
Use Table-Valued Arguments [page 56] (Optional) Call a procedure with arguments stored as values
in a table
Calling Procedures with Arguments that Reference an Existing Table
If you want to pass a table as an argument rather than a JavaScript object, you must specify the name of the
table (as a string) in the call statement as well as the name of the schema where the table is located. The
following example shows how to reference the table rating_table.
getRating('schema.rating_table', 3);
The SAP HANA database enables you to materialize the results of a procedure call; that is, to write the results
into a physical table using the WITH OVERVIEW expression. In the WITH OVERVIEW expression, you pass a
string value to the output parameter position that contains the result you want to materialize. The value
returned is not the rating itself, but a reference to the table into which the results have been written. The results
of the procedure call can now be retrieved from the specied table, in this example, OUTPUT_TABLE.
var resCall = getRating(rating, 3, "schema.output_table");
// {"RESULT": [{"variable":"RESULT","table":"\"SCHEMA\".\"OUTPUT_TABLE\""}]}
The WITH OVERVIEW expression also allows you to write the results of a procedure into a global temporary
table; that is, a table that is truncated at session close. To use XS Procedures to write the results of a procedure
into a global temporary table, you do not specify a name for the result table; you include an empty string (''),
as illustrated in the following example:
var conn = $.db.getConnection();
resCall = getRating(rating, 3, '', conn);
// {"RESULT": [{"variable":"RESULT","table":"\"SCHEMA\".
\"RESULT_5270ECB8F7061B7EE10000000A379516\""}]}
The returned reference points to a global temporary table which can be queried for the procedure results with
the same connection.
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 55
Note
To ensure access to the global temporary table, it is necessary to specify the connection object conn.
Using Table-Valued Arguments
XS Procedures enables you to call procedures with arguments stored as values in a table, as illustrated in the
following example. Table-valued input arguments are passed using a JavaScript array that corresponds to the
rows of the table to pass. These row objects must contain properties that correspond to the name of the
columns. Skipped columns are lled with NULL, and properties that do not correspond to an identically named
column are ignored.
var XSProc = $.import("sap.hana.xs.libs.dbutils", "procedures");
XSProc.setTempSchema($.session.getUsername().toUpperCase());
var conn = $.db.getConnection();
var createPurchaseOrder = XSProc.procedure("SAP_HANA_DEMO",
"sap.hana.democontent.epm.Procedures::poCreate", {
connection: conn
});
var result = createPurchaseOrder([{
"PURCHASEORDERID": '0300009001',
"HISTORY.CREATEDBY": '0000000044',
"HISTORY.CREATEDAT": new Date(),
"HISTORY.CHANGEDBY": '0000000044',
"HISTORY.CHANGEDAT": new Date()
}]);
if (result && result.ERROR.length > 0) {
$.response.setBody(result.ERROR.length + " errors occurred.");
} else {
$.response.setBody("no error occurred");
}
Related Information
SAP HANA XS JavaScript API Reference
3.4.3 Tutorial: Query a CDS Entity using XS Data Services
You can use the SAP HANA XS Data Services (XSDS) library to query CDS entities as if they were JavaScript
objects.
Prerequisites
A new (or an existing) development workspace in the SAP HANA repository
56
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
A new (or an existing) shared project in the workspace
This tutorial refers to CDS 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.
Context
XS Data Service queries are used to build incrementally advanced queries against data models that are dened
with Core Data Service. Query results are arrays of nested JSON objects that correspond to instances of CDS
entities and their associations.
Procedure
1. Import the XS DS library and reference it through a variable.
var XSDS = $.import("sap.hana.xs.libs.dbutils", "xsds");
2. Import the CDS entities you want to query.
As a rst step to working with CDS entities in SAP HANA XS JavaScript, you must import the CDS entities.
The following example shows how to import to the entities as dened in the SHINE demonstration content:
var soItem = XSDS.$importEntity("sap.hana.democontent.epm.data",
"EPM.SO.Item");
var soHeader = XSDS.$importEntity("sap.hana.democontent.epm.data",
"EPM.SO.Header", {
items: {
$association: {
$entity: soItem,
$viaBacklink: "SALESORDERID"
}
}
});
In addition to the basic CDS denition, the code in the example above shows how to extend the denition of
soHeader by an explicit association called items. This is done by using the keyword $association
together with the referenced entity (soItem) and the type of the association. In this case, $viaBacklink
is used as type, that is; the items of soHeader stored in soItem have a foreign key SALESORDERID
referencing the key of the soHeader table.
3. Add a query.
A general query related to an entity is built by calling the $query() method of the entity constructor.
var qOrders = soHeader.$query();
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 57
4. Rene the query if required.
You can rene the query object as necessary to suit your use case. For example, you can specify that the
query returns only the rst three (3) entries.
qOrders = qOrders.$limit(3);
5. Execute the query.
Use the $execute method to run the query.
var result = qOrders.$execute();
result contains an array of unmanaged values, each of which represents a row of the Post entity.
Note
In the renements to the query, you must call $execute to send the query to the database.
6. Specify the elds the query should return.
Use the $project() method to create a query which species the elds the query should return. For
example, you can return the IDs of the sales orders together with the net amount of the header and the net
amount of all items.
var qOrderAndItemTitles = qOrders.$project({
SALESORDERID: true,
NETAMOUNT: "TotalNet",
items: {
NETAMOUNT: true
}
});
The list of projected elds is a JavaScript object, where desired elds are marked by either true or a String
literal such as "TotalNet" denoting an alias name. The query illustrated in the example above would
return the following result.
[{
"SALESORDERID": "0500000236",
"TotalNet": 273.9,
"items": {
"NETAMOUNT": 29.9
}
}, {
"SALESORDERID": "0500000236",
"TotalNet": 273.9,
"items": {
"NETAMOUNT": 102
}
}, {
"SALESORDERID": "0500000236",
"TotalNet": 273.9,
"items": {
"NETAMOUNT": 55
}
}]
The actual database query automatically JOINs all required tables based on the associations involved. In
the example above, the generated SQL looks like the following:
58
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
Note
In the following code example, the names of table are abbreviated to help readability.
SELECT "t0"."SALESORDERID" AS
"t0.SALESORDERID",
"t0"."NETAMOUNT" AS "t0.NETAMOUNT",
"t0.items"."NETAMOUNT" AS "t0.items.NETAMOUNT"
FROM "Header" "t0"
LEFT OUTER JOIN "Item" "t0.items"
ON "t0"."SALESORDERID"="t0.items"."SALESORDERID"
LIMIT 10
7. Use conditions to restrict the result set.
You can use the $where() method to set conditions that restrict the result set returned by the query. The
following example show how to select all items with a net amount equal to a half (or more) of their order's
net amount.
var qSelectedOrders =
qOrderAndItemTitles.$where(soHeader.items.NETAMOUNT.
$div(soHeader.NETAMOUNT).$gt(0.5))
References to elds and associations such as items are available as properties of the entity constructor
function, for example, soHeader.items. As in the case with projections, XSDS generates all required
JOINs for associations referenced by the conditions automatically, even if they are not part of the current
projection. To build more complex expressions in $where, see the SAP HANA XS Data Services JavaScript
API Reference.
8. Rene the query conditions to a specic matching pattern.
With the $matching() method you can specify conditional expressions using the JSON-like syntax of the
$find() and $findAll() methods. The following code example shows how to further rene the selection
returned by the result set, for example, to accept only those items with a EUR currency and quantity
greater than 2.
qSelectedOrders = qSelectedOrders.$matching({
items: {
CURRENCY: 'EUR',
QUANTITY: {
$gt: 2
}
}
});
Tip
Unlike $findAll(), $matching() returns an unmanaged plain value and ignores all unpersistent
changes to any entity instances.
9. Add arbitrary values to the result set.
You can add arbitrary calculated values to the result set by using the $addFields() method. The
following example shows how to query the days passed since the delivery of the sales item.
qSelectedOrders = qSelectedOrders.$addFields({
"DaysAgo": soHeader.items.DELIVERYDATE.$prefixOp("DAYS_BETWEEN", new
Date())
});
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 59
Note
This query refers to the SQL function DAYS_BETWEEN, which is not a pre-dened function in XSDS.
Instead, you can use the generic operator $prefixOp, which can be used for any SQL function f, for
example, with the syntax f(arg1, … argN).
10. Use aggregations with calculated elds.
Aggregations are a special case of calculated elds that combine the $addFields() operator with an
additional $aggregate() method. The following example shows to retrieve the average quantity of the
rst 100 sales order IDs together with their product ID.
var qAverageQuantity = soItem.$query().$limit(100).$aggregate({
SALESORDERID: true,
PRODUCTID: true
}).$addFields({
averageQuantity: soItem.QUANTITY.$avg()
});
Tip
In SQL terms, the $aggregate() operator creates a GROUP BY expression for the specied paths and
automatically projects the result.
If you need to use a more restrictive projection, you can replace true with false in the $aggregate call,
as illustrated in the following example, which removes the sales order IDs for the result set.
var qAverageQuantity = soItem.$query().$limit(100).$aggregate({
SALESORDERID: false,
PRODUCTID: true
}).$addFields({
averageQuantity: soItem.QUANTITY.$avg()
});
11. Specify the order of the result set.
To specify the order in the result set, you can use the $order() method, including a number of order
criteria as arguments. Each order criteria contains a property “by” with an expression that denes the
desired order. Optionally each criterion can contain a ag $desc to require a descending order and a
$nullsLast ag. The following example uses two criteria to display the result set rst in descending order
by the net amount in the header and then ascending order by the item net amount.
qSelectedOrders = qSelectedOrders.$order({$by: soHeader.NETAMOUNT,
$desc:true},
{$by: soHeader.items.NETAMOUNT});
12. Remove duplicates entries from the result set.
The $distinct operator removes duplicates from the result set. The following example shows how to
display the set of all the currencies used in the sales orders.
var qAllCurrencies = soHeader.$query().$project({CURRENCY: true}).$distinct();
Related Information
SAP HANA XS JavaScript API Reference
60
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
SAP HANA XS DB Utilities JavaScript API Reference
Creating the Persistence Model in Core Data Services
3.4.4 Tutorial: Update a CDS Entity Using XS Data Services
You can use the XS Data Services (XSDS) library to update CDS entities as if they were JavaScript objects.
Prerequisites
A new (or an existing) development workspace in the SAP HANA repository
A new (or an existing) shared project in the workspace
This tutorial refers to CDS 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.
Context
For read-write scenarios, SAP HANA XS Data Services (XSDS) oer a managed mode with automatic entity
management and additional consistency guarantees. Managed mode shares CDS imports and transaction
handling with unmanaged mode but uses a dierent set of methods provided by the entity constructors.
Procedure
1. Import the XSDS library and the CDS entities into your application.
In your entity import, specify a SAP HANA sequence that is used to generate the required keys.
// import XSDS client library
var XSDS = $.import("sap.hana.xs.libs.dbutils", "xsds");
// import CDS entity as XSDS entity
var SOItem = XSDS.$importEntity("sap.hana.democontent.epm.data",
"EPM.SO.Item");
var SOHeader = XSDS.$importEntity("sap.hana.democontent.epm.data",
"EPM.SO.Header", {
SALESORDERID: { $key: "\"SAP_HANA_DEMO\".
\"sap.hana.democontent.epm.data::salesOrderId\"" },
items: {
$association: {
$entity: SOItem,
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 61
$viaBacklink: "SALESORDERID"
}
}
});
2. Retrieve an existing entity instance in managed mode.
The $importEntity() function returns a constructor for the entity imported. To retrieve an existing
entity instance in managed mode, run a query using the entity's key (for example, using $get), or retrieve
multiple instances that satisfy a given condition.
var order = SOHeader.$get({ SALESORDERID:
"0500000236" }); // by key
var orders = SOHeader.$findAll({ LIFECYCLESTATUS: "N", TAXAMOUNT: { $gt:
17000 } }); // by filter
3. Use or modify entity instances as required.
Iinstances of CDS entities are regular JavaScript objects which you can use and modify as required.
order.CURRENCY = "USD";
order.HISTORY.CHANGEDAT = new Date();
4. Ensure all changes are made persistent in the database.
Calling $save() ushes in-memory changes of the instance and all its reachable associated instances to
the database. Only entity instances that have been changed will be updated in the database.
order.$save();
5. Use the entity constructor to create a new CDS instance.
The key is generated automatically by the SAP HANA sequence supplied during the import of the XSDS
library and the CDS entities into your application.
var newOrder = new SoHeader ({
TAXAMOUNT": 69.04,
NETAMOUNT": 190.9,
GROSSAMOUNT": 325.94,
CURRENCY": "EUR",
PARTNERID": "0100000044",
DELIVERYSTATUS: "I",
BILLINGSTATUS: "I",
LIFECYCLESTATUS: "N",
HISTORY": {
CHANGEDAT": Date.now(),
CHANGEDBY": "0000000033",
CREATEDAT": Date.now(),
CREATEDBY": "0000000033"
},
items: []
});
newOrder.$save();
6. Discard any unwanted instances of a CDS entity.
Retrieved CDS entities are stored in the entity manager cache and subject to general JavaScript garbage-
collection rules. Use the $discard() function to permanently delete an entity instance from the database.
order.$discard();
7. Control how associations in a CDS document are followed.
By default, all associations are resolved, that is; association properties store a reference to their associated
entity instance. For heavily connected data, this may lead to very large data structures in memory. A “lazy”
62
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
association will delay the retrieval of the associated instances until the property is actually accessed. The
rst time the lazy association is accessed, the associated entity is queried from the entity cache or the
database. After a lazy association has been resolved, it becomes a normal property of its parent entity
instance.
To control how associations are being followed, declare “lazy” associations during the import operation, as
shown in the following example:
var SOHeader = XSDS.$importEntity("sap.hana.democontent.epm.data",
"EPM.SO.Header", {
SALESORDERID: { $key: "\"SAP_HANA_DEMO\".
\"sap.hana.democontent.epm.data::salesOrderId\"" },
items: {
$association: {
$entity: SOItem,
$viaBacklink: "SALESORDERID",
$lazy: true
}
}
});
The retrieval of “Lazy” associations is handled transparently by XSDS.
var order = SOHeader.$get({ SALESORDERID: "0500000236" }); // retrieve
single SO header
if (order.DELIVERYSTATUS != "D")
return; // return without loading SO items from database
for (var item in order.items) { … }; // now retrieve items for processing
8. Manually control transactions for your application where necessary.
Every SAP HANA XS application using XSDS is associated with one database connection and one
transaction. This is also true if the application uses multiple imports of the XSDS library; XS libraries are
single instances by default. Entities retrieved from the database are stored in the entity manager cache,
and any updates need to be saved explicitly to the database. By default, database saves will automatically
commit the changes to the database. However, you can manually control transactions for your application
by disabling auto-commit and calling $commit and $rollback explicitly, as illustrated in the following
example.
// disable auto-commit
XSDS.Transaction.$setAutoCommit(false);
var order = SOHeader.$get({ SALESORDERID: "0500000236" });
order.CURRENCY = "JPY";
order.$save(); // persist update
XSDS.Transaction.$commit(); // commit change
order.CURRENCY = "EUR";
order.$save(); // persist update
order.HISTORY.CHANGEDAT = new Date();
order.$save(); // persist update
XSDS.Transaction.$rollback(); // database rollback
// order #0500000236 now has currency JPY again
Related Information
SAP HANA XS JavaScript API Reference
SAP HANA XS DB Utilities JavaScript API Reference
Creating the Persistence Model in Core Data Services
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 63
3.5 Creating Custom XS SQL Connections
In SAP HANA Extended Application Services (SAP HANA XS), you use the SQL-connection conguration le to
congure a connection to the database; the connection enables the execution of SQL statements from inside a
server-side JavaScript application with credentials that are dierent to the credentials of the requesting user.
In cases where it is necessary to execute SQL statements from inside your server-side JavaScript application
with credentials that are dierent to the credentials of the requesting user, SAP HANA XS enables you to dene
and use a specic conguration for individual SQL connections. Each connection conguration has a unique
name, for example, Registration or AdminConn, which is generated from the name of the corresponding
connection-conguration le (Registration.xssqlcc or AdminConn.xssqlcc) on activation in the
repository. The administrator can assign specic, individual database users to this conguration, and you can
use the conguration name to reference the unique SQL connection conguration from inside your JavaScript
application code.
The following code example shows how to use the XS SQL connection AdminConn.xssqlcc.
function test() {
var body;
var conn;
$.response.status = $.net.http.OK;
try {
conn = $.db.getConnection("sap.hana.sqlcon::AdminConn");
var pStmt = conn.prepareStatement("select CURRENT_USER from dummy");
var rs = pStmt.executeQuery();
if (rs.next()) {
body = rs.getNString(1);
}
rs.close();
pStmt.close();
} catch (e) {
body = "Error: exception caught";
$.response.status = $.net.http.BAD_REQUEST;
}
if (conn) {
conn.close();
}
$.response.setBody( body );
}
test();
To use the SQL connection from your application during runtime, you must bind the SQL connection
conguration to a registered database user and assign the user the appropriate permissions, for example, by
assigning a pre-dened role to the user. To maintain this user mapping, SAP HANA XS provides the Web-based
SAP HANA XS Administration Tool. When the run-time status of the XSSQLCC artifact is set to active, SAP
HANA generates a new auto user (with the name XSSQLCC_AUTO_USER_[...]. The new user is granted the
permissions specied in a role, which can be assigned using the parameter role_for_auto_user - either in
the design-time artifact or the run-time conguration.
Note
Access to the tools provided by the XS Administration Tool requires the privileges granted by one or more
specic user roles.
64
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
To use the SAP HANA XS Administration Tool to view or maintain an XS SQL connection conguration, you need
the privileges granted by the following SAP HANA XS roles:
sap.hana.xs.admin.roles::SQLCCViewer
Required to display the available SQL Connections and the current user mapping
sap.hana.xs.admin.roles::SQLCCAdministrator
Required to modify details of the user mapping; the SQLCCAdministrator role includes the role
SQLCCViewer.
Troubleshooting Tips
If you are having problems implementing the XS SQL connection feature using an .xssqlcc conguration,
check the following points:
User permissions
Make sure that you grant the necessary user the activated role (for example,
sap.hana.xs.admin.roles::SQLCCAdministrator). You can use the developer tools to grant roles (or
privileges), as follows:
Note
The granting user must have the object privilege EXECUTE on the procedure
GRANT_ACTIVATED_ROLE.
SAP HANA studio
In the Systems view of the Administration Console perspective, choose Security Users
SAP HANA Web-based Development Workbench
In the Security tool, expand the Users node, choose the target (or add a new) user, and use the Granted
roles tab.
XS Administration Tools
In the SQL Connection Details tab of the XSSQLCC artifact's run time conguration. To edit user/role
details here, you will need the role SQLCCAdministrator and, in addition, the appropriate administrator
permissions required to set up (and assign roles to) a database user.
File location
Make sure that the SQL-role conguration le (.xssqlcc) you create is located in the same package as
the application that references it.
Logon dependencies
If your application is using form-based logon (congured in the application's .xsaccess le), make sure
the libxsauthenticator library is present and specied in the list of trusted libraries displayed in the
SAP HANA studio's Administration Console perspective ( Administration Conguration Tab
xsengine.ini application_container application_list . If the libxsauthenticator library is not in the
list of authorized libraries, an SAP HANA system administrator must add it.
Note
If you have to authorize libxsauthenticator, you might also need to refresh the Web page in your
browser the next time you want to access
.xssqlcc to display the logon dialog again.
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 65
3.5.1 Create an XS SQL Connection Conguration
The .xssqlcc le enables you to establish a database connection that you can use to execute SQL statements
from inside your server-side JavaScript application with credentials that are dierent to the credentials of the
requesting user.
Prerequisites
Access to an SAP HANA system
Access to a development workspace and a shared project.
The application package structure in which to save the artifacts you create and maintain in this task
The SQL connection conguration le (.xssqlcc) you create must be located in the same package as the
application that uses it.
You have the privileges granted in the following SAP HANA user roles:
sap.hana.xs.admin.roles::SQLCCViewer
sap.hana.xs.admin.roles::SQLCCAdministrator
Note
This tutorial combines tasks that are typically performed by two dierent roles: the application developer
and the database administrator. The developer would not normally require the privileges of the SAP HANA
administrator or those granted by the SQLCCAdministrator user role.
Context
In this tutorial, you learn how to congure an SQL connection that enables you to execute SQL statements from
inside your server-side JavaScript application with credentials that are dierent to the credentials of the user
requesting the XSJS service.
To congure and use an XS SQL conguration connection le, perform the following steps:
Procedure
1. Start the SAP HANA studio.
a. Open the SAP HANA Development perspective.
b. Open the Project Explorer view.
2. Create the application descriptors for the new application.
a. In the SAP HANA studio's Project Explorer view, right-click the folder acme.com.xs.testApp1 where
you want to create the new (.xsapp) le.
b. In the context-sensitive popup menu, choose New Other... .
66
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
c. In the Select a Wizard dialog, choose SAP HANA Application Development XS Application
Descriptor File
The le-creation wizard adds the required le extension .xsapp automatically.
d. Choose Finish.
Tip
Files with names that begin with the period (.), for example, .xsapp or .xsaccess, are sometimes
not visible in the Project Explorer. To enable the display of all les in the Project Explorer view, use
the
Customize View Available Customization option and clear all check boxes.
e. Activate the application descriptor le.
In the SAP HANA studio's Project Explorer view, right-click the new (.xsapp) le and choose Team
Activate from the context-sensitive popup menu.
3. Create the application access le for the new application.
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) le.
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
The le-creation wizard adds the required le extension .xsaccess automatically and enables direct
editing of the le.
Note
The default name for the core application-access le is .xsaccess and cannot be changed.
e. Choose Finish.
f. Check the contents of the .xsaccess file.
{
"exposed" : true,
"authentication" : { "method" : "Form"},
"prevent_xsrf" : true
}
The entries in the .xsaccess le ensure the following:
Application data can be exposed to client requests
Username and password credentials are required for logon authentication
Protection against cross-site, request-forgery attacks is enabled
g. Activate the application access le.
In the SAP HANA studio's Project Explorer view, right-click the new (.xsaccess) le and choose
Team Activate from the context-sensitive popup menu.
4. Create the XS SQL connection conguration le.
Browse to the folder in your project workspace where you want to create the new SQL connection
conguration le and perform the following steps:
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 67
Note
The SQL connection conguration le (.xssqlcc) you create must be located in the same package as
the application that references it.
a. Right-click the folder where you want to save the XS SQL connection conguration le and choose
New Other... Application Development XS SQL Connection Conguration File in the context-
sensitive popup menu.
b. Enter the name of the SQL connection conguration le in the File Name box, for example,
AdminConn.
Tip
The le-creation wizard adds the required le extension automatically (for example,
AdminConn.xssqlcc) and, if appropriate, enables direct editing of the new le in the
corresponding editor.
c. Choose Finish to save the changes and commit the new XS SQL connection conguration le in the
repository.
5. Congure the details of the SQL connection that the XS JavaScript service will use.
a. Dene the required connection details.
{
"description" : "Admin SQL connection"
"role_for_auto_user" : "com.acme.roles::JobAdministrator"
}
Tip
Replace the package path (com.acme.roles) and role name (JobAdministrator) with the
suitable ones for your case.
b. Activate the XS SQL connection conguration le.
In the SAP HANA studio's Project Explorer view, right-click the new (.xssqlcc) le and choose
Team Activate from the context-sensitive popup menu.
Note
Activating the SQL connection conguration le AdminConn.xssqlcc creates a catalog object with the
name sap.hana.xs.testApp1::AdminConn, which can be referenced in a XS JavaScript application.
6. Write an XS JavaScript application that calls the XS SQL connection conguration.
To create a precongured SQL connection using the conguration object AdminConn, for example, from
inside your JavaScript application code, you must reference the object using the object name with the full
package path, as illustrated in the following code example.
function test() {
var body;
var conn;
$.response.status = $.net.http.OK;
try {
conn = $.db.getConnection("sap.hana.xs.testApp1::AdminConn");
var pStmt = conn.prepareStatement("select CURRENT_USER from dummy");
var rs = pStmt.executeQuery();
68
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
if (rs.next()) {
body = rs.getNString(1);
}
rs.close();
pStmt.close();
} catch (e) {
body = "Error: exception caught";
$.response.status = $.net.http.BAD_REQUEST;
}
if (conn) {
conn.close();
}
$.response.setBody( body );
}
test();
7. Save the changes to the artifacts you have created.
Note
Saving a le in a shared project automatically commits the saved version of the le to the repository.
You do not need to explicitly commit it again.
8. Activate the changes in the repository.
a. In the Project Explorer view, locate and right-click the package containing the new XS SQL and XS
JavaScript artifacts.
b. In the context-sensitive pop-up menu, choose Team Activate .
9. Bind the SQL connection conguration to a user.
You use the Web-based SAP HANA XS Administration Tool to congure the runtime elements of the XS SQL
connection.
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: http://<WebServerHost>:80<SAPHANAinstance>/sap/hana/xs/admin/.
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:
sap.hana.xs.admin.roles::SQLCCViewer
sap.hana.xs.admin.roles::SQLCCAdministrator
b. In the XS Applications tab, expand the nodes in the application tree to locate the application testApp.
c. Choose AdminConn to display details of the XS SQL conguration connection .
10. Set the run-time status of the XS SQL connection conguration.
You must change the status run-time status of the XS SQL connection conguration to Active. This run-
time status can only be changed by an administrator. When the run-time status of the XSSQL connection
conguration is set to active, SAP HANA automatically generates a new user
(XSSQLCC_AUTO_USER_[...]) for the XSSQL connection conguration object and assigns the role
dened in role_for_auto_user to the new auto-generated user.
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 69
Related Information
The SQL Connection Conguration File [page 70]
SQL Connection Conguration Syntax [page 71]
3.5.1.1 The SQL Connection Conguration File
The SQL-connection conguration le species the details of a connection to the database that enables the
execution of SQL statements from inside a server-side (XS) JavaScript application with credentials that are
dierent to the credentials of the requesting user.
If you want to create an SQL connection conguration, you must create the conguration as a at le and save
the le with the sux .xssqlcc, for example, MYSQLconnection.xssqlcc. The new conguration le must
be located in the same package as the application that references it.
Note
An SQL connection conguration can only be accessed from an SAP HANA XS JavaScript application
(.xsjs) le that is in the same package as the SQL connection conguration itself. Neither subpackages
nor sibling packages are allowed to access an SQL connection conguration.
The following example shows the composition and structure of a conguration le AdminConn.xssqlcc for an
SAP HANA XS SQL connection called AdminConn. On activation of the SQL connection conguration le
AdminConn.xssqlcc (for example, in the package sap.hana.sqlcon), an SQL connection conguration
with the name sap.hana.sqlcon::AdminConn is created, which can be referenced in your JavaScript
application. In the xssqlcc artifact, you can set the following values:
description
A short description of the scope of the xs sql connection conguration
role_for_auto_user
The name of the role to be assigned to the auto user (if required) that the XSSQL connection uses, and the
absolute path to the package where the role denition is located in the SAP HANA repository.
sap.hana.sqlcon::AdminConn.xssqlcc
{
"description" : "Admin SQL connection"
"role_for_auto_user" : "com.acme.roles::JobAdministrator"
}
The run-time status of an XSSQL connection conguration is inactive by default; the run-time status can only
be activated by an SAP HANA user with administrator privileges, for example, using the SAP HANA XS
Administration Tools. When the run-time status of the XSSQLCC artifact is set to active, SAP HANA generates a
new auto user (with the name XSSQLCC_AUTO_USER_[...]) and assigns the role dened in
role_for_auto_user to the new auto-generated user.
Tip
In the SAP HANA XS Administration Tools, it is possible to view and edit both the the user's parameters and
the role's denition.
70
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
To create a precongured SQL connection using the conguration object AdminConn, for example, from inside
your JavaScript application code, you reference the object using the object name and full package path, as
illustrated in the following code example.
{
conn = $.db.getConnection("sap.hana.sqlcon::AdminConn");
}
Related Information
SQL Connection Conguration Syntax [page 71]
Create an XS SQL Connection Conguration [page 66]
3.5.1.2 SQL Connection Conguration Syntax
The XS SQL connection-conguration le .xssqlcc uses pairs of keywords and values to dene the SQL
connection.
Example:
The XS SQL Connection Conguration (.xssqlcc) File
Code Syntax
{
"description" : "Admin SQL connection"
"role_for_auto_user" : "com.acme.roles::JobAdministrator"
}
description
A short description of the selected SQL connection conguration.
Sample Code
"description" : "Admin SQL connection"
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 71
role_for_auto_user
The name of (and package path to) the role assigned to be assigned to the new user that is automatically
generated on activation of the XSSQL connection-conguration artifact.
Sample Code
"role_for_auto_user" : "com.acme.roles::JobAdministrator"
Activating the design-time XSSQL connection conguration generates a run-time object whose status is
“inactive” by default; the run-time status must be set to active by an SAP HANA user with administrator
privileges, for example, using the SAP HANA XS Administration Tools. When the run-time status of the
XSSQLCC artifact is set to active, SAP HANA generates a new auto user (with the name
XSSQLCC_AUTO_USER_[...]) and assigns the role dened in role_for_auto_user to the new auto-
generated user.
Related Information
The SQL Connection Conguration File [page 70]
Create an XS SQL Connection Conguration [page 66]
3.6 Setting the Connection Language in SAP HANA XS
HTTP requests can dene the language used for communication in the HTTP header Accept-Language. This
header contains a prioritized list of languages (dened in the Browser) that a user is willing to accept. SAP
HANA XS uses the language with the highest priority to set the language for the requested connection. The
language setting is passed to the database as the language to be used for the database connection, too.
In server-side JavaScript, the session object's language property enables you to dene the language an
application should use for a requested connection. For example, your client JavaScript code could include the
following string:
var application_language = $.session.language = 'de';
Note
Use the language-code format specied in BCP 47 to set the session language, for example: “en-US” (US
English), “de-AT” (Austrian German), “fr-CA” (Canadian French).
As a client-side framework running in the JavaScript sandbox, the SAP UI5 library is not aware of the Accept-
Language header in the HTTP request. Since the current language setting for SAPUI5 is almost never the
same as the language specied in the SAP HANA XS server-side framework, SAPUI5 clients could have
problems relating to text displayed in the wrong language or numbers and dates formatted incorrectly.
72
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
The application developer can inform the SAP UI5 client about the current server-side language setting, for
example, by adding an entry to the <script> tag in the SAPUI5 HTML page, as illustrated in the following
examples:
Script tag parameter:
<script id="sap-ui-bootstrap"
type="text/javascript"
src="/sap/ui5/1/resources/sap-ui-core.js"
data-sap-ui-theme="sap_goldreflection"
data-sap-ui-libs="sap.ui.commons"
data-sap-ui-language="de">
</script>
Global sap-ui-config object:
<script>
window["sap-ui-config"] = {
"language" : "de"
}
</script>
[…]
<script id="sap-ui-bootstrap"
[…]
</script>
The sap-ui-config object must be created and lled before the sap-ui-bootstrap script.
It is important to understand that the session starts when a user logs on, and the specied language is
associated with the session. Although the user can start any number of applications in the session, for
example, in multiple Browser tabs, it is not possible to set a dierent language for individual applications called
in the session,
Setting the Session Language on the Server side
The script tag for the SAPUI5 startup can be generated on the server side, for example, using the
$.session.language property to set the data-sap-ui-language parameter. Applications that have the
SAPUI5 <script> tag in a static HTML page can use this approach, as illustrated in the following example:
<script id="sap-ui-bootstrap"
type="text/javascript"
src="/sap/ui5/1/resources/sap-ui-core.js"
data-sap-ui-theme="sap_goldreflection"
data-sap-ui-libs="sap.ui.commons"
data-sap-ui-language="$UI5_LANGUAGE$">
</script>
The called XSJS page can be instructed to replace the $UI5_LANGUAGE$ parameter, for example, with the
value stored in $.session.language when loading the static HTML page.
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 73
Setting the Session Language with an AJAX Call
You can include an HTTP call in the static HTML page to fetch the correct language from the server using some
server-side JavaScript code, as illustrated in the following example:
<script>
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "getAcceptLanguage.xsjs", false );
xmlHttp.send( null );
window["sap-ui-config"] = {
"language" : xmlHttp.getResponseHeader("Content-Language")
}
</script>
<script id="sap-ui-bootstrap"
</script>
This approach requires an XSJS artifact (for example, getAcceptLanguage.xsjs) that responds to the AJAX
call with the requested language setting, as illustrated in the following example:
$.response.contentType = "text/plain";
$.response.headers.set("Content-Language", $.session.language);
$.response.setBody("");
3.7 Scheduling XS Jobs
Scheduled jobs dene recurring tasks that run in the background. The JavaScript API $.jobs allows
developers to add and remove schedules from such jobs.
If you want to dene a recurring task, one that runs at a scheduled interval, you can specify details of the job in
a .xsjob le. The time schedule is congured using cron-like syntax. You can use the job dened in
an .xsjob le to run an XS Javascript or SQLScript at regular intervals. To create and enable a recurring task
using the xsjob feature, you perform the following high-level tasks:
Note
The tasks required to set up a scheduled job in SAP HANA XS are performed by two distinct user roles: the
application developer and the SAP HANA administrator. In addition, to maintain details of an XS job in the
SAP HANA XS Administration Tool, the administrator user requires the privileges granted by the role
template sap.hana.xs.admin.roles::JobAdministrator.
Setting up Scheduled Jobs in SAP HANA XS.
Step
Task User Role Tool
1 Create the function or script you want to run at
regular intervals
Application developer Text editor
2
Create the job le .xsjob that denes details of
the recurring task
Application developer Text editor
74 P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
Step Task User Role Tool
3 Maintain the corresponding runtime conguration
for the xsjob
SAP HANA administrator XS Job Dashboard
4 Enable the job-scheduling feature in SAP HANA
XS
SAP HANA administrator XS Job Dashboard
5 Check the job logs to ensure the job is running ac
cording to schedule.
SAP HANA administrator XS Job Dashboard
Related Information
The XSJob File [page 79]
Tutorial: Schedule an XS Job [page 75]
XS Job File Keyword Options [page 80]
3.7.1 Tutorial: Schedule an XS Job
The xsjob le enables you to run a service (for example, an XS JavaScript or an SQLScript) at a scheduled
interval.
Prerequisites
You have access to an SAP HANA system.
You have a role based on the role template sap.hana.xs.admin.roles::JobAdministrator.
You have a role based on the role template sap.hana.xs.admin.roles::HTTPDestAdministrator.
Note
This tutorial combines tasks that are typically performed by two dierent roles: the application developer
and the database administrator. The developer would not normally require the privileges granted to the
sap.hana.xs.admin.roles::JobAdministrator role, the
sap.hana.xs.admin.roles::HTTPDestAdministrator role, or the SAP HANA administrator.
Context
In this tutorial, you learn how to schedule a job that triggers an XS JavaScript application that reads the latest
value of a share price from a public nancial service available on the Internet. You also see how to check that
the XS job is working and running on schedule.
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 75
To schedule an XS job to trigger an XS JavaScript to run at a specied interval, perform the following steps:
Procedure
1. Create the application package structure that contains the artifacts you create and maintain in this tutorial.
Create a root package called yahoo. You use the new yahoo package to contain the les and artifacts
required to complete this tutorial.
/yahoo/
.xsapp // application descriptor
yahoo.xsjob // job schedule definition
yahoo.xshttpdest // HTTP destination details
yahoo.xsjs // Script to run on schedule
2. Write the XS JavaScript code that you want to run at the interval dened in an XS job schedule.
The following XS JavaScript connects to a public nancial service on the Internet to check and download
the latest prices for stocks and shares.
Create an XS JavaScript le called yahoo.xsjs and add the code shown in the following example:
function readStock(input) {
var stock = input.stock;
var dest = $.net.http.readDestination("yahoo", "yahoo");
var client = new $.net.http.Client();
var req = new $.web.WebRequest($.net.http.GET, "/d/quotes.csv?f=a&s=" +
stock);
client.request(req, dest);
var response = client.getResponse();
var stockValue;
if(response.body)
stockValue = parseInt(response.body.asString(), 10);
var sql = "INSERT INTO stock_values VALUES (NOW(), ?)";
var conn = $.db.getConnection();
var pstmt = conn.prepareStatement(sql);
pstmt.setDouble(1, stockValue);
pstmt.execute();
conn.commit();
conn.close();
}
Save and activate the changes in the SAP HANA Repository.
Note
Saving a le in a shared project automatically commits the saved version of the le to the repository, To
explicitly commit a le to the repository, right-click the le (or the project containing the le) and
choose
Team Commit from the context-sensitive popup menu.
3. Create an HTTP destination le using the wizard to provide access to the external service (via an outbound
connection).
Since the nancial service used in this tutorial is hosted on an external server, you must create an HTTP
destination le, which provides details of the server, for example, the server name and the port to use for
HTTP access.
76
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
Note
To maintain the runtime conguration details using the Web-based XS Administration Tool you need the
privileges granted in the SAP HANA user role sap.hana.xs.admin.roles::HTTPDestAdministrator.
Create a le called yahoo.xshttpdest and add the following content:
host = "download.finance.yahoo.com";
port = 80;
Save and activate the changes in the SAP HANA Repository.
4. Create the XS job le using the wizard to dene the details of the schedule at which the job runs.
The XS job le uses a cron-like syntax to dene the schedule at which the XS JavaScript must run. This job
le triggers the script yahoo.xsjs on the 59th second of every minute and provides the name “SAP.DE”
as the parameter for the stock value to check.
Create a le called yahoo.xsjob and add the following code:
{
"description": "Read stock value",
"action": "yahoo:yahoo.xsjs::readStock",
"schedules": [
{
"description": "Read current stock value",
"xscron": "* * * * * * 59",
"parameter": {
"stock": "SAP.DE"
}
}
]
}
Save and activate the changes in the SAP HANA Repository.
5. Maintain the XS job's runtime conguration.
You maintain details of an XS Job's runtime conguration in the XS Job Dashboard.
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: http://<WebServerHost>:80<SAPHANAinstance>/sap/hana/xs/admin/.
b. Maintain the details of the XS job.
Note
To maintain details of an XS job using the Web-based XS Administration Tool you need the
privileges granted in the SAP HANA user role sap.hana.xs.admin.roles::JobAdministrator.
You need to specify the following details:
User
The user account in which the job runs, for example, SYSTEM
Password
The password required for user, whose account is used to run the job.
Locale
The language encoding required for the locale in which the job runs, for example, en_US
Start/Stop time
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 77
An optional value to set the period of time during which the job runs. Enter the values using the
syntax used for the SAP HANA data type LocalDate and LocalTime, for example, 2014-11-05
00:30:00 (thirty minutes past midnight on the 5th of November 2014).
Active
Enable or disable the job schedule
Session timeout
Specify the session timeout for this XSJob in seconds. If you specify a value of 0 (zero) seconds for
the XSJob's session timeout, the XSJob checks if a value is dened for the sessiontimeout key
in the section scheduler of the xsengine.ini le. If no such key exists, the default session
timeout of 900 seconds is used. If you want to dene a non-default value for the scheduler's
sessiontimeout key, you must create the key in the scheduler section of the xsengine.ini
le and supply the desired timeout value, for example, 600 seconds.
Caution
It is not recommended to specify a value of 0 (zero) for the sessiontimeout key; this
disables the session-timeout feature for all jobs started by the scheduler.
c. Save the job.
Choose Save Job to save and activate the changes to the job schedule.
6. Enable the job-scheduling feature in SAP HANA XS.
This step requires the permissions granted to the SAP HANA administrator.
Note
It is not possible to enable the scheduler for more than one host in a distributed SAP HANA XS
landscape.
a. In the XS Job Dashboard set the Scheduler Enabled toggle button to YES.
Toggling the setting for the Scheduler Enabled button in the XS Job Dashboard changes the value set for
the
SAP HANA conguration variable xsengine.ini scheduler enabled , which is set in the
Conguration tab of the SAP HANA studio's Administration perspective.
7. Check the job logs to ensure the XS job is active and running according to the dened schedule.
You can view the xsjob logs in the XS Job Dashboard tab of the SAP HANA XS Administration Tool.
Note
To maintain details of an XS job using the Web-based XS Administration Tool you need the privileges
granted in the SAP HANA user role sap.hana.xs.admin.roles::JobAdministrator.
If the job does not run at the expected schedule, the information displayed in the xsjob logs includes details
of the error that caused the job to fail.
Related Information
The XS Job File [page 79]
XS Job-File Keyword Options [page 80]
78
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
3.7.1.1 The XS Job File
The .xsjob le denes the details of a task that you want to run (for example, an XS JavaScript or an
SQLScript) at a scheduled interval.
The XS job le uses a cron-like syntax to dene the schedule at which the service dened in an XS JavaScript
or SQLScript must run, as you can see in the following example, which runs the specied job (the stock-price
checking service yahoo.xsjs) on the 59th second minute of every minute.
{
"description": "Read stock value",
"action": "yahoo:yahoo.xsjs::readStock",
"schedules": [
{
"description": "Read current stock value",
"xscron": "* * * * * * 59",
"parameter": {
"stock": "SAP.DE"
}
}
]
}
When dening the job schedule in the xsjob le, pay particular attention to the entries for the following
keywords:
action
Text string used to specify the path to the function to be called as part of the job.
"action": "<package_path>:<XSJS_Service>.xsjs::<FunctionName>",
Note
You can also call SQLScripts using the action keyword.
description
Text string used to provide context when the XSjob le is displayed in the SAP HANA XS Administration
tool.
xscron
The schedule for the specied task (dened in the “action” keyword); the schedule is dened using
cron-like syntax.
parameter
A value to be used during the action operation. In this example, the parameter is the name of the stock
SAP.DE provided as an input for the parameter (stock) dened in the readStock function triggered by
the xsjob action. You can add as many parameters as you like as long as they are mapped to a parameter
in the function itself.
The following examples illustrate how to dene an xscron entry including how to use expressions in the
various xscron entries (day, month, hour, minutes,...):
2013 * * fri 12 0 0
Every Friday of 2013 at 12:00 hours
* * 3:-2 * 12:14 0 0
Every hour between 12:00 and 14:00 hours on every day of the month between the third day of the month
and the second-last day.
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 79
Tip
In the day eld, third from the left, you can use a negative value to count days backwards from the end
of the month. For example, * * -3 * 9 0 0 means: three days from the end of every month at
09:00.
* * * * * */5 *
Every ve minutes (*/5) and at any point (*) within the specied minute.
Note
Using the asterisk (*) as a wild card in the seconds eld can lead to some unexpected consequences, if
the scheduled job takes less than 59 seconds to complete; namely, the scheduled job restarts on
completion. If the scheduled job is very short (for example, 10 seconds long), it restarts repeatedly until
the specied minute ends.
To prevent short-running jobs from restarting on completion, schedule the job to start at a specic second
in the minute. For example, * * * * * */5 20 indicates that the scheduled job should run every ve
minutes and, in addition, at the 20th second in the specied minute.
* * * -1.sun 9 0 0
Every last Sunday of a month at 09:00 hours
Related Information
XS Job File Keywords [page 80]
Tutorial: Schedule an XS Job [page 75]
3.7.1.2 XS Job File Keyword Options
The XS job le .xsjob uses a number of keywords to dene the job that must be run at a scheduled interval.
Example:
The XS Job (.xsjob) File
{
"description": "Read stock value",
"action": "yahoo:yahoo.xsjs::readStock",
"schedules": [
{
"description": "Read current stock value",
"signature_version": 1,
"xscron": "* * * * * * 59",
"parameter": {
"stock": "SAP.DE"
}
80
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
}
]
}
description
{
"description": "Read stock value",
}
The description keyword enables you dene a text string used to provide context when the XS job is displayed
for maintenance in the SAP HANA XS Administration Tool. The text string is used to populate the Description
eld in the SCHEDULED JOB tab.
action
{
"action": "myapps.finance.yahoo:yahoo.xsjs::readStock",
}
The action keyword enables you to dene the function to run as part of the XS job, for example, an XS
JavaScript or an SQLScript. The following syntax is required: “action” :
<package.path>:<XSJS_Service>.xsjs::<functionName>.
Note
If you want to use the action to call an SQLScript, replace the name of the XSJS service in the example, with
the corresponding SQLScript name.
schedules
{
"schedules": [
{
"description": "Read current stock value",
"xscron": "* * * * * * 59",
"parameter": {
"stock": "SAP.DE"
}
}
]
}
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 81
The schedules keyword enables you dene the details of the XS job you want to run. Use the following
additional keywords to provide the required information:
description (optional)
Short text string to provide context
xscron
Uses cron-like syntax to dene the schedule at which the job runs
parameter (optional)
Denes any values to be used as input parameters by the (XSJS or SQLScript) function called as part of
the job
signature_version
{
"signature_version": 1,
}
The signature_version keyword enables you manage the version “signature” of an XS job. You change the XS job
version if, for example, the parameter signature of the job action changes; that is, an XS job accepts more (or
less) parameters, or the types of parameters dier compared with a previous version of an XS job. On
activation in the SAP HANA Repository, the signature of an XS job is compared to the previous one and, if the
job’s signature has changed, any job schedules created at runtime will be deactivated.
Note
The default value for signature_version is 0 (zero).
Deactivation of any associated runtime job schedules prevents the schedules from silently failing (no
information provided) and enables you to adjust the parameters and reactivate the job schedules as required,
for example, using the enhanced XS JS API for schedules. Schedules dened in a design-time XS Job artifact
are replaced with the schedules dened in the new version of the XS job artifact.
Tip
Minor numbers (for example, 1.2) are not allowed; the job scheduler interprets “1.2” as “12”.
xscron
{
"schedules": [
{
"description": "Read current stock value",
"xscron": "* * * * * * 59",
"parameter": {
"stock": "SAP.DE"
}
}
]
}
82
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
The xscron keyword is used in combination with the schedules keyword. The xscron keyword enables you to
dene the schedule at which the job runs. As the name suggests, the xscron keyword requires a cron-like
syntax.
The following table explains the order of the elds (*) used in the “xscron” entry of the .xsjob le and lists
the permitted value in each eld.
xscron Syntax in the XS Job File
xscron Field (* from left to right)
Meaning and Permitted Value
Year 4-digit, for example, 2013
Month 1 to 12
Day -31 to 31
DayofWeek mon,tue,wed,thu,fri,sat,sun
Hour 0 to 23
Minute 0 to 59
Second 0 to 59
Note
Using the asterisk (*) as a wild card in the seconds eld can lead to some unexpected consequences, if the
scheduled job takes less than 59 seconds to complete; namely, the scheduled job restarts on completion. If
the scheduled job is very short (for example,10 seconds long), it restarts repeatedly until the specied
minute ends.
To prevent short-running jobs from restarting on completion, schedule the job to start at a specic second in
the minute. For example, * * * * * */5 20 indicates that the scheduled job should run every ve minutes
and, in addition, at the 20th second in the specied minute. The job starts at precisely 20 seconds into the
specied minute and runs only once.
The following table illustrates the syntax allowed to dene expressions in the “xscron” entry of the .xsjob
le.
Expression
Where used... Value
* Anywhere Any value
*/a Anywhere Any a-th value
a:b Anywhere Values in range a to b
a:b/c Anywhere Every c-th value between a and b
a.y DayOfWeek On the a-th occurrence of the weekday
y (a = -5 to 5)
a,b,c Anywhere a or b or c
parameter
{
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 83
"schedules": [
{
"description": "Read current stock value",
"xscron": "* * * * * * 59",
"parameter": {
"stock": "SAP.DE",
"share": "BMW.DE"
}
}
]
}
The optional parameter keyword is used in combination with the schedules keyword. The parameter keyword
denes values to be used as input parameters by the XSJS function called as part of the job. You can list as
many parameters as you like, separated by a comma (,) and using the JSON-compliant syntax quotations (“”).
3.7.2 Add or Delete a Job Schedule during Runtime
The $.jobs application programming interface (API) enables you to manipulate the schedules for an XS job at
runtime.
Context
You can use the $.jobs.JobSchedules API to add a schedule to (or delete a schedule from) a job dened in
an .xsjob le at runtime.
Note
Schedules added at runtime are deleted when the .xsjob le is redeployed.
Procedure
1. Create an XS job le using the .xsjob syntax.
Note
If you have already created this XS job le, for example, in another tutorial, you can skip this step.
Create a le called yahoo.xsjob and add the following code:
{
"description": "Read stock value",
"action": "yahoo:yahoo.xsjs::readStock",
"schedules": [
{
"description": "Read current stock value",
"xscron": "* * * * * * 59",
"parameter": {
84
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
"stock": "SAP.DE"
}
}
]
}
Save and activate the changes in the SAP HANA Repository.
Note
Saving a le in a shared project automatically commits the saved version of the le to the repository, To
explicitly commit a le to the repository, right-click the le (or the project containing the le) and
choose Team Commit from the context-sensitive popup menu.
2. Create the XS JavaScript (.xsjs) le you want to use to dene the automatic scheduling of a job at
runtime.
Name the le schedule.xsjs.
3. Use the $.jobs JavaScript API to add or delete a schedule to a job at runtime.
The following example schedule.xsjs adds a new schedule at runtime for the XS job dened in
yahoo.xsjob, but uses the parameter keyword to change the name of the stock price to be checked.
var myjob = new $.jobs.Job({uri:"yahoo.xsjob"});
var id = myjob.schedules.add({
description: "Query another stock",
xscron: "* * * * * * * */10",
parameter: {
stock: "APC.DE"
}
});
// delete a job schedule
// myjob.schedules.delete( {id: id } );
4. Save and activate the changes in the SAP HANA Repository.
5. Call the XS JavaScript service schedule.xsjs to add the new job schedule at runtime.
Related Information
SAP HANA XS JavaScript Reference
XS Job File Keyword Options [page 80]
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 85
3.8 Tracing Server-Side JavaScript
The SAP HANA XS server-side JavaScript API provides tracing functions that enable your application to write
predened messages in the form of application-specic trace output in the xsengine trace les
(xsengine*.trc) according to the trace level you specify, for example, “info”(information) or “error”.
If you use the server-side JavaScript API to enable your application to write trace output, you can choose from
the following trace levels:
debug
info
warning
error
fatal
For example, to enable debug-level tracing for your JavaScript application, include the following code:
$.trace.debug("request path: " + $.request.path);
3.8.1 Trace Server-Side JavaScript Applications
The server-side JavaScript API for SAP HANA XS enables you to activate the writing of messages into a trace
le; the following trace levels are available: debug, error, fatal, info, and warning.
Context
By default, applications write messages of severity level error to the xsengine*.trc trace les; you can
increase the trace level manually, for example, to fatal. In SAP HANA XS, the following steps are required to
enable trace output for your server-side JavaScript application:
Procedure
1. Open the SAP HANA studio.
2. In the Systems view, double-click the SAP HANA instance to open the Administration view for the
repository where your server-side JavaScript source les are located.
3. Choose the Trace Conguration view.
4. In the Database Trace screen area, choose Edit Conguration.
The Edit Conguration icon is only visible if you have the required privileges on the selected SAP HANA
system.
86
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
Note
If the Database Trace screen area is not displayed, check that you are using a version of SAP HANA
studio that is compatible (the same as) with the SAP HANA server where you want to set up tracing.
5. Select the Show All Components checkbox.
6. Enter the partial or full name of your application into the search box.
7. Find the trace matching your application name and choose the trace level you want to use to generate
output.
The application name is the location (package) of the .xsapp le associated with the application you are
tracing. The trace topic is named xsa:<package.path> <appName>.
Note
To set the trace level, click the cell in the System Trace Level column that corresponds with the
application you want to trace and choose the desired trace level from the drop-down list.
8. Choose Finish to activate the trace level changes.
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 87
3.8.2 View XS JavaScript Application Trace Files
The server-side JavaScript API for SAP HANA XS enables you to instruct your JavaScript applications to write
application-specic trace messages in the xsengine*.trc trace les. You can view the trace les in the
Diagnosis Files tab page of the Administration perspective in the SAP HANA studio.
Context
The trace levels “debug”, “error”, “fatal”, “info”, and “warning” are available. To view trace output for your
server-side JavaScript application, perform the following steps:
Procedure
1. Open the SAP HANA studio.
2. In the Systems view, double-click the SAP HANA instance to open the Administration view for the
repository where your server-side JavaScript source les are located.
3. Choose the Diagnosis Files tab page.
4. In the Filter box, enter a string to lter the list of search les displayed, for example, xsengine*.trc.
The timestamp displayed in the Modied column does not always reect the precise time at which the
trace le was written or most recently modied.
5. Locate the trace le for your SAP HANA XS application and doubleclick the entry to display the contents of
the selected trace-le in a separate tab page.
3.9 Debugging Server-Side JavaScript
SAP HANA XS provides a set of dedicated tools to enable you to debug the XS JavaScript code that you write.
To trigger debugging, you need an XS JavaScript conguration.
Overview
To prepare the system for debugging, you need to perform the following high-level steps:
Ensure all prerequisites listed below are met.
Create a debug conguration or choose an existing debug conguration to use.
Set breakpoints in the le you want to debug.
Execute XS JavaScript debugging.
To trigger debugging, you need to choose an XS JavaScript conguration; each conguration type represents a
dierent starting point for debugging an XS JavaScript le. To debug XS JavaScript, you must choose one of
the following types of conguration:
XS JavaScript
88
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
Use to debug a stand-alone XS JavaScript service.
XS JavaScript: Manual Session
Use to debug an XS JavaScript initiated from any remote client using that specic XS session.
XS JavaScript: HTML-based
Use to debug an XS JavaScript initiated from HTML.
XS JavaScript: XS OData-based
Use to debug an XS JavaScript initiated from an XS OData breakout.
Note
Before you start debugging server-side JavaScript on SAP HANA Extended Application Services (SAP
HANA XS), rst check that you have fullled the following prerequisites:
Ensure the delivery unit for SAPHANA XS debugging tools is imported
To import the HANA_XS_BASE.tgz delivery unit (DU) that contains the XS JavaScript debugging tools, in
SAP HANA Studio, choose the option New Import Delivery Unit .
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 89
Enable debugging on the system level:
1. Ensure the SAP HANA XS Web server is running, and that you have HTTP access to the following URL:
http:<SAPHANA_HOSTNAME>:<PortNumber>:/
90
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
2. Start SAP HANA Studio and open the Administration perspective.
3. In the Conguration tab, add a section called xsengine.ini debugger (if it does not exist) and add
(or set) the following parameter: enabled=true
Assign the debugging role to your user
SAP HANA XS provides a dedicated debugger user role; the role must be assigned to any user who wants
to start a debugging session for server-side JavaScript in SAP HANA XS.
Assign the debugging role to another user (optional)
You can grant a user global access to any of your debug sessions or grant access to a debug session that is
agged with a specied token. You can also restrict access to a debug session to a specied period of time.
Note
By default, other users do not have the permissions required to access your XS JavaScript debugging
sessions. However, SAP HANA XS enables you to grant access to your debug sessions to other users,
and vice versa.
1. Start SAP HANA Studio and open the Administration perspective.
2. In the Systems view, expand the Security node and double-click the user to whom you want to assign
the debugger role.
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 91
3. In the Granted Roles view, choose the [+] icon and, in the Select Role dialog, enter debugger to search
for the debugger role and choose OK.
Note
Debugging can also be done in other settings, for example, when a server is cloud-based or when it is a
secured server.
Debugging with HANA Cloud Platform (HCP) (optional)
Debugging using HCP requires prerequisites to be fullled. For more information, see Getting Started in
the SAP HANA Cloud Documentation.
Debugging using a secure server (optional)
Debugging using a secure server requires specic prerequisites to be fullled. For more information,
see Congure SSL for SAP HANA Studio Connections in the SAP HANA Security Guide.
Related Information
Debug Session Access [page 97]
The XSJS Debugger Role [page 96]
Congure TLS/SSL for SAP HANA Studio Connections
3.9.1 Create a Debug Conguration
Context
To create an XS JavaScript debug conguration, do the following:
Procedure
1. Open the Debug perspective.
2. Choose and select Debug Congurations.
3. Choose the debug conguration type you want to debug.
It can be one of the following:
XS JavaScript: Use to debug a standalone XS JavaScript service.
XS JavaScript: Manual Session : Use to debug an XS JavaScript initiated from any remote client using
that specic XS session.
XS JavaScript: HTML-based: Use to debug an XS JavaScript initiated from HTML.
92
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
XS JavaScript: XS OData-based: Use to debug an XS JavaScript initiated from an XS OData breakout.
Note
You can use an existing conguration, change it or create a new debug conguration by selecting the
le type to use for debugging, and clicking on the New button.
4. In the General tab, enter a name for the new debug conguration.
5. The external browser is your default debug mode. You can also choose to debug using the internal SAP
HANA Studio.
6. To build the URL, select the le and resource path or add parameters where relevant. Parameters can be
entered using raw text or a table format.
When creating a manual session debug conguration, you only need to select the system to debug.
If a system is logged o, it will not show in the system dropdown list.
7. You can include stored procedures in your debug conguration which will enable SQL script to be
debugged along with XS JavaScript. If your XS JavaScript code triggers stored procedures, you can set
breakpoints and debug them using the same debug conguration. You do not need to create a separate,
dedicated debug conguration for the stored procedures.
8. For congurations with an Input Parameters tab, select the method, and enter the header and body
information as relevant. Body details can be entered as raw text or in the x-www-form-urlencoded format.
9. Choose Apply.
10. Choose Close to save the conguration for later use or Debug to start debugging.
3.9.2 Execute XS JavaScript Debugging
SAP HANA studio enables you to debug XS JavaScript les, including setting breakpoints and inspecting
variables.
Context
To enable the display of more helpful and verbose information for HTTP 500 exceptions on the SAP HANA XS
Web server, add the parameter developer_mode to the xsengine.ini httpserver section and set it to
true. xsengine.ini is in the Conguration tab of the Administration perspective in SAP HANA studio.
Prerequisites
Ensure that debugging is enabled on the SAP HANA server.
You have the debugger role assigned to your user.
User authentication is enabled. This is required to open the debugging session.
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 93
To start debugging, do the following:
Procedure
1. In a Web browser, run the XS JavaScript source le that you want to debug.
2. Create or choose a debug conguration for debug sessions for a specic SAP HANA installation.
a. Open the Debug view.
b. Choose a debug conguration.
You can also create a new conguration by doing one of the following:
From the menu bar, click Run Debug Conguration Run Debug Congurations .
Select the le to be debugged and right-click, choose Debug As Debug Congurations .
c. Choose Apply.
d. Choose Close.
3. Set Breakpoints
Set breakpoints in the JavaScript code by double-clicking the left vertical ruler.
4. Run the new debug conguration for your server by choosing and selecting your debug
conguration.
You can also run the debug conguration by doing one of the following:
From the menu bar, click Run Debug Congurations , then choose the debug conguration you
want to use.
Select the le to be debugged and right-click on it, and then choose Debug As.
From Debug Congurations, click the debug conguration you want to use.
For an HTML le, select the le to be debugged and right-click on it, then choose Debug As
HTML .
Note
When using the external debug mode, you can only have one open XS debug session per system. This
is relevant for the following debug congurations:
94
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
XS JavaScript
XS JavaScript: HTML-based
XS JavaScript: XS OData-based
Related Information
Create a Debug Conguration [page 92]
3.9.2.1 The Debug Perspective
SAP HANA studio includes a dedicated debug perspective, which provides the tools needed by a developer who
wants to debug server-side JavaScript code.
Application developers can use the SAP HANA studio's Debug perspective to perform standard debugging
tasks, for example: starting and resuming code execution, stepping through code execution, adding
breakpoints to the code. Developers can also inspect variables and check the validity of expressions. The
following views are available as part of the standard Debug perspective:
Debug
Displays the stack frame for the suspended or terminated threads for each target you are debugging. Each
thread in your program appears as a node in the tree. You can also see which process is associated with
each target.
Breakpoints
Displays a list of the breakpoints set in the source le you are currently debugging
Variables
Displays a list of the variables used in the source le you are currently debugging
Expressions,
Displays global variables, such as $.request and other SAP HANA XS JavaScript API objects
Outline
Displays a structural view of the source le you are currently debugging. You can double-click an element
to expand and collapse the contents.
Source-code editor
SAP HANA studio uses the le extension (for example, .js or .xsjs) of the source le you want to debug
and opens the selected le in the appropriate editor. For example, les with the .js or .xsjs le extension
are displayed in the built-in JavaScript editor.
Note
Unied Debugger
In the unied debugger, if you choose to include the SQL script layer in the debugging session, you will see
the targets of both the XS JavaScript and SQL script in the debug view.
If a breakpoint is set in the XS JavaScript or in an SQL script procedure, you will see the breakpoints in the
breakpoint view. The debugger will stop at the breakpoints in the relevant XS JavaScript or in the SQL script
as usual. SQL script debugging behavior is the same in the SQL script debugger as it is in the unied
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 95
debugger, with the exception of the call stack behavior. For more information about debugging SQL script
procedures, see Debugging Procedures.
Related Information
Debugging Procedures
3.9.2.2 The XSJS Debugger Role
The JavaScript debugger included with SAP HANA Extended Application Services (SAP HANA XS) requires
user authentication to start a debug session. SAP HANA XS includes a dedicated debugger role, which denes
the permissions needed by a developer who wants to debug server-side JavaScript code.
Debugging application code is an essential part of the application-development process. SAP HANA Extended
Application Services (SAP HANA XS) includes a debug perspective, a debug view, and a dedicated debugger
role that must be assigned to any developer who wants to debug XS JavaScript. The debugging role is named
sap.hana.xs.debugger::Debugger and can be assigned to a user (or a role) either with the standard role-
assignment feature included in SAP HANA studio (the Application Privileges tab in the Security area of the
Systems view) or in a design-time, role-conguration le (.hdbrole).
96
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
Since a developer primarily needs to debug his own HTTP calls, the following limitations apply to a debug
session:
Only authenticated users can start a debug session, for example, by providing a user name and password
when logging in to a debug session
A user can debug his own sessions.
A user can debug any session to which access has been explicitly granted, for example, by the owner of the
session.
Note
It is also possible to use SSL for debugging. If SSL is congured, the server redirects the Web-socket
connect call to the corresponding SSL (secure HTTP) URL, for example, if sent by plain HTTP.
SAP HANA studio includes a graphical user interface (GUI) which you can use to grant access to debug
sessions at both the session level and the user level.
Related Information
Custom Development Role
3.9.2.3 Debug Session Access
You can grant other developers access to the debug sessions you use for debugging server-side JavaScript on
SAP HANA XS.
By default, other users are not allowed to access your XSJS debugging sessions. However, SAP HANA XS
provides a tool that enables you to grant access to your debugging sessions to other users, too.
Note
You can grant a user global access to any of your sessions or grant access to a session that is agged with a
specied token. You can also restrict access to a debug session to a specied period of time.
The XS Debugging tool is available on the SAP HANA XS Web server at the following URL:
<SAPHANAWebServer>80<SAPHANAinstance>/sap/hana/xs/debugger/.
When you are grant access to your debugging session, the following options are available:
User Name
The name of the database user who requires access to your debug session
Privilege Expires
The point in time that marks the end of the period for which access to one or more debug sessions is
allowed.
grant debug permission for all sessions
You can grant a user global access to any of your debug sessions.
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 97
Restriction
The user you grant access to must already be registered and authenticated in the SAP HANA database.
grant debug permission for this session only
You can grant access to a debug session that is agged with a specic token:
Restriction
Unauthenticated users must use the token-based option.
The following rules apply to access to debug sessions agged with a token:
The session used for granting access to the debug sessions is agged automatically.
The session token is distributed by means of a session cookie; the cookie is inherited by any session
created with the current browser session.
Session Name
A freely denable name that can be used to distinguish your debug session in the context of multiple
sessions.
Related Information
The XSJS Debugger Role [page 96]
Debugging Server-Side JavaScript [page 88]
3.9.3 Troubleshoot Server-Side JavaScript Debugging
When debugging your JavaScript code, you sometimes need to solve problems, not only with the code itself,
but the conguration of the sessions and the tools you use to perform the debugging.
Prerequisites
Start a Web-browser session with the SAP HANA server before starting a debug session.
Make sure you open a session with the SAP HANA server by calling an XS JavaScript le from your Web
browser before starting the debug operation.
Select the session ID.
Before starting to debug, select the session whose ID is specied in the xsSessionId cookie in your open
Web-browser session.
98
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
Context
If you are having problems using the embedded debugging tools to debug your server-side XSJS (JavaScript)
code, check the following solutions:
Breakpoints
The execution of your XS JavaScript code is not stopping at a breakpoint.
Network connections
Your SAP HANA server is behind a proxy or a rewall.
Procedure
1. Restart the SAP HANA studio with the -clean option.
Sample Code
hdbstudio.exe -clean
To determine if a clean restart of SAP HANA studio is required, check if the Breakpoints view in SAP HANA
studio's Debug perspective displays the breakpoints as type SAP HANA XSE Script, as follows:
a. In the Breakpoints view, choose the View Menu.
b. Choose Group By Breakpoint Types
2. Remove breakpoints.
Try removing all the existing breakpoints from the debug session and recreating them.
3. Create a new workspace.
If a restart of SAP HANA studio with the -clean option does not solve the problem of unrecognized
breakpoints, it might be necessary to create a new Eclipse (not repository) Workspace.
4. Set the Active Provider feature to manual.
If your SAP HANA server is behind a proxy or rewall, check that your Network Connections are congured
for using a proxy, as follows:
Note
It is not recommended to run a debugging session without using the Secure Sockets Layer (SSL)
protocol. The debugging session uses standard HTTP(S). The session either leverages an existing
session or requests basic (HTTP) authentication on the connection request. The debugging session
upgrades the HTTP connection to a WebSocket.
a. In SAP HANA studio, choose Window Preferences General Network Connections .
b. Set the Active Provider to Manual.
The default setting is Native
c. Update the schemas.
d. Add the relevant proxy host and port.
5. Congure the Debug Conguration Connection properties.
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 99
a. Select and right-click your SAP HANA system.
b. Choose Properties XS Properties .
c. Check that your system's SAP HANA XS properties match the Debug Conguration Connection
properties.
Related Information
Execute XS JavaScript Debugging [page 93]
3.10 Testing XS JavaScript Applications
SAP HANA provides a test framework called XSUnit that enables you to set up automatic tests for SAP HANA
XS applications.
The test framework SAP HANA XSUnit (XSUnit) is a custom version of the open-source JavaScript test
framework, Jasmine, adapted for use with SAP HANA XS. You can use the XSUnit test framework to automate
the tests that you want to run for SAP HANA XS applications, for example, to test the following elements:
Server side JavaScript code
SQLScript code (stored procedures and views)
Modeled calculation views
To use the tools and features provided with the XSUnit test framework, you must perform the following high-
level steps:
1. Set up the client-side environment:
Install the latest version of SAP HANA studio (optional).
Ensure that the hdbclient tool is installed and running.
2. Set up the server-side environment.
The XSUnit test framework is included in the delivery unit HANA_TEST_TOOLS, which you must install
manually, for example, using the SAP HANA studio or the SAP HANA Application Lifecycle Management
tool. After the installation completes, the tools are available in the package sap.hana.testtools.
Note
Importing a delivery unit into an SAP HANA system requires the REPO.IMPORT privilege, which is
normally granted only to the system administrator.
3. Maintain SAP HANA user privileges.
The system administrator must grant test users the privileges required to use the test tools. The privileges
are dened in roles, which the SAP HANA administrator can assign to all developers by default.
4. Maintain the test schema (optional).
If you write XSUnit tests that are designed to test database content, you require a test schema in which you
create test tables during your test execution and ll the tables with test data. To avoid conicts when
dierent users run the same test at the same time, it is recommended that individual developers place test
tables in their corresponding user schema.
100
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
Note
You must ensure that _SYS_REPO has select permission to schema where the tables are located (for
example, either your user schema or the test schema).
grant select on schema MY_TEST_SCHEMA to _SYS_REPO with grant option;
Related Information
Automated Tests with XSUnit in SAP HANA [page 101]
XSUnit Test Examples [page 109]
SAP HANA XSUnit JavaScript API Reference
3.10.1 Automated Tests with XSUnit in SAP HANA
XSUnit is an integrated test environment that enables you to set up automatic tests for SAP HANA XS
applications.
People developing applications in the context of the SAP HANA database need to understand how to
implement a test-automation strategy. Especially for new applications which are designed to work exclusively
with SAP HANA, it is a good idea to consider the adoption of best practices and tools.
If you want to develop content that is designed to run specically in SAP HANA, it is strongly recommended to
use the XSUnit test framework that is integrated in SAP HANA XS; this is the only way to transport your test
code with your SAP HANA content. The XSUnit tools are based on a Java Script unit test framework that uses
Jasmine as the underlying test library.
Test Isolation and Simulation
To write self-contained unit tests that are executable in any system, you have to test the various SAP HANA
objects in isolation. For example, an SAP HANA view typically has dependencies to other views or to database
tables; these dependencies pass data to the view that is being tested and must not be controlled or overwritten
by the test. For this reason, you need to be able to simulate dependencies on the tested view. XSUnit includes a
test-isolation tool that provides this functionality; it allows you to copy a table for testing purposes.
Note
Although you cannot copy a view for testing purposes, you can create a table that acts like a view.
All (or specic) dependencies on any tables or views are replaced by references to temporary tables, which can
be created, controlled, and populated with values provided by the automated test.
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 101
Test Data
Preparing and organizing test data is an important part of the process of testing SAP HANA content such as
views and procedures; specic data constellations are required that have to be stable in order to produce
reliable regression tests. In addition, test-isolation tools help reduce the scope of a test by enabling you to test
a view without worrying about dependent tables and views. Limiting the scope of a test also helps to reduces
the amount of data which needs to be prepared for the test.
Related Information
XSUnit Test Examples [page 109]
Test an SAP HANA XS Application with XSUnit [page 102]
3.10.2 Application Development Testing Roles
Dedicated roles enable developers to access and use the tools provided with the SAP HANA XS test framework
(XSUnit).
To grant access to the SAP HANA XS test framework that enables developers to set up automatic testing for
SAP HANA applications, the SAP HANA system administrator must ensure that the appropriate roles are
assigned. The following table lists the roles that are available; one (or more) of the listed roles must be assigned
to the application developers who want to use the XSUnit testing tools.
Default Developer Testing Roles
Role Name
Description
sap.hana.testtools.common::TestExe
cute
Enables you to view the persisted test results produced by the XSUnit test frame
work and to execute the examples included in the demonstration package
(
sap.hana.testtools.demo).
sap.hana.xs.debugger::Debugger Enables you to debug your server side JavaScript (test-)code
sap.hana.xs.ide.roles::Developer Enables you to view source les in the SAP HANA Web-based Work Bench (Web
IDE)
3.10.3 Test an SAP HANA XS Application with XSUnit
Use the XSUnit tools to set up automated testing of your applications in SAP HANA XS.
Prerequisites
The following prerequisites apply if you are using SAP HANA studio to set up and run tests with XSUnit:
102
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
SAP HANA studio
You will need access to a shared development project in the SAP HANA system where you plan to run the
tests.
Context
If you want to develop content that is designed to run specically with SAP HANA, you can use the XSUnit tools
that are integrated in SAP HANA XS. The XS Unit tools are based on a Java Script unit test framework that uses
Jasmine as the underlying test library.
Procedure
1. Create an Eclipse project.
If you want to create your rst unit test, you need an XS Project that will contain the test code. You can
either create a new shared XS Project or, if a shared project already exists, you can checkout and import
the existing project from the SAP HANA Repository. Within that project you can structure your tests in
folders.
To create a shared Eclipse project, start SAP HANA studio and, in the SAP HANA Development perspective,
perform the following steps:
a. In the Systems view, add the SAP HANA system you want to work and test on.
b. In the Repositories view, add a repository workspace for your SAP HANA system
c. Create and share a project of type XS Project.
Tip
You can also check out and import an existing project from the SAP HANA Repository.
2. Create an XSUnit test.
XSUnit test les are XSlibrary les (les with the .xsjslib sux).
a. Create an XSlibrary le, for example, called <MyFirstTest>.xsjslib.
You can use the le-creation Wizard in SAP HANA studio, for example, File New Other SAP
HANA Development
XS JavaScript Library File
b. Add the following content to the new XSlibrary test le <MyFirstTest>.xsjslib.
/*global jasmine, describe, beforeOnce, beforeEach, it, xit, expect*/
describe("My First Test Suite using Jasmine", function() {
it('should show an assertion that passes', function() {
expect(1).toBe(1);
});
it("should show an negative assertion", function() {
expect(true).not.toBe(false);
});
it("should throw an expected error", function() {
expect(function() {
throw new Error("expected error");
}).toThrowError("expected error");
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 103
});
//xit = this test case is excluded
xit("should show an assertion that fails", function() {
expect(1).toBe(2);
});
});
The JSLint tool that SAP HANA studio uses to check your XSJS code tells you that functions (for
example, describe, it, expect) do not exist. This is not true; the functions do exist but they are
dened in another library. To ensure that JSLint considers functions to be globally available, add the
following comment as the rst line of the XSUnit test le: /*global jasmine, describe,
beforeOnce, beforeEach, it, xit, expect*/
Note
You can extend the list of globally available functions to include any additional functions that you
use in your test.
c. Save the test le.
d. Activate the test le.
In the SAP HANA studio's SAP HANA Development perspective, open the Project Explorer view, right-
click the test le, and choose Team Activate .
3. Execute the XSUnit test.
How you execute an XSUnit test depends on the development tool suite you are using, for example, SAP
HANA studio.
You execute an XSUnit test by entering the following URL in a Web Browser:
http://<hostname>:<port>/sap/hana/testtools/unit/jasminexs/TestRunner.xsjs?
package=
<packageName>
Where <hostname> is the name of the SAP HANA system where you are running your application test, and
<port> is the port number that the SAP HANA instance is available on.
The TestRunner tool recursively searches the package <packageName> for any les with the
sux .xsjslib whose names match the pattern “*Test”.
Note
If you want to search for a string other than “*Test”, you must pass a custom pattern to TestRunner
using the parameter pattern.
Related Information
XSUnit Test Run Options [page 107]
104
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
3.10.3.1 XSUnit's Enhanced Jasmine Syntax
The XSUnit test framework is a custom version of the JavaScript test framework Jasmine adapted to suit SAP
HANA XS.
A test specications begin with a call to the global Jasmine function describe. The describe functions
dene suites that enable you to group together related test suites and specications. Test-suite specications
are dened by calling the global Jasmine function it. You can group several test suites in one test le. The
following code snippet shows one test suite (introduced by the function
describe”) and two test
specications, indicated by the function “it”.
/*jslint undef:true */
describe('testSuiteDescription', function() {
beforeOnce(function() {
// beforeOnce function is called once for all specifications
});
beforeEach(function() {
// beforeEach function is called before each specification
});
it('testSpecDescription', function() {
expect(1).toEqual(1);
});
it('anotherTestSpecDescription', function() {
expect(1).not.toEqual(0);
});
});
To enable a test suite to remove any duplicate setup and teardown code, Jasmine provides the global functions
beforeEach and afterEach. As the name implies the beforeEach function is executed before each
specication in the enclosing suite and all sub-suites; the afterEach function is called after each
specication. Similarly, the special methods beforeOnce and afterOnce are called once per test suite.
beforeOnce
Executed once before all specications of the test suite
afterOnce
Executed once after all specications of the test suite
Database Connection Setup
The XSUnit framework provides a managed database connection called jasmine.dbConnection, which is
globally available. You can use it in the following scenarios:
Directly (in the function “it”)
In the functions “beforeEach” and “afterEach
In other functions dened in your test libraries
In imported libraries (if you have moved test code to external libraries)
One obvious advantage of this is that you no longer have to pass the database connection as a parameter or
dene it as a global variable. The jasmine.dbConnection is opened automatically and rolled back (and
closed). However, if you want to persist your data, you have to commit() jasmine.dbConnection manually.
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 105
XSUnit TestRunner Tool Flow Chart
3.10.3.2 XSUnit Test Tools Syntax
Example syntax for the functions, assertions, and parameters required by the SAP HANA XSUnit test tools.
The following code example lists the most commonly used functions and assertions used in the XSUnit
syntax.For more information about the assertions used, for example, toBe, toBeTruthy, or toBeFalsy, see
Assertions.
/*global jasmine, describe, beforeOnce, beforeEach, it, xit, expect*/
describe("My First Test Suite using Jasmine", function() {
beforeOnce(function() {
// beforeOnce is called only one time for all specs
});
beforeEach(function() {
// beforeEach is called before each specs
});
// it = test case specification it("should show an assertion that passes",
function() {
var array = [{foo: 'bar', baz: 'quux'}, {bar: 'foo', quux: 'baz'}];
expect(1).toBeTruthy();
expect(12).toBe(jasmine.any(Number));
expect(array).toContain(jasmine.objectContaining({foo: 'bar' }));
});
it("should show an negative assertion", function() {
expect(true).not.toBe(false);
106
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
});
it("should throw an expected error", function() {
expect(function() {
throw new Error("expected error");
}).toThrowError("expected error");
});
// xit = this test case is excluded
xit("should show an assertion that fails", function() {
expect(1).toBe(2);
});
});
XSUnit Assertions and Parameters
The following code example lists the most commonly used assertions, shows the required syntax, and the
expected parameters.
expect(actual).toBe(expected);
expect(actual).toBeFalsy();
expect(actual).toBeTruthy()
expect(actual).toEqual(expected);
expect(actualArray).toContain(expectedItem);
expect(actual).toBeNull();
expect(actualNumber).toBeCloseTo(expectedNumber, precision);
expect(actual).toBeDefined();
expect(actual).toBeUndefined();
expect(actualString).toMatch(regExpression);
expect(actualFunction).toThrowError(expectedErrorMessage);
expect(actualFunction).toThrowError(expectedErrorType, expectedErrorMessage);
expect(actualTableDataSet).toMatchData(expected, keyFields);
expect(actual).toBeLessThan(expected);
expect(actual).toBeGreaterThan(expected);
3.10.3.3 XSUnit Test Run Options
The XSUnit tool suite includes a generic tool that you can use to run tests.
You can start the XSUnit test-running tool (TestRunner.xsjs) by entering the following URL in a Web
Browser:
http://<hostname>:80<HANAinstancenumber>/sap/hana/testtools/unit/jasminexs/
TestRunner.xsjs?<parameters>
The following table lists the parameters that you can use to control the behavior of test-runner tool. If you
execute the test runner without specifying the pattern parameter, only the tests in *Test.xsjslib les are
discovered (and run) within the package hierarchy.
Note
You can specify multiple parameters by separating each parameter=value pair with the ampersand
character (&), for example:
coverage=true&exclude=sap.hana.tests
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 107
TestRunner.xsjs Parameters
Name Mandatory Description
package yes Package that acts as starting point for discovering the tests. If not otherwise
specied by parameter “pattern” all .xsjslib les in this package and its sub-pack
ages conforming to the naming pattern “*Test” will be assumed to contain tests
and will be executed.
package=sap.hana.testtools.demo
pattern
no Naming pattern that identies the .xsjslib les that contain the tests. If not speci
ed, the pattern “*Test” is applied. You can use question mark (?) and asterisk (*)
as wildcards to match a single or multiple arbitrary characters, respectively. To
match all “
Suite.xsjslibles, use the following code:
pattern=Suite
format
no Species the output format the test runner uses to report test results. By default,
the results will be reported as HTML document. This parameter has no eect if a
custom reporter is provided via parameter “reporter”. To display outputs results
using the JSON format, use the following code:
format=json
reporter
no Complete path to module that provides an implementation of the Jasmine re
porter interface. With this parameter a custom reporter can be passed to publish
the test results in an application specic format . To specify the reporter interface,
use the following code:
reporter=sap.hana.testtools.unit.jasminexs.reporter.db
.dbReporter
Note
format=db produces the same result
tags
no Comma-separated list of tags which is used to dene the tests to be executed.
tags=integration,long_running
prole no Name of a "prole" dened in the test which lters the tests to be executed on the
basis of tags.
profile=end2end
coverage no Activate code coverage measurement for all server-side (XS) JavaScript code
that is executed by the tests or which is in the scope of a specied package.
coverage=true
coverage=sap.hana.testtools.mockstar
coverage=true&exclude=sap.hana.testtools.mockstar.test
s
108 P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
3.10.3.4 XSUnit Test Examples
XSUnit includes a selection of test packages that demonstrate the scope of tests you can perform on an SAP
HANA XS application.
The following table lists the test packages included in the XSUnit test framework. The table also indicates the
name of the test le and provides a quick overview of the scope of the test.
Note
If you want to have a look at the code in the tests, checkout the package sap.hana.testtools.demo as
an XS project to your local workspace.
ExampleTest Units
Package Name
Test Name (.xsjslib) Description
tests.getting_started myFirstTest Shows the usage of some basic Jas
mine matchers as well as the usage of
custom matchers
toMatchData and
toEqualObject that are supported
by the extended Jasmine version.
tests.attribute_view_1
AT_PRODUCTS_Test Shows how to congure mockstar in or
der to replace a CDS entity with a test
table. Be aware that this test does not
make sense, as this attribute test tests
nothing at all - no logic, no joins,...
tests.graphic_calcview_1
CA_ORDERS_Test Tests a copy of the graphical calculation
view where the direct dependent tables
are replaced by test tables.
tests.graphic_calcview_3 CA_OPEN_AMOUNT_Test Tests the integration with the analytic
view but replaces the dependencies to
the tables with test tables. This exam
ple test shows how to upload data from
a comma-separated-values (CSV) le
into the test tables
tests.hdbprocedure_with_cds
CreateProductTest Tests a non-read-only HDBProcedure
with table in/out parameters while re
placing the underlying Core Data Serv
ices (CDS) entities with test tables.
tests.hdbprocedure_with_hdbview
GetInvoicesTest
Tests an HDBProcedure with scalar in
and view out parameters while replac
ing a dependent hdbview with a test
table.
tests.hdbprocedure_with_hierarchy
view
HierarchyProcedureTest Tests an HDBProcedure that includes a
hierarchy view while replacing all under
lying CDS entities with test tables.
tests.hdbprocedure_with_hdbproce
dure
CreateProductTest Tests an HDBProcedure while replacing
a dependent
hdbprocedure with an
hdbprocedure that was created for
testing.
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 109
Package Name Test Name (.xsjslib) Description
tests.http_service whoAmIServiceTestE2E Tests an http service and checks if it re
turns the expected value. This test is
not automatically executed since the
SAP HANA instance needs to be main
tained by the system administrator.
tests.procedure_1
PR_OPEN_AMOUNT_Test Tests a copy of the stored procedure
where the directly dependent tables are
replaced with test tables.
tests.scripted_calcview_1 CA_ABC_PRODUCTS_Test Tests a copy of the scripted calculation
view where the directly dependent ana
lytic view is replaced with a test table.
tests.scripted_calcview_2 CA_OPEN_AMOUNT_SCRIPTED_W_PR
OCEDURE_Test
Tests the integration with the called
stored procedures but replaces the de
pendencies to the tables with test ta
bles.
apps.rating.tests
validatorTest Tests a simple server-side (XS) Java
Script.
dataAccessorTest Tests the database layer of server-side
(XS) JavaScript using Jasmine
spyOn() for testing in isolation.
oDataTestE2E Checks the accessibility of an OData
service and tests an OData service
without dependencies using mockstar.
ratingServicesTestE2E Tests an XS JavaScript service (end-to-
end scenario test).
tests myMockstarEnvironment Shows how to enhance the
mockstarEnvironment library to
add further reuse functions or change
the behaviour slightly to suit the con
text.
3.10.3.5 The Mockstar Test Environment
Mockstar is a tool that is designed to enable you to isolate SAP HANA content in tests run by an automated test
suite.
To write self-contained unit tests that are executable in any system, it is essential to be able to test the selected
SAP HANA objects in isolation. For a typical unit test using the XSUnit tools, you need to be able to change any
direct dependencies between the tested objects and other views or tables with references to simple tables. For
integration tests, rather than change the direct dependencies to a view or a table, you might need to change
dependencies between the dependent views (deeper in the dependency hierarchy).
Mockstar is a tool that is specically designed to enable you to isolate test objects, for example, a view or
procedure. Mockstar allows you to create a copy of the tested view or procedure and substitute the
dependency to a another view or table with a table that is stored in a test schema. It is strongly recommended
to use a dedicated schema for the tests; in this test schema, you have write permissions and, as a result, full
control over the data in the tables and views.
110
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
The Mockstart test-isolation tool provides the following features:
Creates a copy of the SAP HANA object to test (for example, a view or database table); the copied object
retains the same business logic as the original one object, but replaces some or all dependencies.
Replaces the (static) dependencies to tables or views with temporary tables
Supports deep dependency substitution
Mockstar can determine dependencies deep within a hierarchy of dependencies and copy only the
necessary parts of the hierarchy.
Mockstar tools are included in the delivery unit HANA_TEST_TOOLS, which you must install manually, for
example, using the SAP HANA studio or the SAP HANA Application Lifecycle Management tool. After the
installation completes, the Mockstar tools are available in the package sap.hana.testtools.mockstar.
Note
Importing a delivery unit into an SAP HANA system requires the REPO.IMPORT privilege, which is normally
granted only to the system administrator.
3.10.3.6 Mockstar Environment Example Syntax
A basic example of the syntax required to set up the Mockstar test environment.
The following example shows a simple setup using standard locations.
Note
The names of schemas, tables, and views used in the following code example are intended to be for
illustration purposes only.
var mockstarEnvironment = $.import('sap.hana.testtools.mockstar',
'mockstarEnvironment');
describe('testSuiteDescription', function() {
var testEnvironment = null;
beforeOnce(function() {
var definition = {
schema : 'SCHEMA',
model : {
schema : '_SYS_BIC',
name : 'modelName' //e.g. package/MODEL
},
substituteTables : {
"table" : { name : 'package::TABLE' }
},
substituteViews : {
"view" : {
schema : '_SYS_BIC',
name : 'package/VIEW'
}
}
};
testEnvironment = mockstarEnvironment.defineAndCreate(definition);
});
});
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 111
3.10.3.7 XSUnit Troubleshooting Solutions
Use trace les and other tools to x problems with test operations.
The Mockstar test-isolation tools write helpful information in the SAP HANA trace les. You can adapt the trace
level, for example, to debug to ensure the right amount and type of information is written during the test run.
Note that you need the corresponding administration role to be able to change the trace-level settings in
SAP
HANA. The trace les are written in the trace component xsa:sap.hana.testtools (truncated to
“xsa:sap.hana.tes” in the trace les).
Tip
As an alternative to reading the trace les directly, you can also use the SQL console to select data from the
table M_MERGED_TRACES.
This section contains information about the problems that developers frequently encounter during test runs:
SAP HANA Test Tools Version [page 112]
The Library is Not Part of an Application [page 112]
Error for Cloned OData Service [page 113]
Duplicate Entries When Inserting Test Data [page 113]
Test Table Already Exists [page 113]
Test Model Activation Fails [page 114]
No Entries Returned From Copied Test Model [page 114]
No Test Data Inserted into Test Table [page 114]
TestRunner Tool Times Out [page 115]
Test Model Creation is Aborted [page 116]
Database Connections in XSUnit Test [page 116]
SAP HANA Test Tools Version
Which version of the SAP HANA test tools suite is installed?
1. Start SAP HANA studio
2. Open the SAP HANA Modeler perspective.
3. In the Quick Launch window, choose Delivery Units...
4. Choose HANA_TEST_TOOLS.
Import Error: The Library is Not Part of an Application
If the test runner tool shows the following error:
import: the library is not part of an application
The JavaScript library you want to test can only be loaded when there is an application descriptor (.xsapp le)
dened within the package hierarchy. The application descriptor is the core le that you use to describe an
112
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
application's framework within SAP HANA XS. If your tests are not part of your application package hierarchy, it
is recommended you to create an .xsapp le in the context of the XS Project that contains the tests.
Error for Cloned OData Service
The following error message is displayed when testing access to an OData service in SAP HANA XS:
404 - Not found: Error for cloned OData Service (.xsodata)
Try the following solutions:
1. Try to access the generated service directly in a separate Web browser.
2. Check whether the le (xsodata service denition) exists, has been activated in the SAP HANA repository,
and is in the expected target folder.
3. Ensure that the target folder or one of its parent folders contains the following activated artifacts:
.xsapp le
Application descriptor le required by an SAP HANA XS application
.xsaccess le
Application access le which enables access to an SAP HANA XS application
Duplicate Entries When Inserting Test Data
If you encounter problems concerning duplicate entries when running tests, try the following solutions:
1. When inserting records into a productive table, ensure that no jasmine.dbConnection.commit() call
occurs during test execution.
2. When inserting records into a test table, ensure that the table entries are deleted (dropped) before they are
(re)created.
var tableUtils = new TableUtils(jasmine.dbConnection);
tableUtils.clearTableInUserSchema(invoicesTestTable);
Test Table Already Exists
You encounter an error message that explains that a test table cannot be created during the test because the
table already exists. You must ensure that the specied table is deleted before the test tries to create it during
the test run.
var sqlExecutor = new SqlExecutor(jasmine.dbConnection);
var createTableString = 'CREATE COLUMN TABLE ' + <table name> + '...' );
sqlExecutor.execSingleIgnoreFailing('drop table ' + <table name> );
sqlExecutor.execSingle(createTableString );
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 113
You can also use the functions provided by the table utilitites library, which enables you to ensure that the table
is dropped at the right time:
var tableUtils = new TableUtils(jasmine.dbConnection);
testTable = tableUtils.copyIntoUserSchema(originSchema, originTable);
Test Model Activation Fails
Your test produces an error relating to a failed activation:
Error: Repository: Activation failed for at least one object [...]
identifier is too long:[...]
Maximum length is 127: ...
the name of the model is too long (including the package name). You can reduce the name by setting the
TruncOptions option as shown in the following code snippet:
var mockstar = $.sap.hana.testtools.mockstar;
testView = mockstar.apiFacade.createTestModel(originalModel,
targetPackage, dependencySubstitutions, mockstar.TruncOptions.FULL);
Tip
Its a good idea to analyze the created model before it is activated.
To generate a detailed and structured error log, in the SAP HANA Systems view in the SAP HANA studio and
locate the test package and activate it manually.
No Entries Returned From Copied Test Model
1. Open the generated test model.
The generated model is located in a package with the name
tmp.unittest.<userName>.<originalPackage>. If you have congured the createTestModel()
function with the parameter mockstar.TruncOptions.FULL, the package name is
tmp.unittest.<userName>.
2. Ensure that the dependencies have been replaced as expected.
To see if the tables are lled correctly by the test, see No Test Data Inserted into Test Table [page 114].
3. Check the test view itself.
If the tested view returns no data, but data are expected, check if the data are removed by a lter during
extraction from the underlying data source.
No Test Data Inserted into Test Table
To test whether a test inserts data as expected into the created test table, implement a
jasmine.dbConnection.commit( ) connection to ensure that the data created during the test is stored
114
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
persistently. Without the jasmine.dbConnection.commit( ), the test data is not persistent; the test
deletes all test data when the database session is closed. Start the test again using the TestRunner tool. When
the test completes, the test table should contain test data.
TestRunner Tool Times Out
The default timeout setting for the TestRunner tool is ten (10) minutes. If your test run for longer than ten
minutes and cause a timeout, try splitting the test into smaller and shorter elements. If this is no possible, try
running the test in three phases:
1. Prepare the test run.
/sap/hana/testtools/unit/jasminexs/PrepareTestRun.xsjs
This generates a new test-run ID; no test runs are executed.
Response:
Returns the new test-run ID. If you request the answer in HTML format and provide all required
parameters for the TestRunner tool, you receive the appropriate links you can use in the following
steps (run the test and fetch the results).
Parameters:
format (optional; default = “html”)
Set this parameter to receive the test-run ID in the desired format. You can use any of the formats
supported by the TestRunner format parameter.
2. Run the tests.
/sap/hana/testtools/unit/jasminexs/TestRunner.xsjs
This step is almost identical to the usual test execution with the addition of parameter runid.
Response:
If the tests nish within the congured time frame, you receive the test results as expected. If the test
are too long,a timeout occurs.
Parameters:
runid. Required for this kind of (manual) execution: This is the test-run ID generated in the previous
step.
3. Fetch the test results (optional: only required if the test run causes a timeout).
/sap/hana/testtools/unit/jasminexs/GetTestResults.xsjs
Fetches the test results for a given test-run ID. You an run this service multiple times for each test.
Response:
Returns the test results in the requested format. If the tests are not yet nished, you receive a status
message (either “PREPARED” or “STARTED”). If the run ID provided does not exist, an error message is
displayed.
Parameters:
runid. Required for this kind of (manual) execution.
format (optional; default = “html”)
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 115
Test Model Creation is Aborted
This error sometimes occurs if you try to create a copy of the original view and replace some dependencies
with test tables. The reason for the error is one of the following:
You did not provide any dependency substitutions. For example, you passed an empty array as the third
parameter of mockstar.createTestModel()).
The view that you want to test does not depend on any of the original views specied in the dependency
substitutions.
For active schema mapping, you have written the dependencies with the physical schema whereas the
view refers to the authoring schema. Provide the schema in the same way as it is written in the view (or
stored procedure).
Database Connections in XSUnit Test
The XSUnit test framework provides a new “managed” database connection called jasmine.dbConnection,
which is automatically opened and rolled back (and closed) after each test completes. You can use it in
beforeEach or afterEach functions, in other functions dened in your test libraries, or even in imported
libraries, in the event that you have moved test code into external libraries.
Related Information
Managed Database Connection Setup [page 105]
3.10.4 Testing JavaScript with XSUnit
Test an XS JavaScript using XSUnit test tools.
As the XSUnit test tools are based on a custom version of the JavaScript test framework Jasmine, you can use
XSUnit to test JavaScript. XSUnit provides tools that enable you to create and install a test “double” for one or
more object methods. In the Jasmine framework, a test double is known as a “spy”. A spy can be used not only
to stub any function but also to track calls to it and all arguments, too.
Note
XSUnit includes special matchers that enable interaction with Jasmine spies.
The XSUnit test tools delivery unit (DU) includes a small XS JavaScript demo “Ratings” application which
comprises an SAPUI5 client front end on top of OData and XS JavaScript services; the Ratings application
enables you to experiment with dierent test techniques. You can try out the application at the following URL:
http://<SAPHANA_host>:80<instancenumber>/sap/hana/testtools/demo/apps/rating/
WebContent/
116
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
Related Information
XSUnit's Jasmine Spy Syntax [page 117]
Testing HTTP Services with XSUnit [page 118]
3.10.4.1 XSUnit's Jasmine Spy Syntax
A command “cheat sheet” for the Jasmine Spy syntax.
The following code example provides a quick overview of commonly used commands that enable the use of
Jasmine Spies. You can see how to perform the following actions:
Install a method double [page 117]
Install an object double [page 117]
Check a function call (and values) [page 118]
Installing a Method Double
The following code example shows how install a method double (simple example).
spyOn(object, "method");
expect(object.method).toHaveBeenCalled();
The following code example shows how install a method double (variant).
var spyMethod = spyOn(object, "method");
expect(spyMethod).toHaveBeenCalled();
The following code example shows how install a method double (custom action for double).
spyOn(object, "method"); // delegates nowhere
spyOn(object, "method").and.returnValue(3); // returns constant value
spyOn(object, "method").and.callThrough(); // delegates to original function
spyOn(object, "method").and.callFake(fakeFunction); // delegates to other
function
Installing an Object Double
The following code example shows how install an object double.
var spyObject = jasmine.createSpyObj("spy name", [ "method1", "method2",
"method3" ]);
spyObject.method1.and.returnValue(3);
expect(spyObject.method1).toHaveBeenCalled();
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 117
Checking Function Calls (and Values)
The following code example shows how to check whether the function has been called as expected, and if so, if
the the right values were used.
expect(spyObject.method).toHaveBeenCalled();
expect(spyObject.method).toHaveBeenCalledWith(expArgValue1, expArgValue2);
expect(spyObject.method.calls.allArgs()).toContain([ expArgValue1,
expArgValue2 ]);
expect(spyObject.method.calls.mostRecent().args).toEqual([ expArgVal1,
expArgVal2 ]);
expect(spyObject.method.calls.count()).toBe(2);
spyObject.method.calls.reset(); // reset all calls
3.10.4.2 Testing HTTP Services with XSUnit
XS JavaScript les that can be accessed by performing an HTTP call against the service dened in the XS
JavaScript le.
You can use the TestRunner tool to call an XS JavaScript service. The TestRunner service is part of the test-
tools package sap.hana.testtools.unit.jasminexs and has one mandatory parameter, namely
package. Since TestRunner is an HTTP GET service, you can execute the service in the browser using the
following URL:
http://<hostname>:80<instancenumber>/sap/hana/testtools/unit/jasminexs/
TestRunner.xsjs?package=<mypackage>
Since it is not possible to import XS Javascript les (.xsjs) les into a JavaScript library (.xsjslib), the
functions you implement inside the XS JavaScript le cannot be tested within an XSUnit test. As a
consequence, it is recommended to include only minimal logic within the XSJS les and delegate tasks to the
functions implemented in corresponding JavaScript libraries; these libraries can be tested in isolation using
XSUnit tools (for example, Mockstar).
Note
XSUnit enables you to perform an HTTP call to your XSJS services via HTTP. However, this is an end-to-end
system test with no possibility to use test doubles during the test. These tests are not suitable for testing a
JavaScript function.
Since you cannot insert test data into the test table during the test, the tests have no control over the data. This
restriction reduces the scope of the tests you can perform for HTTP calls, for example, you can test the
following scenarios:
Service must return an error if mandatory parameters are missing
Service must return an error if the chosen HTTP type is correct
Service must return an error if the wrong input is provided
End-to-end HTTP scenarios (CREATE, READ, UPDATE, and DELETE)
describe("example for http tests", function() {
it("should receive answer from service", function() {
var requestBody = '{"param1":42,"param2":"xyz"}';
var headers = {
118
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
"Content-Type" : "application/json"
};
var response = jasmine.callHTTPService("/path/to/your/app/Service.xsjs",
$.net.http.POST, requestBody, headers);
expect(response.status).toBe($.net.http.OK);
var body = response.body ? response.body.asString() : "";
expect(body).toMatch(/regular expression that checks correct response/);
});
});
SAP HANA Database Logon for XSUnit
To ensure access to SAP HANA, you need to adapt the default HTTP destination le
(:localhost.xshttpdest) provided with the XSUnit test tools. The default HTTP destination conguration
le is located in sap.hana.testtools.unit.jasminexs.lib:localhost.xshttpdest to t to your
HANA instance. To access an HTTP destination conguration, you need the permissions granted in the user
role sap.hana.xs.admin.roles::HTTPDestAdministrator.
Caution
To change the HTTP destination, create an HTTP extension" of your own; do not make any changes to the
le localhost.xshttpdest. Changes to localhost.xshttpdest are overwritten by updates to the
XSUnit test tools on your system.
Related Information
Maintaining HTTP Destinations
3.10.4.3 Testing JavaScript Functions with XSUnit
Use XSUnit tools to test JavaScript code that depends on functions in your code, for example: dependencies on
functions, libraries, or to database tables.
In JavaScript it is possible to overwrite anything that is visible in a context, for example: public data, public
functions, or even the whole class. With XSUnit, you can make use of a simulation framework that is included
with Jasmine. The simulation framework provides a mechanism that enables you to create and install a test
double (so-called Jasmine “Spy”), which can help you to reduce some of the basic code and keep the code
more concise. Jasmine Spies should be created in the test setup, before you dene any expectations. The
Spies can then be checked, using the standard Jasmine expectation syntax. You can check if a Spy is called (or
not) and nd out what (if any) parameters were used in the call. Spies are removed at the end of every test
specication.
Note
Each dependency increases the complexity of testing involved for a function or a component.
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 119
The Average Component Dependency (ACD) is the number of dependencies to other components, averaged
over all components; it indicates whether your system is loosely coupled. If you prefer to implement JavaScript
in an object-oriented way, you can apply dependency management aspects by following object-oriented design
principles (OOD).
The information in this topic covers the following test scenarios:
Dependencies on Function Libraries [page 120]
Dependency on Database Table [page 121]
Dependencies on Function Libraries
The following code snippet denes a controller that you want to test; the controller depends on a Date object.
The accompanying code snippet shows how you can test this code.
var Controller = null;
(function() {
//constructor function
Controller = function(dataModel) {
this.model = dataModel;
};
function updateModelWithTimestamp(newData) {
this.model.updateData(newData, this.getCurrentDate());
}
Controller.prototype.updateModel = function(newData) {
//bind 'this' to the private function
updateModelWithTimestamp.call(this, newData);
};
Controller.prototype.getCurrentDate = function() {
return new Date(Date.now());
};
}());
function DataModel() {
var modifiedAt = null;
var modifiedBy = null;
var data = null;
this.updateData = function(newData, modifiedAtDate) {
data = newData;
modifiedAt = modifiedAtDate;
modifiedBy = $.session.getUsername();
};
this.getModificationDate = function() {
return modifiedAt;
};
}
The following code snippets shows an example of the test code you could run; the code uses a Jasmine Spy
ensures the dependencies on the Date object are replaced and tested as expected.
var Controller = $.import("sap.hana.testtools.demo.objects.xs_javascript",
"javascriptOO").Controller;
var DataModel= $.import("sap.hana.testtools.demo.objects.xs_javascript",
"javascriptOO").DataModel;
describe('Controller', function() {
var controller = null;
var model = null;
var anyDate = new Date(2013, 8, 27, 11, 0, 0, 0);
beforeEach(function() {
model = new DataModel();
120
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
controller = new Controller(model);
});
it('should set current date when data is modified (replace Date.now() using
jasmine spies)', function() {
spyOn(Date, 'now').and.returnValue(anyDate.getTime());
oController.updateModel({data : [1,2,3]});
expect(model.getModificationDate()).toEqual(anyDate);
});
});
Dependency on Database Table
It is important to try to avoid mixing business logic that is implemented in JavaScript with the data base
interaction. We recommend moving the database persistency logic into a dedicated persistency class, so that
just the business logic remains for testing. The goal of the test is to be able to test both normal and special
cases without interacting with the data base at all.
To unit test the persistency class, you can parameterize the schema and use a schema for testing, for example,
the user schema where you have all authorizations required to create, modify, and drop objects, and cannot
mess things up with the test. Last of all, you can oer a small set of integration tests, that just ensure that the
productive classes, the AnyService class, and the Persistency class, integrate well.
Note
For sake of conciseness, resource closing and error handling is missing from the following code example.
function Persistency(dbConnection, schema) {
var dbSchema = schema !== undefined ? schema : 'SAP_HANA_TEST_DEMO';
this.existsEntry = function(key) {
var pstmt = dbConnection.prepareStatement('SELECT key FROM "' +
dbSchema + '"."Table" WHERE KEY=?');
pstmt.setString(1, key);
if (pstmt.executeQuery().next()) {
return true;
);
return false;
};
this.insertEntry = function(newEntry) {
var pstmt = dbConnection.prepareStatement('INSERT INTO "' + dbSchema +
'"."Table" VALUES(?,?)');
pstmt.setString(1, newEntry.Id);
pstmt.setString(2, newEntry.Value);
pstmt.execute();
};
}
function AnyService(persistency) {
this.execute = function(input) {
//validate input
if (!persistency.existsEntry(input.Id)) {
//calculate newEntry
persistency.insertEntry(newEntry);
}
};
}
The following code snippets shows an example of the test code you could run to test the dependencies.
var Persistency = $.import("package.of.persistency", "persistency").Persistency;
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
P U B L I C 121
describe('Persistency test', function() {
var SqlExecutor = $.import('sap.hana.testtools.unit.util',
'sqlExecutor').SqlExecutor;
var TableUtils = $.import('sap.hana.testtools.unit.util',
'tableUtils').TableUtils;
var originTable = 'TableName';
var testTable = null;
var originSchema = 'SAP_HANA_TEST_DEMO';
var userSchema = $.session.getUsername().toUpperCase();
beforeOnce(function(){
var tableUtils = new TableUtils(jasmine.dbConnection);
testTable = tableUtils.copyIntoUserSchema(originSchema, originTable);
});
it('should insert one entry into table', function() {
var persistency = new Persistency(jasmine.dbConnection, userSchema);
persistency.insertEntry({ Id : '0815', Value : 1});
expect(persistency.existsEntry('0815');
expect(selectAllFromTable().getRowCount()).toBe(1);
});
function selectAllFromTable() {
var sqlExecutor = new SqlExecutor(jasmine.dbConnection);
return sqlExecutor.execQuery('select * from ' + testTable);
}
});
Testing a Self-Contained JavaScript Function
The following code snippet show how to use XSUnit to test a self-contained JavaScript function (mathlib); a
self-contained function has no dependencies to other JavaScript functions, database tables or session
parameters.
var mathlib = $.import("package.of.your.library", "math");
describe('The math XS JavaScript library', function() {
it('should calculate "7" as maximum value of "3, 7"', function() {
var maxValue = mathlib.max(3, 7);
expect(maxValue).toBe(7);
});
it('should calculate "-10" as maximum value of "-10, -20"', function() {
var maxValue = mathlib.max(-10, -20);
expect(maxValue).toBe(-10);
});
});
122
P U B L I C
SAP HANA XS JavaScript Reference
Writing Server-Side JavaScript Code
Important Disclaimer for Features in SAP
HANA
For information about the capabilities available for your license and installation scenario, refer to the Feature
Scope Description for SAP HANA.
SAP HANA XS JavaScript Reference
Important Disclaimer for Features in SAP HANA
P U B L I C 123
Important Disclaimers and Legal Information
Hyperlinks
Some links are classied by an icon and/or a mouseover text. These links provide additional information.
About the icons:
Links with the icon : You are entering a Web site that is not hosted by SAP. By using such links, you agree (unless expressly stated otherwise in your
agreements with SAP) to this:
The content of the linked-to site is not SAP documentation. You may not infer any product claims against SAP based on this information.
SAP does not agree or disagree with the content on the linked-to site, nor does SAP warrant the availability and correctness. SAP shall not be liable for any
damages caused by the use of such content unless damages have been caused by SAP's gross negligence or willful misconduct.
Links with the icon : You are leaving the documentation for that particular SAP product or service and are entering a SAP-hosted Web site. By using such
links, you agree that (unless expressly stated otherwise in your agreements with SAP) you may not infer any product claims against SAP based on this
information.
Beta and Other Experimental Features
Experimental features are not part of the ocially delivered scope that SAP guarantees for future releases. This means that experimental features may be changed by
SAP at any time for any reason without notice. Experimental features are not for productive use. You may not demonstrate, test, examine, evaluate or otherwise use
the experimental features in a live operating environment or with data that has not been suciently backed up.
The purpose of experimental features is to get feedback early on, allowing customers and partners to inuence the future product accordingly. By providing your
feedback (e.g. in the SAP Community), you accept that intellectual property rights of the contributions or derivative works shall remain the exclusive property of SAP.
Example Code
Any software coding and/or code snippets are examples. They are not for productive use. The example code is only intended to better explain and visualize the syntax
and phrasing rules. SAP does not warrant the correctness and completeness of the example code. SAP shall not be liable for errors or damages caused by the use of
example code unless damages have been caused by SAP's gross negligence or willful misconduct.
Gender-Related Language
We try not to use gender-specic word forms and formulations. As appropriate for context and readability, SAP may use masculine word forms to refer to all genders.
124
P U B L I C
SAP HANA XS JavaScript Reference
Important Disclaimers and Legal Information
SAP HANA XS JavaScript Reference
Important Disclaimers and Legal Information
P U B L I C 125
www.sap.com/contactsap
© 2019 SAP SE or an SAP aliate company. All rights reserved.
No part of this publication may be reproduced or transmitted in any form
or for any purpose without the express permission of SAP SE or an SAP
aliate company. The information contained herein may be changed
without prior notice.
Some software products marketed by SAP SE and its distributors
contain proprietary software components of other software vendors.
National product specications may vary.
These materials are provided by SAP SE or an SAP aliate company for
informational purposes only, without representation or warranty of any
kind, and SAP or its aliated companies shall not be liable for errors or
omissions with respect to the materials. The only warranties for SAP or
SAP aliate company products and services are those that are set forth
in the express warranty statements accompanying such products and
services, if any. Nothing herein should be construed as constituting an
additional warranty.
SAP and other SAP products and services mentioned herein as well as
their respective logos are trademarks or registered trademarks of SAP
SE (or an SAP aliate company) in Germany and other countries. All
other product and service names mentioned are the trademarks of their
respective companies.
Please see https://www.sap.com/about/legal/trademark.html for
additional trademark information and notices.
THE BEST RUN