### Run Example Script (Bash) Source: https://github.com/sap/node-hdb/blob/master/README.md Command to execute one of the example JavaScript files using Node.js. This is a basic utility for testing the provided examples. ```bash node examples/app1 ``` -------------------------------- ### Install Browserify Globally Source: https://github.com/sap/node-hdb/wiki/Develop-Chrome-Apps-for-SAP-HANA Installs Browserify as a global npm package, which is a prerequisite for bundling Node.js modules for use in the browser. ```bash npm install -g browserify ``` -------------------------------- ### Clone node-hdb and Install Dependencies Source: https://github.com/sap/node-hdb/wiki/Develop-Chrome-Apps-for-SAP-HANA Clones the node-hdb repository from GitHub and installs its development dependencies using npm. This prepares the project for bundling. ```bash git clone https://github.com/SAP/node-hdb.git cd node-hdb npm install ``` -------------------------------- ### Proxy Connections via SOCKS5, HTTP, and SCC with HDB Source: https://context7.com/sap/node-hdb/llms.txt This JavaScript example shows establishing connections through various proxies (SOCKS5, HTTP with TLS, and SAP Cloud Connector) using the hdb module. It requires 'hdb' and proxy credentials; inputs include host, port, user, and proxy details, outputting success or error. Note that SAP Cloud Connector variant assumes specific account setup, and errors are logged without retries. ```javascript const hdb = require('hdb'); // SOCKS5 proxy const client = hdb.createClient({ host: 'hostname', port: 30015, user: 'user', password: 'secret', proxyHostname: 'proxy.company.com', proxyPort: 1080, proxyUserName: 'proxyuser', proxyPassword: 'proxypass' }); // HTTP proxy (implies TLS) const client2 = hdb.createClient({ host: 'hostname', port: 30015, user: 'user', password: 'secret', proxyHostname: 'proxy.company.com', proxyPort: 8080, proxyHttp: true, proxyUserName: 'proxyuser', proxyPassword: 'proxypass' }); // SAP Cloud Connector const client3 = hdb.createClient({ host: 'hostname', port: 30015, user: 'user', password: 'secret', proxyHostname: 'connector.cloud.sap', proxyPort: 20003, proxyScpAccount: 'subaccount.locationID' }); client.connect(function(err) { if (err) return console.error('Proxy connect error:', err); console.log('Connected via proxy'); client.end(); }); ``` -------------------------------- ### Establish SAP HANA Connection with Session Variables (JavaScript) Source: https://github.com/sap/node-hdb/blob/master/README.md This example shows how to create an SAP HANA client instance and configure it with session variables during the connection process. It includes registering an error handler for network issues and logs the initial ready state of the client. ```javascript var hdb = require('hdb'); var client = hdb.createClient({ host : 'hostname', port : 30015, user : 'user', password : 'secret', 'SESSIONVARIABLE:EXAMPLEKEY' : 'EXAMPLEVALUE' }); client.on('error', function (err) { console.error('Network connection error', err); }); console.log(client.readyState); // new ``` -------------------------------- ### Query with Nesting Option (JavaScript) Source: https://github.com/sap/node-hdb/blob/master/README.md Shows an example of how to use the `nestTables` query option with the node-hdb library. This option is useful for retrieving hierarchical data structures from the database efficiently. ```javascript const hdb = require('hdb'); const client = hdb.createClient({ // connection details... }); client.connect((err) => { if (err) { console.error('Error connecting to HANA:', err); return; } const sql = 'SELECT * FROM "MY_TABLE"'; const queryOptions = { nestTables: true }; client.exec(sql, queryOptions, (err, result) => { if (err) { console.error('Error executing query:', err); } else { console.log('Query result with nested tables:', JSON.stringify(result, null, 2)); } client.end(); }); }); ``` -------------------------------- ### Connect to SAP HANA System Database (JavaScript) Source: https://github.com/sap/node-hdb/blob/master/README.md This code illustrates how to create a client instance to connect to the system database of an SAP HANA MDC (Multi-Database Container) setup. It specifies the host and port for the system database, preparing for potential connection to tenant databases. ```javascript var hdb = require('hdb'); var client = hdb.createClient({ host : 'hostname', // system database host port : 30013, // system database port ``` -------------------------------- ### Multi-Tenant Database Connection (MDC) in JavaScript Source: https://context7.com/sap/node-hdb/llms.txt Shows how to connect to a specific tenant database in a multi-tenant SAP HANA environment using node-hdb. Includes examples with system database and instance number. ```JavaScript const hdb = require('hdb'); // Connect via system database to specific tenant const client = hdb.createClient({ host: 'hostname', // system database host port: 30013, // system database port databaseName: 'TENANT1', // tenant database name user: 'user', password: 'secret' }); // Alternative: use instance number instead of port const client2 = hdb.createClient({ host: 'hostname', instanceNumber: '00', // HANA instance number databaseName: 'TENANT1', user: 'user', password: 'secret' }); // Multiple hosts for distributed systems const client3 = hdb.createClient({ hosts: [ { host: 'host1', port: 30015 }, { host: 'host2', port: 30015 } ], user: 'user', password: 'secret' }); client.connect(function(err) { if (err) return console.error(err); console.log('Connected to tenant database'); client.end(); }); ``` -------------------------------- ### Execute Prepared Statement with Positional Parameters in Node.js hdb Source: https://context7.com/sap/node-hdb/llms.txt Shows how to prepare a SQL statement containing positional placeholders, execute it with an array of parameters, and process the returned rows. The example also demonstrates dropping the prepared statement and terminating the client connection. ```javascript const client = require('hdb').createClient({ host: 'hostname', port: 30015, user: 'user', password: 'secret' }); client.connect(function(err) { if (err) return console.error(err); // Prepare statement with positional parameters client.prepare('SELECT * FROM DUMMY WHERE DUMMY = ?', function(err, statement)n if (err) { return console.error('Prepare error:', err); } console.log('Statement ID:', statement.id); console.log('Parameter metadata:', statement.parameterMetadata); console.log('Result metadata:', statement.resultSetMetadata); // Execute with parameter array statement.exec(['X'], function(err, rows) { if (err) { return console.error('Execute error:', err); } console.log('Rows:', rows); // [{ DUMMY: 'X' }] // Drop statement when done statement.drop(function(err) { if (err) console.error('Drop error:', err); client.end(); }); }); }); }); ``` -------------------------------- ### Configure SAP HDB Client Options in JavaScript Source: https://context7.com/sap/node-hdb/llms.txt This example demonstrates setting configuration options for the SAP HANA Database client, including connection parameters and runtime settings like fetch size. It relies on the node-hdb library for connection. Input includes host, port, user, and password; output is a configured client with updated options. Limitations include packet size constraints between 64KB and 1GB. ```javascript const client = require('hdb').createClient({ host: 'hostname', port: 30015, user: 'user', password: 'secret', // CESU-8 encoding (false for UTF-8, better performance) useCesu8: false, // Default fetch size for result sets fetchSize: 1024, // Hold cursors over commit holdCursorsOverCommit: true, // Enable scrollable cursors scrollableCursor: true, // Packet size configuration (64KB to 1GB-1) packetSize: Math.pow(2, 17), // 128KB packetSizeLimit: Math.pow(2, 20), // 1MB max // Enable network compression compress: true, // TCP keepalive (seconds, or false to disable) tcpKeepAliveIdle: 200 }); client.connect(function(err) { if (err) return console.error(err); // Get configuration value console.log('User:', client.get('user')); console.log('Host:', client.get('host')); console.log('FetchSize:', client.get('fetchSize')); // Set runtime configuration client.set('fetchSize', 2048); console.log('Updated FetchSize:', client.get('fetchSize')); client.end(); }); ``` -------------------------------- ### Stream LOB Data from HANA using Node.js Source: https://context7.com/sap/node-hdb/llms.txt This example illustrates how to stream Large Object (LOB) data, such as images, from the HANA database to a local file using Node.js. It connects to the database, executes a query to retrieve LOB data, and then creates an object stream. Each row's LOB object is then processed by creating a read stream from the LOB and piping it to a file write stream. The example includes configuration for fetch size and read size for efficient LOB handling. ```javascript const fs = require('fs'); const client = require('hdb').createClient({ host: 'hostname', port: 30015, user: 'user', password: 'secret' }); client.connect(function(err) { if (err) return console.error(err); // Use execute to get LOB objects client.execute('SELECT ID, IMAGE_DATA FROM PHOTOS WHERE ID = 1', function(err, resultSet) { if (err) return console.error(err); resultSet.setFetchSize(1); // Configure LOB read size resultSet.setReadSize(1024 * 1024); // 1MB chunks const stream = resultSet.createObjectStream(); stream.on('data', function(row) { // row.IMAGE_DATA is a Lob object const lob = row.IMAGE_DATA; console.log('LOB type:', lob.type); // 'BLOB' console.log('LOB length:', lob.length); // size in bytes console.log('LOB locator:', lob.locatorId); // Create read stream from LOB const lobStream = lob.createReadStream(); const fileStream = fs.createWriteStream('/tmp/image.jpg'); lobStream.pipe(fileStream); lobStream.on('end', function() { console.log('LOB streaming complete'); }); lobStream.on('error', function(err) { console.error('LOB stream error:', err); }); }); stream.on('end', function() { if (!resultSet.closed) resultSet.close(); client.end(); }); }); }); ``` -------------------------------- ### Call Stored Procedure with Output Parameters via Node.js hdb Source: https://context7.com/sap/node-hdb/llms.txt Provides a full example of creating a stored procedure, preparing a CALL statement, executing it with input parameters, and retrieving both output parameters and a result set. It also shows how to drop the statement and close the client. ```javascript const client = require('hdb').createClient({ host: 'hostname', port: 30015, user: 'user', password: 'secret' }); client.connect(function(err) { if (err) return console.error(err); // Create procedure: in a, in b, out c, out d (result set) const createProc = [ 'CREATE PROCEDURE PROC_DUMMY (IN a INT, IN b INT, OUT c INT, OUT d DUMMY)', 'LANGUAGE SQLSCRIPT', 'READS SQL DATA AS', 'BEGIN', ' c := :a + :b;', ' d = SELECT * FROM DUMMY;', 'END;' ].join('\n'); client.exec(createProc, function(err) { if (err && err.code !== 328) return console.error(err); // ignore if exists // Prepare call statement client.prepare('CALL PROC_DUMMY (?, ?, ?, ?)', function(err, statement) { if (err) return console.error(err); // Execute with input parameters statement.exec({ A: 3, B: 4 }, function(err, parameters, dummyRows) { if (err) return console.error(err); console.log('Output parameters:', parameters); // { A: 3, B: 4, C: 7 } console.log('Result set:', dummyRows); // [{ DUMMY: 'X' }] statement.drop(); client.end(); }); }); }); }); ``` -------------------------------- ### Call Stored Procedure (JavaScript) Source: https://github.com/sap/node-hdb/blob/master/README.md Provides a basic example of how to call a stored procedure in SAP HANA using the node-hdb library. This function is essential for executing business logic defined within the database. ```javascript const hdb = require('hdb'); const client = hdb.createClient({ // connection details... }); client.connect((err) => { if (err) { console.error('Error connecting to HANA:', err); return; } const procedureName = '"MY_SCHEMA"."MY_PROCEDURE"'; const parameters = [1, 'some_value']; // Example parameters client.call(procedureName, parameters, (err, result) => { if (err) { console.error('Error calling stored procedure:', err); } else { console.log('Stored procedure executed successfully:', result); } client.end(); }); }); ``` -------------------------------- ### Bulk Insert Multiple Rows using Prepared Statement in Node.js hdb Source: https://context7.com/sap/node-hdb/llms.txt Illustrates preparing an INSERT statement once and executing it with an array of parameter arrays to insert many rows efficiently. The example logs the affected rows for each insert and shows total insertion count before cleanup. ```javascript const client = require('hdb').createClient({ host: 'hostname', port: 30015, user: 'user', password: 'secret' }); client.connect(function) { if (err) return console.error(err); client.prepare('INSERT INTO NUMBERS VALUES (?, ?)', function(err, statement) { if (err) return console.error(err); // Pass array of parameter arrays for bulk insert const rows = [ [1, 'one'], [2, 'two'], [3, 'three'], [4, 'four'], [5, 'five'] ]; statement.exec(rows, function(err, affectedRows) { if (err) return console.error(err); console.log('Affected rows:', affectedRows); // Output: [1, 1, 1, 1, 1] console.log('Total inserted:', affectedRows.reduce((a, b) => a + b, 0)); // 5 statement.drop(); client.end(); }); }); }); ``` -------------------------------- ### Execute Query and Get Rows as Objects (JavaScript) Source: https://github.com/sap/node-hdb/blob/master/README.md Executes a SQL query and returns results as an array of objects, where property names correspond to column display names. This is the default behavior for single-row results. ```javascript var command = 'select top 1 * from t1'; client.exec(command, function(err, rows) { /* rows will be an array like this: [{ ID: 1, A: 't1.1.a', B: 't1.1.b' }] */ }); ``` -------------------------------- ### JWT Token Authentication with Node.js HDB Source: https://context7.com/sap/node-hdb/llms.txt This JavaScript example demonstrates connecting to an SAP HANA database using JWT token authentication via the hdb module. It requires the 'hdb' package and a valid JWT token. After connection, it logs user and session details, then ends the client; note that error handling is basic and assumes environment variables for host and port. ```javascript const hdb = require('hdb'); const client = hdb.createClient({ host: 'hostname', port: 30015 }); // Connect with JWT token client.connect({ token: 'eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1c2VyIn0...' }, function(err) { if (err) { return console.error('JWT authentication error:', err); } console.log('User:', client.get('user')); console.log('SessionCookie:', client.get('sessionCookie')); client.end(); }); ``` -------------------------------- ### Stream Query Results as Objects (JavaScript) Source: https://context7.com/sap/node-hdb/llms.txt This example demonstrates streaming query results as objects using the node-hdb library. It uses the execute method instead of exec to enable streaming, sets a fetch size to control memory usage, and iterates over the object stream to process each row. Error handling for the stream is also included. ```javascript const hdb = require('hdb'); const client = hdb.createClient({ host: 'hostname', port: 30015, user: 'user', password: 'secret' }); client.connect(function(err) { if (err) return console.error(err); // Use execute instead of exec for streaming client.execute('SELECT * FROM TABLES', function(err, resultSet) { if (err) return console.error(err); // Configure fetch size for streaming resultSet.setFetchSize(2048); // Create object stream const stream = resultSet.createObjectStream(); let count = 0; stream.on('data', function(row) { count++; console.log('Row:', row); // { SCHEMA_NAME: 'SYS', TABLE_NAME: 'DUMMY', ... } }); stream.on('error', function(err) { console.error('Stream error:', err); if (!resultSet.closed) resultSet.close(); }); stream.on('end', function() { console.log('Total rows:', count); if (!resultSet.closed) resultSet.close(); client.end(); }); }); }); ``` -------------------------------- ### Handle Datetime Types in Prepared Statements (JavaScript) Source: https://context7.com/sap/node-hdb/llms.txt Demonstrates how to insert various datetime types (TIME, DATE, TIMESTAMP, SECONDDATE) into SAP HANA using prepared statements with the node-hdb library. The input strings must adhere to the specific formats expected by node-hdb for each type. Ensure the 'hdb' module is installed. ```javascript const client = require('hdb').createClient({ host: 'hostname', port: 30015, user: 'user', password: 'secret' }); client.connect(function(err) { if (err) return console.error(err); client.prepare('INSERT INTO EVENTS VALUES (?, ?, ?, ?, ?)', function(err, statement) { if (err) return console.error(err); // Use exact format required by node-hdb statement.exec([ 1, '13:32:20', // TIME format '2016-04-14', // DATE format '2016-04-14T13:32:20.737', // TIMESTAMP format '2016-04-14T13:32:20' // SECONDDATE format ], function(err, affectedRows) { if (err) return console.error(err); console.log('Datetime values inserted:', affectedRows); statement.drop(); client.end(); }); }); }); ``` -------------------------------- ### Stream HANA Query Results as Arrays using Node.js Source: https://context7.com/sap/node-hdb/llms.txt This example shows how to execute a SQL query against the HANA database and stream the results as an array. It uses the `hdb` Node.js client to connect, execute a query, and then create an array stream from the result set. Error handling for the stream and client connection is included. The stream emits 'data' events for each row and an 'end' event when finished. ```javascript const hdb = require('hdb'); const client = hdb.createClient({ host: 'hostname', port: 30015, user: 'user', password: 'secret' }); client.connect(function(err) { if (err) return console.error(err); client.execute('SELECT SCHEMA_NAME, TABLE_NAME FROM TABLES', function(err, resultSet) { if (err) return console.error(err); // Create array stream const stream = resultSet.createArrayStream(); stream.on('data', function(row) { console.log('Row:', row); // ['SYS', 'DUMMY'] }); stream.on('end', function() { if (!resultSet.closed) resultSet.close(); client.end(); }); stream.on('error', function(err) { console.error('Stream error:', err); if (!resultSet.closed) resultSet.close(); }); }); }); ``` -------------------------------- ### Direct SQL DML Operations using Node.js HDB Source: https://context7.com/sap/node-hdb/llms.txt This JavaScript example performs DML operations (INSERT, UPDATE, DELETE) on SAP HANA with the hdb module. It depends on 'hdb' and an existing table; inputs are SQL strings, outputs are affected row counts. The code chains operations sequentially, logging results, but lacks error recovery beyond basic logging. ```javascript const client = require('hdb').createClient({ host: 'hostname', port: 30015, user: 'user', password: 'secret' }); client.connect(function(err) { if (err) return console.error(err); // Insert returns affected rows count client.exec("INSERT INTO NUMBERS VALUES (1, 'one')", function(err, affectedRows) { if (err) { return console.error('Insert error:', err); } console.log('Affected rows:', affectedRows); // 1 // Update client.exec("UPDATE NUMBERS SET B = 'ONE' WHERE A = 1", function(err, affectedRows) { console.log('Updated rows:', affectedRows); // 1 // Delete client.exec('DELETE FROM NUMBERS WHERE A = 1', function(err, affectedRows) { console.log('Deleted rows:', affectedRows); // 1 client.end(); }); }); }); }); ``` -------------------------------- ### Query with Nested Tables for JOINs in Node.js HDB Source: https://context7.com/sap/node-hdb/llms.txt This JavaScript example performs a JOIN query with nested table results using the hdb module's nestTables option. It depends on 'hdb' and tables T1/T2; input includes SQL and options object, output is nested row objects or error. Useful for complex joins, but requires tables to exist and assumes no NULL values in joins. ```javascript const client = require('hdb').createClient({ host: 'hostname', port: 30015, user: 'user', password: 'secret' }); client.connect(function(err) { if (err) return console.error(err); const sql = 'SELECT * FROM T1 JOIN T2 ON T1.ID = T2.ID'; const options = { nestTables: true }; client.exec(sql, options, function(err, rows) { if (err) return console.error(err); console.log(rows); // Output with nested table structure: // [ // { // T1: { ID: 1, A: 't1.1.a', B: 't1.1.b' }, // T2: { ID: 1, A: 't2.1.a', B: 't2.1.b' } // } // ] client.end(); }); }); ``` -------------------------------- ### Pipe HANA Query Results to JSON Stream using Node.js Source: https://context7.com/sap/node-hdb/llms.txt This example demonstrates piping query results from a HANA database directly to a JSON stringifier and then to standard output. It uses the `hdb` Node.js client to connect and execute a query, creating an array stream from the results. A JSON stringifier is then piped from the array stream, and the output is directed to `process.stdout`. This is useful for efficiently exporting query results in JSON format. ```javascript const hdb = require('hdb'); const client = hdb.createClient({ host: 'hostname', port: 30015, user: 'user', password: 'secret' }); client.connect(function(err) { if (err) return console.error(err); client.execute('SELECT TOP 50 SCHEMA_NAME, TABLE_NAME FROM TABLES', function(err, resultSet) { if (err) return console.error(err); const stream = resultSet.createArrayStream(); const stringifier = hdb.createJSONStringifier(); function finish(err) { stream.removeListener('error', finish); stream.removeListener('end', onend); stringifier.removeListener('finish', finish); if (err) console.error('Stream error:', err); client.end(); } function onend() { if (!resultSet.closed) { resultSet.close(); } } stream.on('error', finish); stream.on('end', onend); stringifier.on('finish', finish); // Pipe to stdout as JSON stream.pipe(stringifier).pipe(process.stdout); }); }); ``` -------------------------------- ### Chrome App Window Page (index.html) Source: https://github.com/sap/node-hdb/wiki/Develop-Chrome-Apps-for-SAP-HANA The main HTML file for the Chrome App window. It includes a textarea for SQL queries, a button to execute them, an area to display results, and links to the bundled 'hdb.js' and 'main.js' scripts. ```html My First SAP HANA Chrome App

    
    
    
  

