241
BUILDING APPLICATIONS WHICH LEVERAGE SAP HANA Version: September 2013 Exercises / Solutions Rich Heilman / SAP Labs, LLC. Thomas Jung /SAP Labs, LLC.

Building Applications Which Leverage SAP HANA - September 2013 XS Only

  • Upload
    ysrphy

  • View
    74

  • Download
    0

Embed Size (px)

DESCRIPTION

hana

Citation preview

  • BUILDING APPLICATIONS WHICH LEVERAGE

    SAP HANA

    Version: September 2013

    Exercises / Solutions Rich Heilman / SAP Labs, LLC. Thomas Jung /SAP Labs, LLC.

  • 2

    Contents

    Getting Help .................................................................................................................................................... 6

    Source code solutions ..................................................................................................................................... 6

    HANA Studio Configuration ..........................................................................................................................................6

    Adding the HANA Studio Perspectives............................................................................................................. 6

    Create a connection to the HANA server ......................................................................................................... 7

    Configure Regi for SAP HANA Studio ............................................................................................................ 10

    Installing SAPUI5 Tools into SAP HANA Studio ............................................................................................. 11

    Exercise 1 Setup of a Project .................................................................................................................................. 15

    Exercise 1 Solution ................................................................................................................................................. 16

    Create a group package ................................................................................................................................ 16

    Create a Repository Workspace .................................................................................................................... 17

    Create a XS Project ....................................................................................................................................... 19

    Creating Sub-Packages ................................................................................................................................. 23

    Creating Access Control ................................................................................................................................ 24

    Creating and running a Hello World HTML page from our Project .................................................................. 27

    Creating a Hello World HTML test manually ................................................................................................... 32

    Creating a database Schema ........................................................................................................................ 34

    Creating a repository role .............................................................................................................................. 36

    Grant the Role ............................................................................................................................................... 39

    Exercise 2 Creating Database Objects via the Repository ....................................................................................... 41

    Exercise 2 Solution ................................................................................................................................................. 42

    Creating the hdbdd development artifact ........................................................................................................ 42

    Defining reusable types and structures .......................................................................................................... 44

    Defining database tables ............................................................................................................................... 45

    (Optional) Creating tables via hdbtable .......................................................................................................... 50

    Creating Sequences ...................................................................................................................................... 52

    SQL Views .................................................................................................................................................... 54

    Automatic Table Data Loads.......................................................................................................................... 55

    Exercise 3 Modeling Views ..................................................................................................................................... 59

    Exercise 3 Solution ................................................................................................................................................. 60

    Creating an Attribute View ............................................................................................................................. 60

    Creating an Analytic View .............................................................................................................................. 67

    Exercise 4 Using SQLScript .................................................................................................................................... 74

  • 3

    Exercise 4 Solution ................................................................................................................................................. 76

    Creating a procedure leveraging CE functions ............................................................................................... 76

    Creating a procedure leveraging imperative logic ........................................................................................... 80

    Debugging SQLScript Procedures ................................................................................................................. 81

    Creating Table User Defined Functions(UDFs) .............................................................................................. 87

    Creating Scalar User Defined Functions(UDFs) ............................................................................................. 90

    Creating Triggers........................................................................................................................................... 92

    Exercise 5 OData Services ..................................................................................................................................... 99

    Exercise 5 Solution ............................................................................................................................................... 100

    Creating a Simple OData Service ................................................................................................................ 100

    Creating an OData Service with an Entity Relationship ................................................................................ 105

    Creating an OData Service with Create Operation and SQLScript Exit ......................................................... 107

    Exercise 6 Server Side JavaScript ........................................................................................................................ 110

    Exercise 6 Solution ............................................................................................................................................... 111

    Creating a Hello World XSJS Service .......................................................................................................... 111

    Creating an XSJS Service with custom output format................................................................................... 113

    Creating an XSJS Service with outbound HTTP Connectivity ....................................................................... 116

    Debug a XSJS Service from HANA Studio ................................................................................................... 121

    Alternative: Debug a XSJS Service from the SAP HANA Web-based Development Workbench ................... 129

    Exercise 7 UI5 Basics ........................................................................................................................................... 132

    Exercise 7 Solution ............................................................................................................................................... 133

    Create a SAPUI5 Project ............................................................................................................................. 133

    Share the SAPUI5 Project with the HANA Repository .................................................................................. 136

    Testing your Hello World Application ........................................................................................................... 141

    Creating a Text Bundle (Optional) ................................................................................................................ 142

    Exercise 8 Consuming OData from UI5 ................................................................................................................. 146

    Exercise 8 Solution ............................................................................................................................................... 147

    Consume a Basic OData Service within UI5 binding the service to a Table .................................................. 147

    Use oData Metadata to dynamically create the columns. ............................................................................. 151

    Consume an OData Service with Create Option .......................................................................................... 153

    Exercise 9 Consuming XSJS from UI5 .................................................................................................................. 159

    Exercise 9 Solution ............................................................................................................................................... 160

    Consume XSJS Services via JQuery AJAX calls ......................................................................................... 160

  • 4

    Use the liveUpdate and linked fields for interactive search ........................................................................... 164

    Exercise 10 UI Integration Services ....................................................................................................................... 169

    Exercise 10 - Solution .............................................................................................................................................. 170

    Create a Widget .......................................................................................................................................... 170

    Create an Application Site ........................................................................................................................... 174

    Exercise 11 Delivery Units and Transport of Content ............................................................................................. 179

    Exercise 11 Solution ............................................................................................................................................. 180

    Create a Deliver Unit using the HALM tool ................................................................................................... 180

    Export a Delivery Unit using the HALM tool.................................................................................................. 184

    Alternative: Create and export a Delivery Unit using the SAP HANA Web-based Development Workbench . 187

    Exercise 12 putting it all together purchase order worklist ................................................................................... 191

    Exercise 12 - solution............................................................................................................................................... 194

    Exercise Preparations ................................................................................................................................. 194

    The Data Model ........................................................................................................................................... 199

    XSODATA Services..................................................................................................................................... 207

    XSJS Services ............................................................................................................................................ 209

    User Interface.............................................................................................................................................. 212

    Exercise 13 putting it all together Adapt to use UIS ............................................................................................ 216

    Exercise 13 Solution ............................................................................................................................................. 217

    Project Structure.......................................................................................................................................... 217

    Create Components .................................................................................................................................... 218

    Create Widget XML Specifications ............................................................................................................... 219

    Create Widgets ........................................................................................................................................... 220

    Create an Application Site ........................................................................................................................... 223

    Design an Application Site ........................................................................................................................... 224

    Implementing Communication Between Widgets ......................................................................................... 225

    Personalize Preferences.............................................................................................................................. 229

    Appendix A: Installing THE WORKSHOP and DEMO Delivery Units ........................................................................ 230

    Prerequisite Checks .................................................................................................................................... 230

    Importing Delivery Units............................................................................................................................... 231

    Post-Installation Setup Steps ....................................................................................................................... 232

    Appendix B: Installing The WEB IDE ........................................................................................................................ 234

    Installation ................................................................................................................................................... 234

  • 5

    Appendix C: Installing SAP HANA UI Integration Services........................................................................................ 238

    Installation ................................................................................................................................................... 238

  • 6

    BEFORE YOU START

    Getting Help

    If you need addition help resources beyond this document, we would suggest the following content:

    The Online Help at http://help.sap.com/hana/SAP_HANA_Developer_Guide_en.pdf

    The integrated help within SAP HANA Studio (content identical to the above mentioned online help)

    Source code solutions

    All source code solutions and templates for all exercises in this document can be found in the following webpage. http://:/workshop/admin/ui/exerciseMaster/?workshop=xs In some cases it might be a little easier to copy and paste the coding instead of typing it all manually. If copying/pasting, I would suggest that you make sure to understand what is being copied/pasted before moving on.

    1. Open the browser and enter the following URL to access the solutions web page. You can access the source code for each exercise by clicking on the appropriate exercise in the navigation bar. http://:/workshop/admin/ui/exerciseMaster/?workshop=xs

    HANA STUDIO CONFIGURATION

    Explanation Screenshot

    Adding the HANA Studio Perspectives

    1) To support the new developer centric workflow, there are two need Eclipse Perspectives which have been added to SAP HANA Studio. These are not displayed by default. In the upper right corner of your SAP HANA Studio, there is an add Perspectives button. Press this.

  • 7

    2) Add the SAP HANA Development perspective. This is the perspective you should be using for almost this entire workshop.

    3) Repeat the step and add the Debug perspective.

    Create a connection to the HANA server

    1) Make sure you are in the SAP HANA Development perspective by clicking on the button. .

    2) Click on the SAP HANA Systems view. Right click and choose Add System.

  • 8

    3) Input the server hostname and the instance number which were provided by your workshop instructor. Enter a meaningful description of your choice. Press the Next button.

    4) Enter the user id and password which the instructor has provided to you. The user id should be WORKSHOP_. Your group number will be given to you by the session instructor. For example if the group number is 01, then your user id would be WORKSHOP_01. Enter the password which was supplied by your instructor. Click Finish.

  • 9

    5) You should now have a new connection with your specific user id for the M41 system. Please make sure to use this connection for the rest of the exercise. Please DO NOT use the Demo or any other connections.

    4) If you do not see the Content folder in the SAP HANA Systems View, you can add it to your view. Click the View Menu button on the Navigator toolbar.

    5) Click Customize View.

    6) In the following dialog, click the Content tab, then click the checkbox for Content. Click OK.

  • 10

    Configure Regi for SAP HANA Studio

    1) From the Window menu, choose Preferences.

    2) From the left side of the screen, expand SAP HANA Development, then click Repository Access. In the right side of the screen, click Change. Browse to the client installation directory (default: C:\Program Files\SAP\hdbclient\) and choose regi.exe. Next, click Apply, then OK.

  • 11

    Installing SAPUI5 Tools into SAP HANA Studio

    1) Begin the installation by adding the SAPUI5 tools update site to your SAP HANA Studio. Use Window->Preferences.

    2) From the preferences, choose Install/Update -> Available Software Sites. The press Add to create a new entry.

    3) You can also consider using the public update site: https://tools.hana.ondemand.com/juno

  • 12

    4) To perform the installation from this new update site, use Help -> Install New Software.

    5) In the Available Software dialog, choose the SAPUI5 update site you just created. Select the parameters: Show only software applicable to the target environment, Contact all update sites during install to find required software, and Hide items that are already installed. If you scroll down in the list of available software, you should find the UI development toolkit for HTML5.

  • 13

    6) Confirm the items to install

    7) Accept the license agreement:

    8) Depending upon your network connection speed, it can take several minutes to complete the installation.

  • 14

    9) Near the end of the installation, the process might stop and make you confirm that you want to install the unsigned content

    10) Upon completion of the installation you must restart SAP HANA Studio

    You have completed the initial setup!

    You are now able to:

    Configure the HANA Client Connection

    Setup the Development Perspective

    Install SAPUI5

  • 15

    EXERCISE 1 SETUP OF A PROJECT

    Objective In this exercise, you will learn the basics of creating a workspace and creating an XS project which you will use for the remainder of this workshop. Exercise Description

    Create a workspace which is linked to the HANA Server

    Create a project which is linked to the workspace

    Create a schema

    Create access control files

    Create a role

    Create a HelloWorld.html file to test your setup

  • 16

    EXERCISE 1 SOLUTION

    Explanation Screenshot

    Create a group package

    1) Expand the workshop package under the Content folder. There should be session specific packages already created for you. Because this hands-on session will be given multiple times, we will use different session letters to separate each classs work. The session instructor will tell you what session package to use for your session. For this example document we will use session x. Right-click on the session package and choose New, then Package.

    2) In the package dialog, you will create a package for your group. The group numbers will be provided by the instructor. This ensures that every attendee has a unique namespace for their work. All the content you create today will then be placed within this unique session/group package hierarchy. Enter the name of the package as your group number. For example, if the assigned group number is 00 and your session package is sessionx, then the complete package name would be workshop.sessionx.g00. That is workshopsessionx

  • 17

    ot>g00. You will use this same naming convention throughout the rest of the exercise document. Click OK.

    Create a Repository Workspace

    1) Switch to the SAP HANA Repositories view. Click the icon for Create Repository Workspace.

    2) Select the system entry you created previously. Enter the name of the workspace as Workshop.

  • 18

    3) Choose any directory on your local drive, for example, you could use the hdbstudio folder under your documents folder. Click Ok.

    4) Click Finish.

  • 19

    5) You should now see the new workspace in the SAP HANA Repositories view.

    Create a XS Project

    1) Move to the Project Explorer view, and right-click in the white space. Choose New, then Other.

    2) Browse to SAP HANA Development and choose XS Project. Then click Next.

  • 20

    3) Enter the name of the project as Exercises and choose Finish

    4) Your project should now be visible in the Project Explorer but still needs to be connected to your HANA Server. Right click on the project and choose Team, then Share Project.

  • 21

    5) Based on your installed plug-ins, you may not get the following dialog. If you do receive the following dialog, choose SAP HANA Repository and click Next.

    6) In the Share Project dialog, choose the Repository Workspace you created in the previous steps. Uncheck Add project folder as sub-package. Then click Browse so that you can select the package to place your project in.

  • 22

    7) Navigate through the Repository hierarchy to workshop -> your session folder -> your group folder. Select your group folder/package and then press OK.

    8) Confirm your project sharing settings and then press Finish to share the project.

  • 23

    9) Your project is now shared with the repository.

    Creating Sub-Packages

    1) In order to prepare for the development we will be doing, we should create sub-packages under your project package. You can create packages from the project explorer simply by creating folders. Right mouse click on the project name and choose New->Folder

    2) Create a folder named data

  • 24

    3) Repeat this process for folders named: models, procedures, services, and ui.

    Creating Access Control

    1) In this step we will learn the basics of XSEngine access control. The first artifact we must create is the .xsapp. The XSAPP file is necessary for exposing any content via the XSEngine web server. Begin by right mouse clicking on the root of your project and choosing New->File

  • 25

    2) Create a file named .xsapp. This is file with only the extension. This way you can only have one file per folder. This same naming concept is repeated with other artifacts which must only exist once per folder. The names of the individual development artifacts dont need to be unique because the package hierarchy also functions as the namespace and web server path

    3) The default configuration of HANA Studio might have the .xsapp file open in Notepad rather than the in-place editor. If so, simply close Notepad.

    4) The newly created file is visible in your Project Explorer. The icon (grey diamond) for the file signifies that this object exists on the client side and has been committed to the HANA Repository but is not yet active. The file is automatically opened in an editor. This particular development artifact doesnt actually need any content in it. You can close the editor.

  • 26

    5) All objects are stored in an inactive state when first committed. Therefore before this artifact can be used on the server it must be activated. Choose Team->Activate from the parent folder ( press the activate button on the toolbar or use the keyboard shortcut Ctrl + F3). This will activate all inactive objects. Individual object activation is also possible. Once successfully activated, the icon next to the object will change to an orange cylinder.

    6) Next you need to create an access control file. With this object you can set the required privilege, if the package is exposed via HTTP, the allowed authentication mechanisms, and default file for a package. Unlike the .xsapp and .xsprivileges files which are generally setup once at the root of a project folder; the .xsaccess files can be placed at many levels of the package hierarchy and override the higher levels. Create a new file in the root of your project named .xsaccess.

    7) If this file opens in Notepad, close Notepad. To open in the in-place editor, right mouse click on the object and choose Open With ->Text Editor

  • 27

    8) For this root .xsaccess file, set exposed to true and define the authentication mechanisms Basic. You can access the solution code here if you have difficulties: http://:

  • 28

    3) Input the same user name and password you used to logon to the HANA System via the Studio

    4) The Web Workbench has the same repository tree as we have access to in the HANA Studio. The difference here is that we dont check out projects, but instead directly edit and save objects. Commit and Activate are both performed upon save.

  • 29

    5) The Web Workbench also has some project wizards. Expand the content tree for workshop, your session folder, and then select your group folder. Then choose Project -> Project Templates ->Create Hello World Project.

    6) In the Create new Folder dialog, input the full repository path to your group folder plus a new folder named HelloWorld. Path should be /workshop/session/g/HelloWorld. Then press OK.

  • 30

    7) Your group folder now contains a sub-folder named HelloWorld with basic html and xsjs (Server Side JavaScript) examples.

    8) Right mouse click on the index.html file in the repository tree and choose Execute File in Browser Window in order to test it.

  • 31

    9) The index.html file should open in a new browser window. When you press the Call Backend button it will make an AJAX call to the HANA Server and read your User ID. This simple test tells us that your project, role and access control files are all setup properly.

    10) If you return to the HANA Studio and your Project in the Project Explorer; you can right mouse click and choose Team ->Check Out

  • 32

    11) All the content created in the Web Workbench is now copied into our local project. This allows you to move between either development environments as you work.

    Creating a Hello World HTML test manually

    1) The alternative to the wizard would be to create a simple HTML file so that we have something which we can execute from the web browser in order to test our access control. Begin by creating a new file called HelloWorld.html in the root of you project.

  • 33

    2) Place the following HTML code into the new file. This should create a simple HTML5 page based upon the SAPUI5 framework with a single Button (we will learn much more about SAPUI5 in later exercises). When the button is pressed it should disappear. Note: if you dont want to type this code, we recommend that you cut and paste it from this web address: http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX1_2

    3) Save and then activate your new content.

    4) Launch your web browser. The URL path matches your folder/package structure. It would be http://:/workshop/session#/g99/HelloWorld.html where # is your session id and 99 is your group number. For example if your session letter was x and your group number was 00 then the URL would be:

    http://:/workshop/sessionx/g00/HelloWorld.html You will be prompted for authentication. Use your current HANA System Username and Password.

  • 34

    5) The URL path and resource names for the XSEngine are case sensitive. Therefore a common mistake of removing the case when typing the URL would result in the following error message

    Creating a database Schema

    1) In the past, database objects could only be created via SQL directly in the database catalog. However this meant they couldnt be transported via delivery units like all other repository objects. As part of HANA Native Development, we now have tools to create database objects via a repository representation which generates the catalog objects upon activation. We will create all of our database objects within the data folder of our project. This simply helps keep the various parts of our application separated for easier use and maintenance.

  • 35

    2) First we will need a database schema to hold all of our database tables and various other catalog objects. Begin by creating a file named HANA_WORKSHOP_.hdbschema. For this example this would be HANA_WORKSHOPX_00.hdbschema.

    3) The syntax of the schema document is really quite simple. Its: schema_name=;. Follow the same pattern as the filename for the creation of your schema. HANA_WORKSHOP_ For this example this would be HANA_WORKSHOPX_00 Save and Activate this file.

  • 36

    4) Expand the SAP HANA System Library node in your project and refresh the Catalog folder. You will see the new schema; however you dont actually have access to this Schema yet. The activation of the Schema was done by the repository and consequently the user SYS_REPO owns the Schema. This is true of all database objects created in this new repository approach. Next we will create a repository role and grant it to our user. Only then will we have authorization to see the objects which we are creating in this exercise.

    Creating a repository role

    1) Similar to the way that catalog objects now have a repository representation, roles have a similar artifact. In this step we will create roles using this new approach and grant this role to our users. The role object has an Eclipse Wizard to help with the creation of new roles. Begin the process by choosing New->Other

  • 37

    2) In the Wizard, under SAP HANA Development, choose Role.

    3) Place the new role in the data folder of your project. Name the role user.

    4) This creates a user.hdbrole file and inserts the skeleton of the role definition into the edit.

  • 38

    5) Replace the package name placeholder with your exercise package name: workshop.session.g.data. For example if this were session X and you were group number 00, the package value would be: workshop.sessionx.g00.data.

    6) In your role definition, grant select access to your Schema: HANA_WORKSHOP_. For example if you were in Session X and Group Number 00, your schema would be named HANA_WORKSHOPX_00.

    7) Create a second role using the same steps. Name this second role admin.

    8) Using the extends role syntax, make your admin role inherit from the user role

    9) Expand the Schema access to include SELECT, INSERT, UPDATE, DELETE, and DROP

    10) Save and activate both new roles.

  • 39

    Grant the Role

    1) We need only grant this role to our user. Open the SQL Console by right mouse clicking on the SAP HANA System Library node in your project and choosing SQL Console

    2) You will need to call a SQLScript Procedure to perform the grant. This procedure will run as SYS_REPO and therefore can grant the role to your user (note: Access to execute this procedure should be extremely limited since it gives anyone who has it great power). The Procedure you need to call is GRANT_ACTIVATED_ROLE which has two input parameters ROLENAME and USERNAME. Note: if you dont want to type this code, we recommend that you cut and paste it from this web address http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX1_3

  • 40

    3) Your user now has the assigned role

    You have completed the exercise!

    You are now able to:

    Create a connection to the HANA server in HANA Studio Create a workspace which is linked to the HANA Server Create a project which is linked to the workspace Create a schema Create access control files Create a role Create a HelloWorld.html file to test your setup

  • 41

    EXERCISE 2 CREATING DATABASE OBJECTS VIA THE REPOSITORY

    Objective In the past, database objects could only be created via SQL directly in the database catalog. However this meant they couldnt be transported via delivery units like all other repository objects. As part of HANA Native Development, we now have tools to create database objects via a repository representation which generates the catalog objects upon activation. Exercise Description We create a schema to hold all of our database objects. Next we will use the new development objects (new as of SPS6) hdbdd which utilizes the CDS syntax to define reusable types, structures and tables. We will also look at the legacy way of creating tables with hdbtable. We will create database views via hdbview. For example:

    Create a HDBDD object

    Use CDS Syntax to define types, structures and tables

    Create a HDBTABLE object

    Create a HDBVIEW object

    Setup Automatic Table Data Loads

  • 42

    EXERCISE 2 SOLUTION

    Explanation Screenshot

    Creating the hdbdd development artifact

    1) We now want to create two database tables one for purchase order headers and one for items. Both of these objects will be created via a single development object called PurchaseOrder.hdbdd. Begin this process by right mouse clicking on the data folder in your project and choosing New -> Other.

    2) In the New wizard, expand the SAP HANA Development folder and choose DDL Source File. Then press Next.

  • 43

    3) Verify that the data folder is selected. Type the filename PurchaseOrder. The file extension hdbdd will be added automatically for you. Finally, press Finish.

    4) The hdbdd file is opened in the editor with the correct namespace and context already entered for you.

    5) Next we need to tell the HDBDD file which schema all objects should be created within. Add a @Schema note after the namespace but before the context and supply the name of the Schema you created in the previous exercise: HANA_WORKSHOP_. For this example this would be HANA_WORKSHOPX_00.

  • 44

    Defining reusable types and structures

    1) First we need to define some reusable elemental types. These will later be used to define the data type of individual columns in our tables. Create element types for BusinessKey, SDate, CurrencyT, AmountT, QuantityT, UnitT, and StatusT. Note: if you dont want to type this code, we recommend that you cut and paste it from this web address http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX2_1

    2) We can also create reusable structures with multiple fields. This is useful when the same sets of fields are repeated in multiple tables. Create a reusable structure for History with CREATEDBY, CREATEDAT, CHANGEDBY, and CHANGEDAT fields. Note: if you dont want to type this code, we recommend that you cut and paste it from this web address http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX2_2

  • 45

    Defining database tables

    1) The syntax for creating Entities is similar to types. Entities will become database tables when activating the hdbdd file. Create a purchase order entity with these fields and types: Note: if you dont want to type this code, we recommend that you cut and paste it from this web address http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX2_3

    2) Repeat this process for the Item Entity. Note: if you dont want to type this code, we recommend that you cut and paste it from this web address http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX2_4

    3) Here is the complete source code for your hdbdd file.

    namespace workshop.sessionx.g00.data; @Schema: 'HANA_WORKSHOPX_00' context PurchaseOrder { type BusinessKey : String(10); type SDate : LocalDate; type CurrencyT : String(5); type AmountT : Decimal(15,2); type QuantityT : Decimal(13,3); type UnitT: String(3); type StatusT: String(1); Type HistoryT { CREATEDBY : BusinessKey; CREATEDAT : SDate; CHANGEDBY : BusinessKey; CHANGEDAT : SDate; }; @Catalog.tableType : #COLUMN

  • 46

    Entity Header { key PurchaseOrderId: BusinessKey; History: HistoryT; nullable NoteId: BusinessKey; PartnerId: BusinessKey; Currency: CurrencyT; GrossAmount: AmountT; NetAmount: AmountT; TaxAmount: AmountT; LifecycleStatus: StatusT; ApprovalStatus: StatusT; ConfirmStatus: StatusT; OrderingStatus: StatusT; InvoicingStatus: StatusT; }; @Catalog.tableType : #COLUMN Entity Item { key PurchaseOrderId: BusinessKey; key PurchaseOrderItem: BusinessKey; ProductId: BusinessKey; nullable NoteId: BusinessKey; Currency: CurrencyT; GrossAmount: AmountT; NetAmount: AmountT; TaxAmount: AmountT; Quantity: QuantityT; QuantityUnit: UnitT; DeliveryDate: SDate; }; };

    4) Save and activate your hdbdd file.

  • 47

    5) Open the SAP HANA System Library in your project and expand the node for your Schema. Within Procedures->Table Types you should find the structure for your HistoryT type. Within Tables you should both your PurchaseOrder.Header and PurchaseOrder.Item tables.

    6) You can double click on any of these objects to open their definition.

  • 48

    7) For this workshop, we have created an application which will verify the tables in your schema and input some random test data for you. Run this application from http://:/workshop/solution/ui/cdsTest.html

    8) Input your Schema name and press Create Data. HANA_WORKSHOP_. For this example this would be HANA_WORKSHOPX_00.

  • 49

    9) The tables in this page will then display the newly inserted data in your header and item tables.

    10) You can return to the HANA Studio and browse the data from there as well by choosing Open Data Preview

  • 50

    11) The same data from the web application is now displayed in the data preview tool of HANA Studio.

    (Optional) Creating tables via hdbtable

    1) HDBDD was first introduced in SP6. There is an alternative development object called hdbtable which can also be used from SP5 and forward to create database tables. We now want to create two database tables using this alternative approach. Begin by creating a new file named header.hdbtable

  • 51

    2) Here you need to supply the schema name from the previous step, the table type (COLUMNSTORE), all the table columns, and the primary key. Use the following fields:

    i. OrderId type NVARCHAR length 10 ii. CreatedBy type NVARCHAR length 10 iii. CreatedAt type DATE iv. Currency type NVARCHAR length 5 v. GrossAmount type Decimal length 15,2

    3) Here is the complete table definition Note: if you dont want to type this code, we recommend that you cut and paste it from this web address http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX2_5

    4) Repeat the process now creating an item table (item.hdbtable) Note: if you dont want to type this code, we recommend that you cut and paste it from this web address http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX2_6

    i. OrderId type NVARCHAR length 10 ii. OrderItem type NVARCHAR length 10 iii. ProductId type NVARCHAR length 10, iv. Quantity type DECIMAL length 13,3 v. QuantityUnit type NVARCHAR length 3 vi. DeliveryDate type DATE

    5) Save / Activate both of your hdbtable files.

  • 52

    6) We were all able to use very common table names, because the package hierarchy is used as a namespace on the front of the generated table. You may need to refresh the Tables folder in order to see the new tables.

    Creating Sequences

    1) With the tables we created, we use a unique order id number as the primary key. Therefore we need a sequence to have an auto incrementing unique id generated for us as we insert new data Create a new file named orderId.hdbsequence

  • 53

    2) Create a non-cycling sequence within your schema starting from 200000000 and ending with 299999999. Make it dependent upon your header table with the full package id on the front of the header table name. Note: if you dont want to type this code, we recommend that you cut and paste it from this web address http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX2_7

    3) Save / Activate your sequence file.

  • 54

    SQL Views

    1) Although most of the views you create in HANA should be modeled views (Attribute, Analytic, or Calculation views); it is also possible to create simple SQL views. We follow a similar process as to the previous steps to create SQL views as a repository file. Create a new file named ordersExt.hdbview

    2) The syntax of this view file is largely comprised of the SQL Statement used to create the join for the view. Use the following syntax to create a view between the header and item tables of the sample model. Also because this SQL Statement is embedded within a JSON notation syntax, the quotes inside the SQL statement must be escaped with a backslash \. Note: Due to the complexity of this code snippet, we highly recommend that you cut and paste it from this web address http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX2_8

  • 55

    3) You can test the output of your view from the Catalog just as we learned to do earlier with tables.

    Automatic Table Data Loads

    1) You may want to deliver an initial set of data within a table particular a configuration table. In this exercises we will learn how to create automatic data load configuration and the accompanying CSV files for just such a situation. The data load for table requires two files 1. A csv (comma separated) file which holds the data you want to load. 2. A hdbti file which specifies the target table for a source csv file.

  • 56

    2) For the header table we created earlier in this exercise, want to begin by creating a csv file named header.csv in the data folder of your project.

    3) By default, HANA Studio might try to open CSV files in Microsoft Excel. However Excel creates CSV files which arent technically compatible with this data load mechanism. Therefore we will close Excel and instead open the header.csv file in a plain text edit via Open With -> Text Editor

    4) Fill in two records into the CSV file for header records. Note: You cut and paste it from this web address http://:/workshop/admin/ui/exercis

  • 57

    eMaster/?workshop=xs&sub=EX2_9

    5) Repeat this process for a item.csv file. Note: You cut and paste it from this web address http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX2_10

    6) Now create a single control file named Purchase.hdbti. Here we maintain the link between the two previously created csv files and the target tables. Note: if you dont want to type this code, we recommend that you cut and paste it from this web address http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX2_11

    7) Save / Activate all 3 files youve created so far.

  • 58

    8) You can return to the Navigator view and browse the data. From the tables or views within the Catalog folder, you can use either the Open Content or Open Data Preview to view the data.

    You have completed the exercise!

    You are now able to:

    Create a HDBDD object

    Use CDS Syntax to define types, structures and tables

    View your generated catalog tables

    Create Sequences

    Create SQL Views

    Configured Automatic Table Data Loads

  • 59

    EXERCISE 3 MODELING VIEWS

    Objective Although earlier we created a database SQL view, most views should be created as HANA specific view types Attribute Views, Analytic Views, and Calculation Views. In this exercise, we will utilize these modeling tools to create some more advanced views. You created a basic header and item table earlier as well. Rather than spending time creating a larger series of tables and sample data, the workshop will leverage the standard EPM (Enterprise Procurement Model) demo model which is delivered as part of SHINE (SAP HANA Interactive Education). This model already exists in the workshop system under the schema SAP_HANA_EPM_SP6 and contains Sales Orders, Purchase Orders, supporting master data, and currency conversion and unit of measure base tables.

    Exercise Description

    Create an Attribute View

    Create an Analytic View

  • 60

    EXERCISE 3 SOLUTION

    Explanation Screenshot

    Creating an Attribute View

    1) In the models sub-package of your workshop package, create a new attribute view based upon the expanded information for the products. This will require joining the products, texts, businessPartner, and address tables. From the right mouse click on the models package, choose New -> Other

    2) In the New Wizard, expand the SAP HANA Modeler folder. Select Attribute View and press Next.

  • 61

    3) Create an Attribute View named AT_PRODUCTS.

    4) To add tables to the data foundation of your view, you can drag and drop them from the SAP_HANA_EPM_SP6 Schema.

  • 62

    5) Add MasterData.Products, MasterData.BusinessPartner, MasterData.Addresses and Util.Texts (twice) to your data foundation

    6) Using the Add to Output option from the context menu, add the PRODUCTID, TYPECODE, CATEGORY, CURRENCY, and PRICE fields from the products table to the output

  • 63

    7) Optionally, you can change the name of a column as it becomes part of the view. For example you might change CATEGORY to ProductCategory.

  • 64

    8) We need to define a key for the view. We can do this by selecting the PRODUCTID column in the Output and setting Key Attribute to True.

    9) Drag and drop the NAMEID column from the products table to the TEXTID column of the texts table. Change the Join Type to Text Join and select Language as the Language Column.

    10) Add the TEXT column to the output and change the column name to ProductName.

  • 65

    11) Create a similar join from the DESCID column of Products to the second instance of the texts table. Name the Text output column ProductDesc.

    12) Create a Referential join between SUPPLIERID of the product table and the PARTNERID column of the businessPartner table. Add PARTNERID and COMPANYNAME to the output.

    13) Add a Referential join between the ADDRESSID of the businessPartner table to the ADDRESSID of the addresses table. Add the CITY, POSTALCODE, STREET, BUILDING, and COUNTRY columns of addresses to the output.

  • 66

    14) Save your model

    15) Activate your model

    16) To test your Attribute View, choose Data Preview from the model toolbar.

    17) In the data preview, there are many tools for performing analysis on the view data. For an initial test choose Raw Data and make sure your outlook looks similar to the following:

    18) If you have problems creating your view, you can refer to a sample implementation in the package sap.hana.democontent.epmSP6.models

  • 67

    Creating an Analytic View

    1) Now we will create an Analytic View which combines purchase order table data with the product attribute view we created in the previous step. Because we have various currency based amounts in our source data, we will also create a calculated column which contains a currency conversion. Using the same steps as the previous part of the exercise; in your models package, create a new Analytic View

    2) Name your new view AN_PURCHASE_ORDERS

  • 68

    3) Drag and drop the AT_PRODUCTS attribute view from the previous part of the exercise into the Logical Join of your new view.

    4) Add the Purchase.Header and Purchase.Item tables from SAP_HANA_EPM_SP6 to the Data Foundation of your view

  • 69

    5) Create a 1:n referential join between Header and Item on the PURCHASEORDERID column

    6) Using Add to Output, add the column History.CREATEDAT from the Header table and the PURCHASEORDERID, PURCHASEORDERITEM, PRODUCTID, CURRENCY, and GROSSAMOUNT columns from the Item table

    7) Create an input parameter named IP_O_TARGET_CURRENCY.

  • 70

    8) Configure as shown with type NVARCHAR length 3 with a Semantic type of Currency. It should be mandatory and have a default value of USD.

    9) From the Semantics Scenario, Set the Default Schema to SAP_HANA_EPM_SP6:

    10) Select the Logical Join box in the Scenario. You can then drag and drop the PRODUCTID from the data foundation to the ProductId column of the AT_PRODUCTS view creating a 1:1 referential join.

  • 71

    11) In the output, create a new Calculated Column for the common currency gross amount.

    12) Create a Calculated Column named ConvGrossAmount which is a summarized measure for the base column Gross Amount. This involves writing an Expression that sets the base value of GROSSAMOUNT.

  • 72

    13) In the Advanced tab of the calculated column creation screen, configure the currency conversion. Use the CURRENCY column from the Header table as the source currency and the IP_O_TARGET_CURRENCY input parameter as the target. Set the Exchange Type to 1001 and for the Conversion Date use the History_CREATEAT column of the Header table. YOU MUST SELECT THESE VALUES FROM THE VALUE HELP AND NOT TYPE THEM IN.

    14) Return to the Semantics Scenario and choose the Auto Assign button to have the system generate proposals for your attributes and measures. If the Auto Assign fails, you can manually set the ConvGrossAmount and GrossAmount as measures and the other fields as attributes.

    15) The GROSSAMOUNT and ConvGrossAmount should both be Measures and all other columns should be attributes.

    16) Save and Activate your Analytic View.

  • 73

    17) Use the Data Preview to test your View. You should see an Input Parameter dialog. You can keep the default value of USD

    18) You should see output similar to this. In particular check the values of the GROSSAMOUNT and ConvGrossAmount Columns. In this workshop system exchange rates have only been maintained for USDEUR; therefore those would be the only records with different values in the ConvGrossAmount column.

  • 74

    EXERCISE 4 USING SQLSCRIPT Objective In this exercise, you will create a SQLScript procedure and leverage CE functions to read data from two tables and return the result set as output. You will then create a SQLScript procedure which uses imperative logic to read a product from a table and determine the sale price. Next, you will learn how to debug SQLScript procedures using the Debug perspective in SAP HANA Studio. Next, you will explore the concepts of User Defined Functions(UDFs). You will create a table UDF which simply retrieves some employee data from the database, and a scalar UDF which calculates the sale price of a product. Currently, you can only create UDFs via the SQL Console. Only the runtime object exists in the catalog. Support for storing UDFs in the repository is planned for a future support package. Next, you will be introduced to the concept of triggers. A trigger is a special kind of stored procedure that automatically executes when an event occurs on a certain table. First you will create two tables using CDS which you will use to explore the concept. You will then create a trigger for a table called products, which will insert a new record into the productsLog table. Currently, you can only create triggers via the SQL Console. Only the runtime object exists in the catalog. Support for storing triggers in the repository is planned for a future support package. Finally, you will learn how to create a database procedure proxy in ABAP which allows you to call a SQLScript procedure directly from the ABAP application server. Exercise Description Creating a procedure leveraging CE functions

    Create a SQLScript procedure using CE functions which read data from the business partner and address tables

    and return the result set via an output parameter.

    Test this procedure by calling it from the SQL Console.

    Creating a procedure leveraging imperative logic

    Create a SQLScript procedure using imperative logic which reads a product from the products table and determines

    the sale price based on the category of the product.

    Test this procedure by calling it from the SQL Console.

    Debugging SQLScript Procedures

    Open a procedure and set breakpoints

    Create a debug configuration for the procedure

    Debug the procedure using the debug perspective

    Set and remove breakpoints

    Evaluate input/output parameters and local variables.

    Creating Table User Defined Functions(UDFs)

    Create a table user defined function from the SQL Console

    Test the table UDF from the SQL Console

  • 75

    Creating Scalar User Defined Functions(UDFs)

    Create a scalar user defined function from the SQL Console

    Test the scalar UDF from the SQL Console

    Creating Triggers

    Create two tables using CDS format.

    Create a trigger for the products table

    Execute an INSERT against the products table

    Check the results in both the products table and the productLog table.

  • 76

    EXERCISE 4 SOLUTION

    Explanation Screenshot

    Creating a procedure leveraging CE functions

    1) Right-click on the

    procedures folder and choose New, then Other.

    2) From the SAP HANA Development folder, choose SQLScript Procedure. Click Next.

  • 77

    3) Enter the name of the procedure as get_bp_addresses_by_role and click Finish. The .procedure file extension will be added for you automatically.

    4) The SQLScript Editor will be opened. Click on the Local Table Types tab.

    5) Create a table type called tt_bp_addresses. Enter the code shown here in the Local Table Types tab. Refer to the exercise solutions & templates web page if you wish to copy/paste the code. http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX4_1

    create type tt_bp_addresses as table ( PARTNERID nvarchar(10), PARTNERROLE nvarchar(3), EMAILADDRESS nvarchar(255), COMPANYNAME nvarchar(80), ADDRESSID nvarchar(10), CITY nvarchar(40), POSTALCODE nvarchar(10), STREET nvarchar(60) )

  • 78

    6) Next, click on the SQLScript tab.

    7) Enter the coding as shown here. This procedure uses CE functions to retrieve data from two database tables, filter the data by partner role, and join the results into the output parameter. Refer to the exercise solutions & templates web page if you wish to copy/paste the code. http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX4_2

    CREATE PROCEDURE get_bp_addresses_by_role ( in partnerrole nvarchar(3), out bp_addresses tt_bp_addresses ) LANGUAGE SQLSCRIPT SQL SECURITY INVOKER

    --DEFAULT SCHEMA READS SQL DATA AS BEGIN /***************************** Write your procedure logic *****************************/ lt_bp = CE_COLUMN_TABLE("SAP_HANA_EPM_SP6"."sap.hana.democontent.epmSP6.data::EPM.MasterData.BusinessPartner", [PARTNERID, PARTNERROLE, EMAILADDRESS, COMPANYNAME, ADDRESSID]); lt_bp_proj = CE_PROJECTION(:lt_bp, [PARTNERID, PARTNERROLE, EMAILADDRESS, COMPANYNAME, ADDRESSID], '"PARTNERROLE" = :partnerrole' ); lt_address = CE_COLUMN_TABLE("SAP_HANA_EPM_SP6"."sap.hana.democontent.epmSP6.data::EPM.MasterData.Addresses", [ADDRESSID, CITY, POSTALCODE, STREET]); bp_addresses = CE_JOIN(:lt_bp_proj, :lt_address, [ADDRESSID], [PARTNERID, PARTNERROLE, EMAILADDRESS, COMPANYNAME, ADDRESSID, CITY, POSTALCODE, STREET]); END;

    8) Click Save.

  • 79

    9) Make sure that your procedure is selected in the project explorer and click the Activate button.

    10) Once the procedure is activated, right click on the SAP HANA System Library node in your project and choose SQL Console.

    11) In the SQL Console window, enter the following CALL statement. Make sure to substitute the session id and group number in the package name of this CALL statement. Refer to the exercise solutions & templates web page if you wish to copy/paste the code. http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX4_3

    call _SYS_BIC."workshop.session.g.procedures/get_bp_addresses_by_role"( partnerrole => '02', bp_addresses => ? );

    12) Click the Execute button.

  • 80

    13) The results of the procedure call are then shown.

    Creating a procedure leveraging imperative logic

    1) Use what you have

    learned so far in this exercise to create another procedure called get_product_sale_price. In the SQLScript tab, enter the following code as shown here. This procedure uses straight SQL(SELECT statements) and some imperative logic constructs to determine the sale price of a product based on the product category. Refer to the exercise solutions & templates web page if you wish to copy/paste the code. http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX4_4

    CREATE PROCEDURE get_product_sale_price ( IN productid NVARCHAR(10), OUT product_sale_price SAP_HANA_EPM_SP6."sap.hana.democontent.epmSP6.data::EPM.Procedures.tt_product_sale_price" ) LANGUAGE SQLSCRIPT SQL SECURITY INVOKER --DEFAULT SCHEMA READS SQL DATA AS BEGIN /***************************** Write your procedure logic *****************************/ declare lv_category nvarchar(40) := null; declare lv_discount decimal(15,2) := 0; lt_product = select PRODUCTID, CATEGORY, PRICE from "sap.hana.democontent.epmSP6.data::EPM.MasterData.Products" where PRODUCTID = :productid; select CATEGORY into lv_category from :lt_product; if :lv_category = 'Notebooks' then lv_discount := .20; elseif :lv_category = 'Handhelds' then lv_discount := .25; elseif :lv_category = 'Flat screens' then lv_discount := .30; elseif :lv_category like '%printers%' then lv_discount := .30; else lv_discount := 0.00; -- No discount end if; product_sale_price = select PRODUCTID, CATEGORY, PRICE, PRICE - cast((PRICE * :lv_discount) as decimal(15,2)) as "SALEPRICE" from :lt_product; END;

  • 81

    2) Save and Activate your new procedure. Finally, call the procedure from the SQL Console using the following CALL statement. Make sure to substitute the session id and group in the package name of this CALL statement. Refer to the exercise solutions & templates web page if you wish to copy/paste the code. http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX4_5

    call _SYS_BIC."workshop.session.g.procedures/get_product_sale_price"( productid => 'HT-1000', product_sale_price => ?);

    3) The results of the procedure call are then shown.

    Debugging SQLScript Procedures

    1) Open the procedure which

    you created in Exercise 3 by double-clicking it from your project.

    2) Click the Open Perspective button.

  • 82

    3) Select the Debug perspective and click Ok.

    4) If you do not see any line numbers in the procedure editor, you can enable this by right-clicking on the space to the left of the editor, and choose Show Line Numbers.

  • 83

    5) Set breakpoints at lines 14, 18, 20, 32, and 37 by double-clicking in the space immediately to the left of the line number.

    6) From the toolbar, click the down arrow next to the Debug icon. Choose Debug Configurations...

  • 84

    7) In the following dialog, double click on SQLScript Procedure.

    8) Enter the name of the debug configuration. This can be any name, but it is recommended to use something which reflects the procedure which is being debugged. Choose the radio button for Procedure to Debug, and click Browse.

  • 85

    9) Browse to the procedure and select it. Click Ok.

    10) Next, click on the Input Parameters tab.

    11) In this tab, all input parameters for the procedure will be listed. Set the value of the input parameter as shown here and click Apply, then Debug.

  • 86

    12) You will notice that the debug session has been initiated. Continue to the next step.

    13) Execution has stopped at the first breakpoint. Continue to the next step

    14) Click the Resume button to continue execution to the next breakpoint. You will see execution stop at the next breakpoint.

    15) On the variables tab, evaluate the values of the input/output parameters and intermediate variables. To view the contents of a table, right click on it, and choose Open Data Preview

  • 87

    16) A new tab appears at the bottom of the perspective which lists all the rows of the table.

    17) Continue debugging to the end of the procedure and evaluate the variables as you wish. Once debugging is complete, you can delete the terminated debug session by clicking the Remove All Terminated Launches button.

    18) Return to the SAP HANA Development perspective by clicking the button.

    Creating Table User Defined Functions(UDFs)

    1) From your project, right

    click on the SAP HANA System Library node, and choose SQL Console.

  • 88

    2) In the SQL Console, enter the code as shown here. This function will execute a SELECT(INNER JOIN) statement against the employee and address tables and filter by a fuzzy search on the last name. Make sure to substitute your session id and group number in the schema and function name in the CREATE FUNCTION statement. Refer to the exercise solutions & templates web page if you wish to copy/paste the code. http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX4_6

    CREATE FUNCTION "HANA_WORKSHOP_"."workshop.session.g/get_employees_by_name_filter" (lastNameFilter nvarchar(40)) RETURNS table ( EMPLOYEEID NVARCHAR(10), "Name.FIRST" NVARCHAR(40), "Name.LAST" NVARCHAR(40), EMAILADDRESS NVARCHAR(255), ADDRESSID NVARCHAR(10), CITY NVARCHAR(40), POSTALCODE NVARCHAR(10), STREET NVARCHAR(60)) LANGUAGE SQLSCRIPT SQL SECURITY INVOKER AS BEGIN RETURN

    select a.EMPLOYEEID, a."Name.FIRST", a."Name.LAST", a.EMAILADDRESS, a.ADDRESSID, b.CITY, b.POSTALCODE, b.STREET from "sap.hana.democontent.epmSP6.data::EPM.MasterData.Employees" as a inner join "sap.hana.democontent.epmSP6.data::EPM.MasterData.Addresses" as b on a.ADDRESSID = b.ADDRESSID where contains("Name.LAST", :lastNameFilter, FUZZY(0.9)); END;

    3) Click the Execute button.

    4) Browse the catalog and make sure your function has been created. Make sure you are browsing your specific schema which you created in exercise 2. You may have to refresh the folder.

  • 89

    5) Next, use your table UDF in a SELECT statement in the SQL Console. Enter the code as shown here. Make sure to substitute your session id and group number in the schema and function name. This SELECT statement is calling the UDF and passing the filter value *ll* which should return a table of employees whose last names contain two Ls. Refer to the exercise solutions & templates web page if you wish to copy/paste the code. http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX4_7

    select * from "HANA_WORKSHOP_"."workshop.session.g/get_employees_by_name_filter"('*ll*');

    6) Next, click the Execute button.

    7) The results are then shown.

    8) Optional: You can drop the function by simply using a DROP FUNCTION statement. If you wish to drop your function, enter the code shown here, and click Execute. Make sure to substitute your session id and group number in the schema and function name. Refer to the exercise solutions & templates web page if you wish to copy/paste the code. http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX4_8

    drop function "HANA_WORKSHOP_"."workshop.session.g/get_employees_by_name_filter";

  • 90

    Creating Scalar User Defined Functions(UDFs)

    1) Next, create a scalar UDF

    which applies a discount. In the SQL Console, enter the code as shown here. Make sure to substitute your session and group number in the schema and function name in the CREATE FUNCTION statement. Refer to the exercise solutions & templates web page if you wish to copy/paste the code. http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX4_9

    CREATE FUNCTION "HANA_WORKSHOP_"."workshop.session.g/apply_discount"( im_price decimal(15,2), im_discount decimal(15,2)) RETURNS result decimal(15,2) LANGUAGE SQLSCRIPT SQL SECURITY INVOKER AS BEGIN result := :im_price - ( :im_price * :im_discount ); END;

    2) Click Execute.

    3) Browse the catalog and make sure your function has been created. Make sure you are browsing your user schema which should be exactly the same name as the user id which you logged on with. You may have to refresh the folder.

  • 91

    4) Next, use your table UDF in a SELECT statement in the SQL Console. Enter the code as shown here. Make sure to substitute your session id and group number in the schema and function name. Refer to the exercise solutions & templates web page if you wish to copy/paste the code. http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX4_10

    select PRODUCTID, CATEGORY, PRICE, "HANA_WORKSHOP_"."workshop.session.g/apply_discount"(PRICE, 0.33 ) as "SalePrice" from "sap.hana.democontent.epmSP6.data::EPM.MasterData.Products";

    5) Click Execute.

    6) The results are then shown.

    7) Optional: You can drop the function by simply using a DROP FUNCTION statement. If you wish to drop your function, enter the code shown here, and click Execute. Make sure to substitute your session id and group number in the schema and function name. Refer to the exercise solutions & templates web page if you wish to copy/paste the code. http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX4_11

    drop function "HANA_WORKSHOP_"."workshop.session.g/apply_discount";

  • 92

    Creating Triggers

    1) First, create two tables

    using CDS. Right click on the data folder and choose New, then Other.

    2) From the following dialog, select the DDL Source File object from under the SAP HANA Development folder. Click Next.

  • 93

    3) Enter the name of the file as Product. Then click Finish. The .hdbdd file extension is added for you automatically.

    4) In the editor, enter the following code as shown here. Verify that the namespace contains your session id and group number packages. Make sure that the schema name is the schema that you created in exercise 2. Refer to the exercise solutions & templates web page if you wish to copy/paste the code. http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX4_12

    namespace workshop.session.g.data; @Schema: 'HANA_WORKSHOP_' context Product { @Catalog.tableType: #COLUMN Entity products{ key ProductId: String(10); Category: String(40); Price: Decimal(15,2); }; @Catalog.tableType: #COLUMN Entity productLog{ key ProductId: String(10); key DateTime: UTCDateTime; key UserName: String(20); LogText: String(500); }; };

  • 94

    5) Click Save.

    6) Click Activate.

    7) Browse the catalog under your schema and find the two new tables under the Tables folder. You may have to refresh the folder.

  • 95

    8) From your project, right-click on the SAP HANA System Library node and choose SQL Console.

    9) In the SQL Console, enter the following coding for creating the trigger. Make sure to substitute your session id and group number in the schema, the name of the trigger, the table in which it is being created for and in the INSERT statement. Refer to the exercise solutions & templates web page if you wish to copy/paste the code. http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX4_13

    CREATE TRIGGER "HANA_WORKSHOP_"."workshop.session.g/add_insert_to_log" AFTER INSERT ON "HANA_WORKSHOP_"."workshop.session.g.data::Product.products" REFERENCING NEW ROW newrow FOR EACH ROW BEGIN INSERT INTO "HANA_WORKSHOP_"."workshop.session.g.data::Product.productLog" VALUES(:newrow."PRODUCTID", now(), CURRENT_USER, :newrow."PRODUCTID" || ' has been created'); END;

    10) Click Execute.

  • 96

    11) Browse the catalog under your user schema and find the trigger under the Triggers folder. You may have to refresh the folder.

    12) Next, enter the following code into the SQL Console.. Make sure to substitute your session id and group number in the schema and name of the table. Refer to the exercise solutions & templates web page if you wish to copy/paste the code. http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX4_14

    INSERT into "HANA_WORKSHOP_"."workshop.session.g.data::Product.products" values( 'ProductA', 'Software', '299.99');

    13) Click Execute.

  • 97

    14) Next, enter the following code into the SQL Console.. Make sure to substitute your session id and group number in the schema and name of the table. Refer to the exercise solutions & templates web page if you wish to copy/paste the code. http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX4_15

    select * from "HANA_WORKSHOP_"."workshop.session.g.data::Product.products"; select * from "HANA_WORKSHOP_"."workshop.session.g.data::Product.productLog";

    15) Click Execute.

    16) The results of the two SELECT statements are shown. You can see that after an INSERT into the products table, an entry has also been created in the productLog table as well.

  • 98

    17) Optional: You can drop the trigger by simply using a DROP TRIGGER statement. If you wish to drop your trigger, enter the code shown here, and click Execute. Make sure to substitute your session id and group number in schema and the trigger name. Refer to the exercise solutions & templates web page if you wish to copy/paste the code. http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX4_16

    drop trigger "HANA_WORKSHOP_"."workshop.session.g/add_insert_to_log";

    You have completed the exercise!

    You are now able to:

    Create and test a procedure leveraging CE functions to read data from the database. Create and test a procedure leveraging imperative logic. Set and remove breakpoints Create a debug configuration Debug a procedure using the Debug perspective Evaluate input/output parameters and local variables Create and test a table user defined function Create and test a scalar user defined function Create tables using CDS format Create a trigger Test the trigger

  • 99

    EXERCISE 5 ODATA SERVICES

    Objective Learn how to use the generic OData service generation framework in HANA. We will define simple OData services, OData services with relationships, and OData services with update capabilities. The XSEngine contains a special tool for the creation of OData Services without needing to perform server side coding. To create an OData service from an existing HANA table or view, you need only define an XSODATA service definition file. Exercise Description

    Create a Basic OData Service

    Create an OData Service with relationships

    Create an OData Service with Create/Update/Delete operations and SQLScript exits

  • 100

    EXERCISE 5 SOLUTION

    Explanation Screenshot

    Creating a Simple OData Service

    1) We will create all of our services objects within the services folder of our project. This simply helps keep the various parts of our application separated for easier use and maintenance. Create a new file called businessPartners.xsodata in the services package of your project.

    2) The editor might cause this file to open in a new window with Notepad.

  • 101

    3) If this does happen, simply close this window. Then right click on the file and choose Open With -> Text Editor.

    4) We want to define an OData service to expose the business partner table. The syntax of the XSODATA service is relative easy for this use case. We need only define a namespace (your package path), the name of the HANA Table we will base the service from ( sap.hana.democontent.epm.data::businessPartner) and the name of the OData entity (BusinessPartners). Therefore the content of the XSODATA file would be. Note: if you dont want to type this code, we recommend that you cut and paste it from this web address http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX5_1

  • 102

    5) Save and activate the file.

    6) Now run the service from Chrome. The URL to run your service would be http://:/workshop/session#/gXX/services/businessPartners.xsodata where # is your session id and XX is your group number. For example if your session was x and your group number was 00 then the URL would be: http://:/workshop/sessionx/g00/services/businessPartners.xsodata The resulting document describes the service entities. We only had the one entity named BusinessPartners.

  • 103

    7) You can now adjust the URL slightly and add the $metadata parameter to the end of it. The URL to run your service would be http://:/workshop/session#/gXX/services/businessPartners.xsodata/$metadata where # is your session id and XX is your group number. For example if your session letter was X and your group number was 00 then the URL would be: http://:/workshop/sessionx/g00/services/businessPartners.xsoda

    ta/$metadata You can see the field descriptions for all the attributes of the OData service.

    8) In order to view the data of the entity, you would append BusinessPartners to the end of the URL: http://:/workshop/sessionx/g00/services/businessPartners.xsodata/BusinessPartners You are now able to see the data from the businessPartner table.

  • 104

    9) You can also experiment with standard OData URL parameters like $top, $skip, or $filter. These options are interpreted and handled by the OData service of the XSEngine for you. You get complex service handling without any coding. For example the following URL would return only three business partner records and would skip the first five records. Such parameters are helpful when implementing server side scrolling, filtering, or sorting in table UI elements. http://:/Other.

    2) From the New Wizard, choose XS JavaScript Source File from the SAP HANA Development folder

  • 112

    3) Select the services folder. Name your new source file: HelloWorld.xsjs.

    4) We want to create a service which uses the Database APIs to call a select from the dummy table and outputs the results along with a Hello World text string. Note: if you dont want to type this code, we recommend that you cut and paste it from this web address http://:/workshop/admin/ui/exerciseMaster/?workshop=x&sub=EX6_1 Save and Activate your new service.

  • 113

    5) Test the service in your browser. The URL to run your service would be http://:/workshop/session/g/services/HelloWorld.xsjs. For example if your session letter was x and your group number was 00 then the URL would be: http://:/workshop/sessionx/g00/services/HelloWorld.xsjs

    Creating an XSJS Service with custom output format

    1) Now we want to extend the concepts of the XSJS service from the first half of this exercise. Weve already seen how we can use our own custom logic in an XSJS service. Next we want to see how we can use a custom output format. We will also see how we can perform SQL to use data from the database, but manipulate or format that returned data. The final result will be a service which reads the Business Partner data but returns it in a tab delimited format ready to open in Microsoft Excel. Using the same steps as before use the file wizard to create another xsjs service named exercise.xsjs. Note: if you dont want to type this code, we recommend that you cut and paste it from this web address http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX6_2 We will explain it block by block in a moment.

  • 114

    2) First weve added an import to a reusable library. We can create such libraries and share them between projects and services. This particular library helps lookup reusable language independent texts from the database. We will use it to fill in the column headers of our Excel export

    $.import("sap.hana.democontent.epmSP6.services", "messages"); var MESSAGES = $.sap.hana.democontent.epmSP6.services.messages;

    3) We add a new function to handle the data retrieval from the Business Partner Table and formatting into Text Tab Delimited. The XSJS server side logic contains various built-in APIs (referenced via the $ object). Here you see the usage of the trace object and the db (database) objects. We build the SQL Query and pass it to the database using syntax very similar to JDBC or ODBC. In reality, the XS engine communicates directly with the HANA Index server to retrieve this data Next you see that we can build a custom formatted string in order to get the text, tab-delimited output we want. Finally we can also set any response headers, which is necessary to control the Content-Disposition so the output acts like a file download from the browser.

    4) This block is actually the entry point to the service handler but must appear after all referenced functions. Here we can query the request URL and determine which action to take. This way a single XSJS file might have multiple services or query parameters. We will look for the URL parameter

  • 115

    called cmd to decide which path to take. These are just examples, as you have complete control over the definition of all URL parameters and how they are handled by the service

    5) Save and Activate your service.

    6) Test the application in your browser. The URL to run your service would be http://:/workshop/session/g/services/exercise.xsjs?cmd=Excel . For example if your session letter was x and your group number was 00 then the URL would be: http://:/workshop/sessionx/g00/services/exercise.xsjs?cmd=Excel

  • 116

    7) Your data should then show up in Excel

    Creating an XSJS Service with outbound HTTP Connectivity

    1) A new feature in SP6 is the ability for XSJS services to also make outbound HTTP calls. In this step we will extend the previous service to make a request to the Library of Congress Image database and return the results to HANA.

  • 117

    2) First we must create an XSHTTPDEST file. This file defines the outbound destination connection parameters. This file must be created in the same package as the service which will use it. Create a new file named images.xshttpdest in your services folder.

    The URL for the remote service is www.loc.gov. The port is 80. The path is /pictures/search/?fo-json&q=. The proxy host is proxy and the proxy port is 8080. Please use the instructions from workshop leader as the proxy host and port can vary depending upon the conditions of the works. If no proxy is required, simply change the value of useProxy to false. Save and active this file. Note: if you dont want to type this code, we recommend that you cut and paste it from this web address http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX6_3

  • 118

    3) Although not needed for this exercise, the XS Admin website can also be used to maintain HTTP Destination settings after creating the xshttpdest file via the developer tools. Only from this website can you configure more advanced settings such as client authentication.

  • 119

    4) Now edit the exercise.xsjs from the previous exercise. Add a new function to the service to call the outbound HTTP connection. Take in to additional URL parameters for the remote search term and the image index in the search results. Be sure to remember to replace your correct package path in the readDestination call. Note: if you dont want to type this code, we recommend that you cut and paste it from this web address http://:/workshop/admin/ui/exerciseMaster/?workshop=xs&sub=EX6_4

    5) Extend the entry point block as well to include the call to this new function. Save and activate the service.

  • 120

    6) Test the application in your browser. The URL to run your service would be http://:/workshop/session/g/services/exercise.xsjs?cmd=Images&search=. For example if your session letter was x and your group number was 00 and you wanted to search for images of HANA then the URL would be: http://:/workshop/sessionx/g00/services/exercise.xsjs?cmd=Images&search=HANA

    7) You can page through the search results by adding the index URL parameter. To search for the 10

    th

    image in the HANA results set use this URL: http://:/workshop/sessionx/g00/services/exercise.xsjs?cmd=Images&search=HANA&index=10

  • 121

    Debug a XSJS Service from HANA Studio

    1) In order to debug XSJS services, there are several configuration steps that are required. First, the you must first enable debugging in the xsengine.ini file. From the Administrative perspective, expand xsengine.ini, then expand debugger. Change the value for enabled to true. This step is already done for you in this HANA system, continue to the next step.

    2) Another prerequisite is that your user id must have the privilege to debug. In SP6, this privilege is granted via a standard role sap.hana.xs.debugger::Debugger. This step has already been done for you in this HANA system, continue to the next step.

    3) Next, you need to create a debug configuration. Click the down arrow next to the Debug As button, then Debug Configurations.

  • 122

    4) Double click XS JavaScript.

    5) Enter the name of the configuration as XS_Workshop. Next, enter the host and port. Host and port will be supplied to you by the instructor. Finally, enter your user id and password, and click Apply, then Close.

  • 123

    6) Next, open the exercise.xsjs file that you created earlier.

    7) In the editor, navigate to the downloadExcel function. You can set breakpoints by double clicking in the bar to the far left.

    8) You can also set a breakpoint using Toggle Breakpoint from the context menu.

  • 124

    9) Set breakpoints at lines 10, 24, and 39.

    10) Before we can start the debugger we must first test the service once in a web browser in order to know our session id. The session id must be supplied to the debugger on start up so it knows which session to connect to and debug. Launch Chrome and open the developer tools.

  • 125

    11) Make sure you are on the Network tab of the developer tools.

    12) Test the application in your browser. The URL to run your service would be http://:/workshop/session/g/services/exercise.xsjs?cmd=Excel . For example if your session letter was x and your group number was 00 then the URL would be: http://:/workshop/sessionx/g00/services/exercise.xsjs?cmd=Excel

  • 126

    13) After calling the service you can display the Headers details of the request to exercise.xsjs. In the Request Headers there should be a cookie called xsSessionId. The value of this cookie will be the value you use in the next steps.

    14) Switch back to SAP HANA Studio without closing your web browser. Switch to the Debug perspective.

    15) Click the down arrow next to the Debug As button and choose Debug Configurations.

  • 127

    16) Choose the debug configuration which you created earlier and choose Debug.

    17) Select your user id from the dropdown, then match the session id in the dialog to the one in your web browser. Click Select.

  • 128

    18) You can now refresh your web browser to make another request to this same service. This should start the interactive debugger. You should see the debugger stopping processing on the first breakpoint. You can also see the values in your JavaScript variables.

    19) Try experimenting with various features of the debugger. You can change values of variables in the debugger. Try changing the query string before it is passed to the prepareStatement. Experiment with the various navigation and observation tools built into the debugger

  • 129

    Alternative: Debug a XSJS Service from the SAP HANA Web-based Development Workbench

    1) You can also debug an

    XSJS service from the SAP HANA Web-based Development Workbench. Open a browser and go to the following URL. http://:/sap/hana/xs/ide/ Enter th