You are on page 1of 25

Week 1: Database Development

Unit 4: SQLScript
SQLScript
Overview

SQLScript is
 Extension of ANSI standard SQL
 Language for creating stored procedures and user-defined functions in SAP HANA
 Set-based declarative SQL & imperative control flow constructs
 Suitable for mass data processing and OLTP scenarios as well

Advantages compared to plain SQL:


 Smaller, parameterized reusable chunks of code (procedures, functions)
 Well-structured query logic (using table variables)
 improves maintainability
 gains performance by parallel execution
 debuggable intermediate steps
 Supports invoker security mode

© 2017 SAP SE or an SAP affiliate company. All rights reserved. ǀ PUBLIC 2


SQLScript
Parallelization

If multiple statements do not dependent on each other they are candidates for parallelization
Supported: Not Supported:
 Table assignments  DMLs
 Read-only procedures  Read-write procedures
 SELECT INTO  Implicit SELECT
– Use parallel execution blocks to parallelize these statements
BEGIN PARALLEL EXECUTION
<dml_stmt>
END;

© 2017 SAP SE or an SAP affiliate company. All rights reserved. ǀ PUBLIC 3


SQLScript
Implicit parallelization

BEGIN

product_ids = SELECT ProductId, Category, DescId
FROM PRODUCTS
WHERE Category = 'Notebooks' or Category = 'PC';

product_texts = SELECT ProductId, Category, DescId, Text


FROM :product_ids as prod_ids
INNER JOIN TEXTS
AS texts ON prod_ids.DescId = texts.TextId;

SELECT COUNT(*) INTO out_notebook_count


FROM :product_texts WHERE Category = 'Notebooks';

SELECT COUNT(*) INTO out_pc_count


FROM :product_texts WHERE Category = 'PC';

SELECT COUNT(*) INTO out_total_count


FROM products;

END;

© 2017 SAP SE or an SAP affiliate company. All rights reserved. ǀ PUBLIC 4


SQLScript
Explicit parallelization

CREATE PROCEDURE cproc3 AS


BEGIN
INSERT INTO ctab3 values (2);
END;

CREATE PROCEDURE cproc4 AS


BEGIN
INSERT INTO ctab4 values (3);
END;

CREATE PROCEDURE parallel (…) AS


BEGIN
...

UPDATE CTAB1 SET A = A + 1;


UPDATE CTAB2 SET A = A + 1;
CALL CPROC4();
CALL CPROC3();

...

END;
© 2017 SAP SE or an SAP affiliate company. All rights reserved. ǀ PUBLIC 5
SQLScript
Explicit parallelization

CREATE PROCEDURE cproc3 AS


BEGIN
INSERT INTO ctab3 values (2);
END;

CREATE PROCEDURE cproc4 AS


BEGIN
INSERT INTO ctab4 values (3);
END;

CREATE PROCEDURE parallel (…) AS


BEGIN
...
BEGIN PARALLEL EXECUTION Restrictions:
UPDATE CTAB1 SET A = A + 1;  Only column-store tables
UPDATE CTAB2 SET A = A + 1;  Modification of tables with a foreign key or triggers are not allowed
CALL CPROC4();  Updating the same table in different statements is not allowed
CALL CPROC3();  Reading / writing the same table is not allowed
END;  Calling procedures containing dynamic SQL (for example, EXEC, EXECUTE IMMEDIATE)
... is not supported in parallel blocks
 Mixing read-only procedure calls and read-write procedure calls in a parallel block is not
END; allowed
© 2017 SAP SE or an SAP affiliate company. All rights reserved. ǀ PUBLIC 6
SQLScript
Dynamic SQL with in/out scalar variables

Allows to pass scalar parameters to the SQL


query as well as return scalar output values
 Does not support table variables
 Use ? or $1, $2, $3 to parameterize the query.
Can only use in SQL statements where query
parameters are supported
 Query will fail if the result set does not have a
single row

© 2017 SAP SE or an SAP affiliate company. All rights reserved. ǀ PUBLIC 7


SQLScript
Index-based cell access for table variables

 Allows the developer to access any


cell (read/write) of an intermediate
table variable or table parameter
directly
– Access via
<table>.<column>[<index>] notation
 Introduced in SAP HANA 2.0 SPS00

© 2017 SAP SE or an SAP affiliate company. All rights reserved. ǀ PUBLIC 8


SQLScript
INSERT/UPDATE/DELETE operators for table variables

 Allows the developer to execute DML-like