```

--------------------------------

### Create HANA client with multiple hosts

Source: https://github.com/sap/node-hdb/blob/master/README.md

Initializes a SAP HANA client with multiple host options. The client connects to the first available host.

```JavaScript
var hdb    = require('hdb');
var client = hdb.createClient({
  hosts : [ { host: 'host1', port: 30015 }, { host: 'host2', port: 30015 } ],
  user     : 'user',
  password : 'secret'
});
```

--------------------------------

### Write LOB Data to HANA Database using Node.js

Source: https://context7.com/sap/node-hdb/llms.txt

This Node.js example demonstrates how to write Large Object (LOB) data into the HANA database. It uses the `hdb` client to connect and prepare an INSERT statement. A readable stream from a local file (e.g., an image) is then passed as a LOB parameter to the prepared statement's `exec` method. The example includes error handling and confirmation of the number of rows affected after the LOB insertion.

```javascript
const fs = require('fs');
const client = require('hdb').createClient({
  host: 'hostname',
  port: 30015,
  user: 'user',
  password: 'secret'
});

client.connect(function(err) {
  if (err) return console.error(err);

  client.prepare('INSERT INTO PHOTOS VALUES (?, ?, ?)', function(err, statement) {
    if (err) return console.error(err);

    // Pass readable stream or buffer as LOB parameter
    const imageStream = fs.createReadStream('/tmp/photo.jpg');

    statement.exec([1, 'vacation.jpg', imageStream], function(err, affectedRows) {
      if (err) return console.error(err);

      console.log('LOB inserted, rows affected:', affectedRows); // 1

      statement.drop();
      client.end();
    });
  });
});
```

--------------------------------

### Run Unit Tests for SAP Node-HDB

Source: https://github.com/sap/node-hdb/blob/master/README.md

Provides commands to run unit tests and acceptance tests for the _hdb_ module. Running acceptance tests requires a configured database connection, specified in config.json.

```bash
make test-unit
```

```bash
make test
```

--------------------------------

### Create HANA client with database connection details

Source: https://github.com/sap/node-hdb/blob/master/README.md

Initializes a SAP HANA client with host, port, database name, user, and password. Suitable for connecting to a tenant database.

```JavaScript
var hdb    = require('hdb');
var client = hdb.createClient({
  host         : 'hostname',
  port         : 30015,
  databaseName : 'DB1',
  user         : 'user',
  password     : 'secret'
});
```

--------------------------------

### Chrome App Background Script (background.js)

Source: https://github.com/sap/node-hdb/wiki/Develop-Chrome-Apps-for-SAP-HANA

Handles the launch event for the Chrome App. When the app is launched, it creates the main application window, specifying the HTML file to load and the window's initial dimensions.

```javascript
chrome.app.runtime.onLaunched.addListener(function() {
  chrome.app.window.create("index.html", {
    id: "mainWindow",
    bounds: {
      width: 640,
      height: 800
    }
  });
});
```

--------------------------------

### Calling Stored Procedures

Source: https://github.com/sap/node-hdb/blob/master/README.md

Demonstrates how to call stored procedures using prepared statements, including handling scalar parameters and multiple result sets.

```APIDOC
## POST /sap/node-hdb/call

### Description
Calls a stored procedure using a prepared statement, allowing for scalar parameters and retrieval of multiple result sets.

### Method
POST

### Endpoint
/sap/node-hdb/call

### Parameters
#### Path Parameters
- **procedure_name** (string) - Required - The name of the stored procedure to call.

#### Request Body
- **parameters** (object) - Required - An object containing scalar input parameters for the stored procedure.
- **resultSets** (array) - Optional - Specifies the expected result sets from the procedure.

### Request Example
```javascript
// Assuming 'client' is an instance of the SAP HANA Node.js client
// And 'PROC_DUMMY' is a stored procedure with signature: (in a int, in b int, out c int, out d DUMMY, out e TABLES)

client.prepare('call PROC_DUMMY (?, ?, ?, ?, ?)', function(err, statement){
  if (err) {
    return console.error('Prepare error:', err);
  }

  // Execute the stored procedure with scalar parameters and capture result sets
  statement.exec({
    A: 3, // Corresponds to the first input parameter 'a'
    B: 4  // Corresponds to the second input parameter 'b'
  }, function(err, parameters, dummyRows, tableRows) {
    if (err) {
      return console.error('Exec error:', err);
    }
    console.log('Parameters:', parameters); // Contains output parameters like 'c'
    console.log('Dummies:', dummyRows);     // Contains result set 'd'
    console.log('Tables:', tableRows);      // Contains result set 'e'
  });
});
```