statements on intermediate table variables
without involving the SQL layer
 Leads to increased performance
 Operations supported
– INSERT
– UPDATE
– DELETE

© 2017 SAP SE or an SAP affiliate company. All rights reserved. ǀ PUBLIC 9


SQLScript
RECORD_COUNT operator

RECORD_COUNT
 Function provides the number of rows of a
given table
 Previously, SELECT COUNT* INTO a variable
or a combination of CARDINALITY and
ARRAY_AGG functions were used
 Both physical tables and table
variables/parameters are supported

© 2017 SAP SE or an SAP affiliate company. All rights reserved. ǀ PUBLIC 10


SQLScript
MAP_MERGE operator

MAP_MERGE
 Operator to apply each row of a
tabular input to a mapper function
and union all intermediate result
tables

© 2017 SAP SE or an SAP affiliate company. All rights reserved. ǀ PUBLIC 11


SQLScript
MAP_MERGE operator – Example

Sequential Execution ( 759ms ) Parallel Execution ( 34ms )

© 2017 SAP SE or an SAP affiliate company. All rights reserved. ǀ PUBLIC 12


SQLScript
Procedure/function encryption

Hides the implementation of the


procedure or function from all users
 The entire definition of the procedure or function
including its signature is saved as an encrypted
string that is not human-readable
 Encrypting a procedure/function means hiding
the content, and this implies losing supportability
features and losing optimizations. Therefore,
encrypted procedures/functions will not be
supported by SQLScript Debugger, PlanViz,
traces, or any supportability tools that can reveal
the procedure/function definitions

© 2017 SAP SE or an SAP affiliate company. All rights reserved. ǀ PUBLIC 13


SQLScript
Support for spatial types/functions

 SQLScript supports the spatial data


type ST_GEOMETRY and SQL spatial
functions to access and manipulate
the spatial data
 SQLScript also supports the objective
style function calls, which are needed
for some SQL spatial functions

© 2017 SAP SE or an SAP affiliate company. All rights reserved. ǀ PUBLIC 14


SQLScript
Global session variables

Global session variables can be used in


SQLScript to share a scalar value between a
procedure and function that are running in
the same session.
 Not visible from another session
 SET <key> = <value> cannot be used within read-
only procedures and functions
 <key> can be a constant string or variable
 <value> can be any expression or scalar variable or
function which returns a variable which can be
converted to type string
 Session variables are null by default, and can be
reset to null by using the UNSET statement

© 2017 SAP SE or an SAP affiliate company. All rights reserved. ǀ PUBLIC 15


SQLScript
Parameterization control of scalar variables

BIND_AS_<PARAMETER|VALUE>
 Control the parametrization behavior of
scalar variables
 Allows to manually override the optimizer’s
parameterization decision and general
configuration

© 2017 SAP SE or an SAP affiliate company. All rights reserved. ǀ PUBLIC 16


SQLScript
Parameterization control of scalar variables – Example

Procedure Call Prepared Statement


select * from "MD.Products"
where typecode = ?
and category = ‘Notebooks’;

select * from "MD.Products"


where typecode = ‘PR’
and category = ‘Notebooks’;

select * from "MD.Products"


where typecode = ?
and category = ?;
© 2017 SAP SE or an SAP affiliate company. All rights reserved. ǀ PUBLIC 17
SQLScript
Parameterization control of scalar variables – Example

Procedure Call Prepared Statement


select * from "MD.Products"
where typecode = ‘PR’
and category = ? ;

select * from "MD.Products"


where typecode = ‘PR’
and category = ? ;

select * from "MD.Products"


where typecode = ‘PR’
and category = ? ;
© 2017 SAP SE or an SAP affiliate company. All rights reserved. ǀ PUBLIC 18
SQLScript
Built-in libraries and sleep/wake functions

Implemented in the new built-in library


SYS.SQLSCRIPT_SYNC
 SLEEP_SECONDS – makes the current process
wait for the given number of seconds
 WAKEUP_CONNECTION – resumes a process
waiting due to SLEEP_SECONDS

© 2017 SAP SE or an SAP affiliate company. All rights reserved. ǀ PUBLIC 19


SQLScript
SQLScript code analyzer – Overview

The SQLScript code analyzer consists of two built-in procedures that scan CREATE
FUNCTION / CREATE PROCEDURE statements. By applying a selected set of rules, they
search for certain patterns that indicate problems regarding code quality, performance,
or security.
 Rules are defined in view SQLSCRIPT_ANALYZER_RULES; currently 4 rules
 Procedure ANALYZE_SQLSCRIPT_DEFINITION can be used to analyze the source code of a single