### Response
#### Success Response (200)
- **parameters** (object) - An object containing the output scalar parameters from the stored procedure.
- **resultSets** (array) - An array where each element represents a result set returned by the stored procedure.

#### Response Example
```json
{
  "parameters": {
    "C": 7 // Example output parameter
  },
  "resultSets": [
    [
      // Rows for the first result set (e.g., from 'd')
    ],
    [
      // Rows for the second result set (e.g., from 'e')
    ]
  ]
}
```

**Note:** Default values for stored procedures are not supported.
```

--------------------------------

### Prepared Statements

Source: https://github.com/sap/node-hdb/blob/master/README.md

Manages prepared statements for efficient execution of queries multiple times. Includes preparing, executing, and dropping statements.

```APIDOC
## /sap/node-hdb/statement

### Description
Handles the preparation, execution, and dropping of prepared statements for efficient query execution.

### Method
POST (Prepare), PUT (Execute), DELETE (Drop)

### Endpoint
/sap/node-hdb/statement

### Parameters
#### Prepare Statement
- **sql** (string) - Required - The SQL statement to prepare.

#### Execute Statement
- **statementId** (string) - Required - The ID of the prepared statement to execute.
- **parameters** (array or object) - Optional - Positional or named parameters for the statement.

#### Drop Statement
- **statementId** (string) - Required - The ID of the prepared statement to drop.

### Request Example
```javascript
// Prepare a statement
client.prepare('select * from DUMMY where DUMMY = ?', function (err, statement) {
  if (err) {
    return console.error('Error:', err);
  }
  console.log('StatementId', statement.id);

  // Execute the statement with positional parameters
  statement.exec(['X'], function (err, rows) {
    if (err) {
      return console.error('Error:', err);
    }
    console.log('Rows:', rows);
  });

  // Execute the statement with named parameters (if applicable)
  // statement.exec({ PARAM_NAME: 'value' }, function(err, rows) { ... });

  // Drop the statement
  statement.drop(function(err) {
    if (err) {
      return console.error('Drop error:', err);
    }
    console.log('Statement dropped');
  });
});
```

### Response
#### Prepare Success (200)
- **statementId** (string) - The unique identifier for the prepared statement.

#### Execute Success (200)
- **rows** (array) - The result rows from the executed statement.

#### Drop Success (200)
- **message** (string) - Confirmation of statement drop.

#### Error Response (400, 500)
- **error** (string) - Description of the error.

```

--------------------------------

### Transaction Management with Commit (JavaScript)

Source: https://context7.com/sap/node-hdb/llms.txt

This example shows how to manage transactions with explicit commit and rollback using node-hdb. It disables auto-commit, executes several insert statements within a transaction, and then commits the transaction if no errors occur. Includes error handling and rollback.

```javascript
const async = require('async');
const client = require('hdb').createClient({
  host: 'hostname',
  port: 30015,
  user: 'user',
  password: 'secret'
});