procedure or function which has yet to be created. Procedure ANALYZE_SQLSCRIPT_OBJECTS can be
used to analyze the source code of multiple already existing procedures or functions
 The SQLScript code analyzer is currently deactivated by default. It can be activated with an ini parameter or
a session parameter:

alter system alter configuration ('indexserver.ini','SYSTEM') set


('sqlscript', 'enable_code_scanner') = 'true' with reconfigure;

set '__SQLSCRIPT_ENABLE_CODE_SCANNER' = 'true';


© 2017 SAP SE or an SAP affiliate company. All rights reserved. ǀ PUBLIC 20
SQLScript
SQLScript code analyzer – Rules

 UNNECESSARY_VARIABLE: Each variable is tested if it is used by any output parameter of the procedure
or if it influences the outcome of the procedure. Relevant statements for the outcome could be DML
statements, implicit result sets, conditions of control statements.
 UNUSED_VARIABLE_VALUE: If a value assigned to a variable is not used in any other statement, the
assignment can be removed. In case of default assignments in DECLARE statements, the default is never
used.
 UNCHECKED_SQL_INJECTION_SAFETY: Parameters of string type should always be checked for SQL
injection safety if they are used in dynamic SQL. This rule checks if for any such parameter the function
is_sql_injection_safe was called. For a simple conditional statement like IF is_sql_injection_safe(:var) = 0
THEN..., the control flow in the true branch is checked. The procedure should either end (by returning or by
throwing an error) or the unsafe parameter value should be escaped with the functions
escape_single_quotes or escape_double_quotes, depending on where the value is used. If the condition is
more complex (e.g. more than one variable checked in one condition), a warning will be displayed, as it
could only be checked if any execution of the dynamic SQL has passed the SQL injection check.
 SINGLE_SPACE_LITERAL: This rule searches for string laterals consisting of only one space. If ABAP
VARCHAR MODE is used, such string literals are treated as empty strings. In this case, CHAR(32) can be
used instead of ' '.
© 2017 SAP SE or an SAP affiliate company. All rights reserved. ǀ PUBLIC 21
SQLScript
SQLScript code analyzer – ANALYZE_SQLSCRIPT_DEFINITION

 Procedure expects 2 input parameters: a string containing the DDL of the procedure or function and the list
of rules
 Procedure returns 1 output parameter: the list of findings

© 2017 SAP SE or an SAP affiliate company. All rights reserved. ǀ PUBLIC 22


SQLScript
SQLScript code analyzer – ANALYZE_SQLSCRIPT_OBJECTS

 Procedure expects 2 input parameters: a list of objects which are to be scanned, and a list of rules
 Procedure returns 2 output parameters: a list of objects which were scanned, and the findings

© 2017 SAP SE or an SAP affiliate company. All rights reserved. ǀ PUBLIC 23


Thank you.
Contact information:

open@sap.com
© 2017 SAP SE or an SAP affiliate company. All rights reserved.

No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP SE or an SAP affiliate company.

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 specifications may vary.

These materials are provided by SAP SE or an SAP affiliate company for informational purposes only, without representation or warranty of any kind, and SAP or its affiliated
companies shall not be liable for errors or omissions with respect to the materials. The only warranties for SAP or SAP affiliate company products and services are those that are
set forth in the express warranty statements accompanying such products and services, if any. Nothing herein should be construed as constituting an additional warranty.

In particular, SAP SE or its affiliated companies have no obligation to pursue any course of business outlined in this document or any related presentation, or to develop or release
any functionality mentioned therein. This document, or any related presentation, and SAP SE’s or its affiliated companies’ strategy and possible future developments, products,
and/or platform directions and functionality are all subject to change and may be changed by SAP SE or its affiliated companies at any time for any reason without notice. The
information in this document is not a commitment, promise, or legal obligation to deliver any material, code, or functionality. All forward-looking statements are subject to various
risks and uncertainties that could cause actual results to differ materially from expectations. Readers are cautioned not to place undue reliance on these forward-looking statements,
and they should not be relied upon in making purchasing decisions.

SAP and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of SAP SE (or an SAP affiliate company)
in Germany and other countries. All other product and service names mentioned are the trademarks of their respective companies.
See http://global.sap.com/corporate-en/legal/copyright/index.epx for additional trademark information and notices.

You might also like