client.connect(function(err) {
  if (err) return console.error(err);

  // Disable auto-commit
  client.setAutoCommit(false);

  async.series([
    client.exec.bind(client, "INSERT INTO NUMBERS VALUES (1, 'one')"),
    client.exec.bind(client, "INSERT INTO NUMBERS VALUES (2, 'two')"),
    client.exec.bind(client, "INSERT INTO NUMBERS VALUES (3, 'three')")
  ], function(err) {
    if (err) {
      // Rollback on error
      client.rollback(function(rollbackErr) {
        if (rollbackErr) {
          console.error('Rollback error:', rollbackErr);
        } else {
          console.log('Transaction rolled back');
        }
        client.setAutoCommit(true);
        client.end();
      });
    } else {
      // Commit on success
      client.commit(function(commitErr) {
        if (commitErr) {
          console.error('Commit error:', commitErr);
        } else {
          console.log('Transaction committed');
        }
        client.setAutoCommit(true);
        client.end();
      });
    }
  });
});
```

--------------------------------

### Connect to SAP HANA and Check Connection State (JavaScript)

Source: https://github.com/sap/node-hdb/blob/master/README.md

This snippet demonstrates initiating a connection to an SAP HANA database and logging the client's ready state after the connection attempt. It highlights the transition from 'new' to 'connected' upon successful authentication.

```javascript
client.connect(function (err) {
  if (err) {
    return console.error('Error:', err);
  }
  console.log(client.readyState); // connected
});
```

--------------------------------

### Create HANA client with instance number

Source: https://github.com/sap/node-hdb/blob/master/README.md

Initializes a SAP HANA client using an instance number instead of a port. Useful for connecting to the system database.

```JavaScript
var hdb    = require('hdb');
var client = hdb.createClient({
  host           : 'hostname',
  instanceNumber : '00',
  databaseName   : 'DB1',
  user           : 'user',
  password       : 'secret'
});
```

--------------------------------

### Prepare a SQL Statement (JavaScript)

Source: https://github.com/sap/node-hdb/blob/master/README.md

Prepares a SQL statement for repeated execution. The `prepare` function returns a statement object that can be reused, improving performance for frequent queries.

```javascript
client.prepare('select * from DUMMY where DUMMY = ?', function (err, statement){
  if (err) {
    return console.error('Error:', err);
  }
  // do something with the statement
  console.log('StatementId', statement.id);
});
```

--------------------------------

### Connect to SAP HANA and Execute a Query (JavaScript)

Source: https://github.com/sap/node-hdb/blob/master/README.md

This snippet demonstrates how to establish a connection to an SAP HANA database using the 'hdb' module, execute a simple SQL query ('select * from DUMMY'), and handle potential connection or execution errors. It also shows how to close the connection after the query is completed.

```javascript
var hdb    = require('hdb');
var client = hdb.createClient({
  host     : 'hostname',
  port     : 30015,
  user     : 'user',
  password : 'secret'
});
client.on('error', function (err) {
  console.error('Network connection error', err);
});
client.connect(function (err) {
  if (err) {
  	return console.error('Connect error', err);
  }
  client.exec('select * from DUMMY', function (err, rows) {
	client.end();
    if (err) {
      return console.error('Execute error:', err);
    }
    console.log('Results:', rows);
  });
});
```

--------------------------------

### Create Database Client and Connect in JavaScript

Source: https://context7.com/sap/node-hdb/llms.txt

Demonstrates how to create a client and connect to a SAP HANA database using node-hdb. Includes error handling and a simple query execution.

```JavaScript
const hdb = require('hdb');

// Create client with connection options
const client = hdb.createClient({
  host: 'hostname',
  port: 30015,
  user: 'user',
  password: 'secret'
});

// Register error handler for network errors
client.on('error', function(err) {
  console.error('Network connection error', err);
});

// Connect to database
client.connect(function(err) {
  if (err) {
    return console.error('Connect error', err);
  }
  console.log('Connected, state:', client.readyState); // 'connected'

  // Execute query
  client.exec('SELECT * FROM DUMMY', function(err, rows) {
    if (err) {
      return console.error('Execute error:', err);
    }
    console.log('Results:', rows);
    // Output: Results: [ { DUMMY: 'X' } ]

    client.end();
  });
});
```

--------------------------------

### X.509 Certificate Authentication in Node.js

Source: https://context7.com/sap/node-hdb/llms.txt

This JavaScript code illustrates X.509 certificate-based authentication for SAP HANA connections using the hdb module. It depends on the 'hdb' and 'fs' modules, requiring a PEM certificate file and optional password. The example connects and logs success, then ends; limitations include not handling encrypted keys without a password.

```javascript
const hdb = require('hdb');
const fs = require('fs');

const client = hdb.createClient({
  host: 'hostname',
  port: 30015,
  authenticationX509: fs.readFileSync('client-cert.pem'),
  authenticationX509Password: 'key-password' // for encrypted keys
});

client.connect(function(err) {
  if (err) {
    return console.error('X.509 authentication error:', err);
  }
  console.log('Authenticated with certificate');
  client.end();
});
```

--------------------------------

### Direct SQL Query Execution in Node.js HDB

Source: https://context7.com/sap/node-hdb/llms.txt

This JavaScript code executes a SELECT query on SAP HANA using the hdb module, returning an array of row objects. It requires 'hdb' and connection details; input is the query string, output is rows or error. The example logs the result, assuming an existing table with data, and has basic error handling.

```javascript
const client = require('hdb').createClient({
  host: 'hostname',
  port: 30015,
  user: 'user',
  password: 'secret'
});

client.connect(function(err) {
  if (err) return console.error(err);

  // Query returns array of row objects
  client.exec('SELECT A, B FROM NUMBERS ORDER BY A', function(err, rows) {
    if (err) {
      return console.error('Query error:', err);
    }

    console.log('Rows:', rows);
    // Output:
    // [
    //   { A: 1, B: 'one' },
    //   { A: 2, B: 'two' },
    //   { A: 3, B: 'three' }
    // ]

    client.end();
  });
});
```

--------------------------------

### Create SAP HANA Chrome App client connection script

Source: https://github.com/sap/node-hdb/wiki/Develop-Chrome-Apps-for-SAP-HANA

Establishes connection to SAP HANA database using node-hdb client library. Handles user authentication, SQL command execution via textarea input, and displays results as formatted JSON. Requires hdb module and valid SAP HANA credentials.

```javascript
window.onload = function () {
  var hdb = require('hdb');

  var client = hdb.createClient({
    host: 'hostname',
    port: 30015,
    user: 'username',
    password: 'secret'
  });

  var command = document.querySelector('textarea');
  var button = document.querySelector('button');

  function showMessage(msg) {
    result.textContent = msg;
  }

  function showError(err) {
    showMessage(err.message);
  }

  button.onclick = function execute(){
    if (client.readyState !== 'connected') {
       return showError(new Error('Not connected'));
    }
    client.exec(command.value, function done(err, rows) {
      if (err) {
        return showError(err);
      }
      var result = document.getElementById('result');
      result.textContent = JSON.stringify(rows, null, 2);
    });
  };

  client.connect(function (err) {
    if (err) {
      return showError(err);
    }
  });
};
```

--------------------------------

### Bundle node-hdb for Chrome App with Browserify

Source: https://github.com/sap/node-hdb/wiki/Develop-Chrome-Apps-for-SAP-HANA

Uses Browserify to create a single JavaScript bundle file named 'hdb.js' from the node-hdb library and the 'buffer' module. This bundle is intended for use within a Chrome App.

```bash
browserify -r buffer -r "./lib":hdb -o ./hdb.js
```

--------------------------------

### Chrome App Manifest (manifest.json)

Source: https://github.com/sap/node-hdb/wiki/Develop-Chrome-Apps-for-SAP-HANA

Defines the metadata and configuration for the Chrome App, including its name, version, icons, background script, and necessary permissions for TCP socket connections.

```json
{
  "manifest_version": 2,
  "name": "MyFirstHanaChromeApp",
  "short_name": "MyFirstHanaChromeApp",
  "description": "My First SAP HANA Chrome App",
  "version": "0.0.1",
  "icons": {
    "16": "assets/icon_16.png",
    "128": "assets/icon_128.png"
  },
  "app": {
    "background": {
      "scripts": ["background.js"]
    }
  },
  "sockets": {
    "tcp": {
      "connect": "*:*"
    }
  }
}
```

--------------------------------

### Enhance SAP HANA app with Dable table display

Source: https://github.com/sap/node-hdb/wiki/Develop-Chrome-Apps-for-SAP-HANA

Upgrades the main script to display query results as an interactive HTML table using the Dable library. Adds showResult function to process metadata and row data, switches from exec to execute method for ResultSet access, and integrates with Dable control for improved data visualization.

```javascript
window.onload = function () {
  var hdb = require('hdb');

  var client = hdb.createClient({
    host: 'hostname',
    port: 30015,
    user: 'username',
    password: 'secret'
  });

  var command = document.querySelector('textarea');
  var button = document.querySelector('button');

  function showMessage(msg) {
    result.textContent = msg;
  }

  function showError(err) {
    showMessage(err.message);
  }
  
  function showResult(metadata, rows) {
    var columns = metadata.map(function(column){
      return column.columnDisplayName;
    });
    var data = rows.map(function(row){
      return columns.map(function(column){
        return '' + row[column];
      });
    });
    var dable = new Dable();
    dable.SetDataAsRows(data);
    dable.SetColumnNames(columns);
    dable.BuildAll('result');
  }  

  button.onclick = function execute(){
    if (client.readyState !== 'connected') {
       return showError(new Error('Not connected'));
    }
    client.execute(command.value, function done(err, rs) {
      if (err) {
        return showError(err);
      }
      rs.fetch(function(err, rows){
        if (err) {
          return showError(err);
        }
        showResult(rs.metadata, rows);
      });
    });
  };
  
  client.connect(function (err) {
    if (err) {
      return showError(err);
    }
  });
};
```

--------------------------------

### Read Complete LOB into Buffer using Node.js

Source: https://context7.com/sap/node-hdb/llms.txt

This example shows how to read an entire Large Object (LOB) from the HANA database into a Node.js Buffer. After connecting and executing a query to select the LOB data, the `resultSet.fetch` method retrieves the row containing the LOB. The `lob.read()` method is then called, which asynchronously reads the complete LOB content into a buffer. The size and initial bytes of the buffer are logged to the console.

```javascript
const client = require('hdb').createClient({
  host: 'hostname',
  port: 30015,
  user: 'user',
  password: 'secret'
});

client.connect(function(err) {
  if (err) return console.error(err);

  client.execute('SELECT IMAGE_DATA FROM PHOTOS WHERE ID = 1', function(err, resultSet) {
    if (err) return console.error(err);

    // Fetch row with LOB
    resultSet.fetch(function(err, rows) {
      if (err) return console.error(err);

      const lob = rows[0].IMAGE_DATA;

      // Read entire LOB into buffer
      lob.read(function(err, buffer) {
        if (err) return console.error(err);

        console.log('LOB size:', buffer.length);
        console.log('First bytes:', buffer.slice(0, 16));

        resultSet.close();
        client.end();
      });
    });
  });
});
```

--------------------------------

### Chrome App Stylesheet (styles.css)

Source: https://github.com/sap/node-hdb/wiki/Develop-Chrome-Apps-for-SAP-HANA

Provides basic styling for the Chrome App's user interface, setting margins, padding, font styles, and defining the appearance and behavior of the results display area.

```css
body {
  margin: 10px;
  padding: 0;
  font-size: 14px;
  font-family: monospace;
}
#result {
  margin-top: 20px;
  min-height: 480px;
  max-height: 640px;
  overflow-y: auto;
  -webkit-user-select: text;
}
```

--------------------------------

### Execute a Prepared Statement with Named Parameters (JavaScript)

Source: https://github.com/sap/node-hdb/blob/master/README.md

Executes a prepared statement using an object of named parameters. This provides a more readable way to pass parameters compared to positional arrays.

```javascript
statement.exec({
  PARAM1: 'value1',
  PARAM2: 123
}, function (err, rows) {
  if (err) {
    return console.error('Error:', err);
  }
  console.log('Rows:', rows);
});
```