diff --git a/docs/README.md b/docs/README.md index b033ec6..00e31f6 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,317 +1,559 @@ -# DB2 for i Access APIs -[//]: # (TOC only works on BB) +# DB2 for i Access APIs - idb-connector + +[//]: # (TOC built in macro on BB makes table of contents) [TOC] - +___ # Introduction -The new DB2 add-on for Node.js is a JavaScript API set for DB2 database manipulation on IBM i. The add-on is shipped with Node.js and located in `/QOpenSys/QIBM/ProdData/OPS/Node4/os400/db2i/`. +- `idb-connector` provides connectivity to DB2 from Node.js. + +- `idb-connector` uses DB2 CLI API to access DB2 subsequently this module is only supported for `IBM i` systems. -It contains a new non-blocking driver db2ia.node and a deprecated blocking driver db2i.node in the bin directory, and their respective library file db2a.js and db2.js in the lib directory. For the usage of the old synchronized db2i add-on, please refer to the -[document](https://www.ibm.com/developerworks/community/wikis/home?lang=en#!/wiki/IBM%20i%20Technology%20Updates/page/DB2%20for%20i%20access%20APIs) +## Install -To use the DB2 add-on, you only need to require the db2a.js file in your source code. + Available on npm -**Note:** The new DB2 Add-on requires Node.js v4, please check the effective Node.js by command `node -v` first. +- `npm install idb-connector` +Build from source + +- `git clone https://bitbucket.org/litmis/nodejs-idb-connector.git` +- `cd nodejs-idb-connector` +- `npm install --build-from-source` +___ # Examples +[//]: # (On BB headers are prefixed by #markdown-header) +[//]: # (Also the title of the header are made lower case) +[//]: # (So to link to Async Exec header: #markdown-header-async-exec) +### Async Exec + -### Basic Query ```javascript -var db = require('/QOpenSys/QIBM/ProdData/OPS/Node4/os400/db2i/lib/db2a'); -var sql = "SELECT STATE,LSTNAM FROM QIWS.QCUSTCDT"; +const {dbconn, dbstmt} = require('idb-connector'); -var dbconn = new db.dbconn(); // Create a connection object. +let sql = 'SELECT * FROM QIWS.QCUSTCDT', + connection = new dbconn(); // Create a connection object. -dbconn.conn("*LOCAL"); // Connect to a database. +connection.conn('*LOCAL'); // Connect to a database. -var stmt = new db.dbstmt(dbconn); // Create a statement object of the connection. +let statement = new dbstmt(dbconn); // Create a statement object of the connection. -stmt.exec(sql, function(result) { +statement.exec(sql, (result, error) => { + if (error){ + throw error; + } + console.log('Result Set:\n', JSON.stringify(result)); - console.log("Result: %s", JSON.stringify(result)); + statement.close(); // Clean up the statement object. + connection.disconn(); // Disconnect from the database. + connection.close(); // Clean up the connection object. +}); - var fieldNum = stmt.numFields(); +``` +___ - console.log("There are %d fields in each row.", fieldNum); +### Sync Exec - console.log("Name | Length | Type | Precise | Scale | Null"); - for(var i = 0; i < fieldNum; i++) +```javascript - console.log("%s | %d | %d | %d | %d | %d", stmt.fieldName(i), stmt.fieldWidth(i), stmt.fieldType(i), stmt.fieldPrecise(i), stmt.fieldScale(i), stmt.fieldNullable(i)); +const {dbconn, dbstmt} = require('idb-connector'); - +let sql = 'SELECT STATE FROM QIWS.QCUSTCDT', + connection = new dbconn(); // Create a connection object. - stmt.close(); // Clean up the statement object. +connection.conn('*LOCAL'); // Connect to the database. - dbconn.disconn(); // Disconnect from the database. +let statement = new dbstmt(connection); // Create a statement object. - dbconn.close(); // Clean up the connection object. +result = statement.execSync(sql); +console.log('Result Set:\n', JSON.stringify(result)); +statement.close(); // Clean up the statement object. +connection.disconn(); // Disconnect from the database. +connection.close(); // Clean up the connection object. +``` +___ + +### Async Prepare Bind Execute + +Calling a Stored Procedure + +```javascript + +const idb = require('idb-connector'), + {dbconn, dbstmt, IN, OUT, CHAR, CLOB} = idb; + +let sql = 'call QXMLSERV.iPLUG512K(?,?,?,?)', + connection = new dbconn(), + ipc = '*NA', + ctl = '*here', + xmlIn ='system wrksbs', + xmlOut = '', + params = [[ipc, IN, CHAR], + [ctl, IN, CHAR], + [xmlIn, IN, CLOB], + [xmlOut, OUT, CLOB] + ]; + +connection.conn('*LOCAL'); +let statement = new dbstmt(connection); + +statement.prepare(sql, (error) => { + if (error){ + throw error; + } + statement.bindParam(params, (error) => { + if (error){ + throw error; + } + statement.execute((out, error) => { + if (error){ + throw error; + } + console.log('Output Params:\n', out); + statement.close(); + connection.disconn(); + connection.close(); + }); + }); }); ``` +___ + +### Sync Prepare Bind Execute + -### Stored Procedure ```javascript -var db = require('/QOpenSys/QIBM/ProdData/OPS/Node4/os400/db2i/lib/db2a'); -var sql = "call QXMLSERV.iPLUG512K(?,?,?,?)"; +const {dbconn, dbstmt, IN, OUT, CLOB, CHAR} = require('idb-connector'); -var dbconn = new db.dbconn(); +let sql = 'call QXMLSERV.iPLUG512K(?,?,?,?)', + connection = new dbconn(), + ipc = '*NA', + ctl = '*here', + xmlIn ='system wrksbs', + xmlOut = '', + params = [[ipc, IN, CHAR], + [ctl, IN, CHAR], + [xmlIn, IN, CLOB], + [xmlOut, OUT, CLOB] + ]; -dbconn.conn("*LOCAL"); +connection.conn('*LOCAL'); -var stmt = new db.dbstmt(dbconn); +let statement = new dbstmt(connection), -var ipc = "*NA"; +statement.prepareSync(sql); +statement.bindParamSync(params); -var ctl = "*here"; +let out = statement.executeSync(); -var xmlIn ="system 'wrkactjob'"; +console.log('Output Params:\n', JSON.stringify(out)); + +statement.close(); +connection.disconn(); +connection.close(); +``` +___ -var xmlOut = ""; +### Async Fetch -stmt.prepare(sql, function(){ +Asynchronously retrieve one row from the result set - stmt.bindParam([ +```javascript +const {dbconn, dbstmt} = require('idb-connector'); - [ipc, db.SQL_PARAM_INPUT, 1], +let connection = new dbconn(); - [ctl, db.SQL_PARAM_INPUT, 1], +connection.conn('*LOCAL'); - [xmlIn, db.SQL_PARAM_INPUT, 0], +let statement = new dbstmt(connection); - [xmlOut, db.SQL_PARAM_OUTPUT, 0], +statement.prepare('SELECT * FROM QIWS.QCUSTCDT', (error) => { + if (error){ + throw error; + } + statement.execute((error) => { + if (error){ + throw error; + } - ], function(){ + statement.fetch((row, rc) => { + if (rc instanceof Error){ + throw rc; + } + console.log('Row: \n', JSON.stringify(row)); - stmt.execute(function(out) { //out is an array of the output parameters. + statement.close(); + connection.disconn(); + connection.close(); + }); + }); +}); +``` +___ - for(var i=0; i { + if (error){ + throw error; + } + statement.execute((error) => { + if (error){ + throw error; + } + statement.fetchAll(function(result, error){ + if (error){ + throw error; + } + console.log('Result Set:\n', JSON.stringify(result)); + statement.close(); + connection.disconn(); + connection.close(); + }); + }); }); +``` +___ -console.log("Execute B."); +### Sync FetchAll -sqlB.exec(sql, function() { +Synchronously retrieve all rows from the result set - console.log("Execute B Done."); +```javascript - sqlB.close(); +const {dbconn, dbstmt} = require('idb-connector'); -}); +let connection = new dbconn(); + +connection.conn('*LOCAL'); + +let statement = new dbstmt(connection); -setTimeout(function(){ +statement.prepareSync("SELECT * FROM SCHEMA.MYTABLE"); +statement.executeSync(); - dbconn.disconn(); +let result = statement.fetchAllSync(); - dbconn.close(); +console.log('Result Set:\n', JSON.stringify(result)); -},1000); //Sleep for 1 second to wait for both queries done. +statement.close(); +connection.disconn(); +connection.close(); ``` -# API Documentation +# Class: dbconn +The dbconn class is used to create a connection object. + +Once the idb-connector is installed you can gain access with: + +`const {dbconn} = require('idb-connector');` + +use the new operator to instantiate it + +`let conn = new dbconn();` + +Once instantiated the methods documented below can be performed. + +Make sure to call `disconn` and `close` when finished. + +## Contructor: dbconn() + +**Description:** -# Class dbconn -The dbconn class represents a connection object. It can connect to a database, and disconnect from it. Please use the new operator to instantiate it and the delete function to clean up. +Allocates a new connection handle, ensure `conn` function is called to connect to the target database. +___ -## setConnAttr +## dbconn.setConnAttr(attribute, value) **Description:** -Set connection attributes. +Sets a connection attribute to a provided valid value. **Syntax:** -setConnAttr(int Attribute, int/string Value) +setConnAttr(attribute, value) **Parameters** -- **Attribute:** is the connection attribute to set. Refer to [this table](https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_71/cli/rzadpfnsconx.htm%23rzadpfnsconx__tbcono) for more details. +- **attribute:** `number(integer)` is the connection attribute to set. +- **value:** `string | number(integer)` the value to set the specified attribute to. + +**Returns:** -- **Value:** Depending on the Attribute, this can be an integer value, or a character string. +`boolean(true)` upon success otherwise an error is thrown. **DB2 CLI API:** SQLSetConnectAttr **Valid Scope:** Before connecting to a database. -**Comments:** The Auto Commit feature is automatically enabled. +**Comments:** + +Auto Commit attribute is automatically enabled. + +Refer to this [table](https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_71/cli/rzadpfnsconx.htm%23rzadpfnsconx__tbcono) for more details. -## getConnAttr +___ + +## dbconn.getConnAttr(attribute) **Description:** -Returns the current settings for the specified connection option +Returns the current settings for the specified connection attribute. **Syntax:** -getConnAttr(int Attribute) +getConnAttr(attribute) **Parameters:** -- **Attribute:** is the connection attribute to set. Refer to [this table](https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_71/cli/rzadpfngcona.htm) for more details. -**Returns:** It returns the attribute option in the format of an integer or a string depending on the attribute type. +- **attribute:** `number(integer)` the connection attribute to set. + +**Returns:** + +`string | number(integer)` depending on the attribute. **DB2 CLI API:** SQLGetConnectAttr **Valid Scope:** After instantiated the connection object. +**Comments:** -## conn +Refer to this [table](https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_71/cli/rzadpfngcona.htm) for more details. +___ + +## dbconn.conn(database) **Description:** -Establishes a connection to the target database. The application can optionally supply a target SQL database, an authorization name, and an authentication string. +Establishes a connection to the target database. + +**NOTE** '*LOCAL' can be provided as the `database` when connecting to a local database, allowing `user` & `password` to be optionally passed. + **Syntax 1:** -conn(string Database) +conn(database) **Syntax 2:** -conn(string Database, function Callback) +conn(database, callback) **Syntax 3:** -conn(string Database, string User, string Password) +conn(database, user, password) **Syntax 4:** -conn(string Database, string User, string Password, function Callback) +conn(database, user, password, callback) **Parameters:** -- **Database:** is the name or alias name of the database. -- **User:** is the authorization name (user identifier). -- **Password:** is the authentication string (password). -- **Callback:** is a callback function running after the connection established. -**DB2 CLI API:** SQLConnect +- **database:** `string` is the name or alias name of the database. + +- **user:** `string` is the authorization name (user identifier). + +- **password:** `string` is the authentication string (password). + +- **callback:** `function` is a callback function running after the `conn` is complete + -**Valid Scope:** Before calling the exec() or prepare() function. +**DB2 CLI API:** SQLConnect +**Valid Scope:** Before calling the dbstmt.exec() or dbstmt.prepare() function. +___ -## disconn +## dbconn.disconn() **Description:** -Ends the connection associated with the database connection handle. After calling this function, either call conn() to connect to another database, or delete the connection object. + +Ends the connection associated with the database connection handle. + +After calling this function, either call `conn` to connect to another database or `close`. **Syntax:** + disconn() **DB2 CLI API:** SQLDisconnect + **Valid Scope:** After calling the conn() function. +**Returns:** + +`boolean(true)` upon success otherwise an error is thrown. -## close +___ + +## dbconn.close() **Description:** -Frees the connection object. All DB2 for i resources associated with the connection object are freed. disconn() must be called before calling this function. + +Frees all DB2 for i resources associated with the connection object. + +`disconn()` must be called before calling this function. **Syntax:** + close() **DB2 CLI API:** SQLFreeConnect + **Valid Scope:** After calling the disconn() function. +**Returns:** + +`boolean(true)` upon success otherwise an error is thrown. -## debug +___ + +## dbconn.debug(flag) **Description:** -Print more detailed debugging information during execution. +Enables or disables verbose output to the console. **Syntax:** -debug(boolean OnOff) +debug(flag) **Parameters:** -- **OnOff:** Default value is false. If it is true, the program will print more detailed information. +- **flag:** `boolean` to turn debug mode on or off. Default value is `false`. + +**Returns:** + +`boolean` the current state of the debug flag otherwise an error is thrown. + +**Valid Scope:** Entire life cycle. -**Valid Scope:** All the life cycle. +___ -## validStmt +## dbconn.validStmt(sql) **Description:** -Checks if the SQL string is valid and interprets vendor escape clauses. If the original SQL string that is passed by the application contains vendor escape clause sequences, DB2 for i CLI returns the transformed SQL string that is seen by the data source (with vendor escape clauses either converted or discarded as appropriate). +Checks if the SQL string is valid and interprets vendor escape clauses. + +If the original SQL string that is passed by the application contains vendor escape clause sequences, + +DB2 for i CLI returns the transformed SQL string that is seen by the data source (with vendor escape clauses either converted or discarded as appropriate). **Syntax:** -validStmt(string Statement) +validStmt(sql) **Parameters:** -- **Statement:** is a SQL string that needs to be checked and escaped. +- **sql:** `string` that needs to be checked and escaped. -**Returns:** It returns an integer value indicating the scale of the specified column in the result set. +**Returns:** + +`string` the transformed sql string upon success, otherwise an error is thrown. **DB2 CLI API:** SQLNativeSql -**Valid Scope:** After calling conn() function +**Valid Scope:** After calling `conn` function +___ # Class dbstmt -The dbstmt class represents a SQL statement object along with its query result set. The construct function accepts an input parameter of a connection object. One connection object can derive many statement objects. Please use the new operator to instantiate it and the delete function to clean up. +Once the idb-connector is installed you can gain access with: + +`const {dbstmt} = require('idb-connector');` + +A connected `dbconn` object is required to create a new `dbstmt` object from. + +```javascript +const {dbconn, dbstmt} = require('idb-connector'); + +let connection = new dbconn(); + +connection.conn('*LOCAL'); + +let statement = new dbstmt(dbconn); + +``` +Once instantiated the methods documented below can be performed. + +Make sure to call `close` when finished with the statement object. + +## Constructor: dbstmt(connection) + +**Parameters:** + +- **dbconn:** `dbconn object` the connection object to create the statement from. -## setStmtAttr +- Ensure `connection` has connected to the database first with `conn` function. +___ + +## dbstmt.setStmtAttr(attribute, value) **Description:** -Set an attribute of a specific statement handle. To set an option for all statement handles associated with a connection handle, the application can call setConnAttr(). +Set an attribute of a specific statement handle. + +To set an option for all statement handles associated with a connection handle `setConnAttr` can be used. **Syntax:** -setStmtAttr(int Attribute, int/string Value) +setStmtAttr(attribute, value) **Parameters:** -- **Attribute:** is the statement attribute to set. Refer to [this table](https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_71/cli/rzadpfnsstma.htm%23rzadpfnsstma__tbstmto) for more details. +- **attribute:** `number(integer)` is the statement attribute to set. + +- **value:** `string | number (integer)` the value to set the specified attribute to. -- **Value:** Depending on the Attribute, this can be an integer value, or a character string. **DB2 CLI API:** SQLSetStmtAttr **Valid Scope:** After allocating the statement handler. +___ -## getStmtAttr +## dbstmt.getStmtAttr **Description:** @@ -323,102 +565,116 @@ getStmtAttr(int Attribute) **Parameters** -- **Attribute:** is the connection attribute to set. Refer to [this table](https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_71/cli/rzadpfngstma.htm) for more details. +- **attribute:** is the connection attribute to set. Refer to this [table](https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_71/cli/rzadpfngstma.htm) for more details. + +**Returns:** -**Returns:** It returns the attribute option in the format of an integer or a string depending on the attribute type. +`string | number (integer)` depending on the attribute. **DB2 CLI API:** SQLGetStmtAttr **Valid Scope:** After allocating the statement handler. +___ -## exec +## dbstmt.exec(sql, callback) **Description:** -Directly runs the specified SQL statement. The statement can only be processed once. Also, the connected database server must be able to prepare the statement. This is a non-blocking API. +Asynchronously runs the specified SQL statement. -**Syntax:** +**NOTE** use the `execute` function to call stored procedures -exec(string SQL, function Callback(JsonObj)) +**Syntax:** -exec(string SQL, function Callback(JsonObj, Error)) +exec(sql,callback) **Parameters** -- **SQL:** is the SQL statement string. +- **sql:** `string` is the sql statement to execute. -- **Callback(JsonObj [, Error]):** is a callback function to process the result set of the SQL statement for callers. JsonObj is the result set of the SELECT SQL statement. It is in the JSON format. Error is the error message when error happens. It's a optional parameter. +- **callback(resultSet, error):** `function` to process after `exec` is complete. + - **resultSet:** `array` of `objects` each object represents a row of data. + - If an error occurred or there is no `resultSet` it is set to `null`. + - **error:** `Error object` when `execSync` is unsuccessful. Otherwise `error` is set to `null`. **DB2 CLI API:** SQLExecDirect -**Valid Scope:** After calling the conn() function. +**Valid Scope:** After calling the `conn` function. + +**Example:** [Here](#markdown-header-async-exec) +___ -## execSync +## dbstmt.execSync(sql [, callback]) **Description:** -The synchronized version of exec(). This is a blocking API. +The synchronous blocking version of `exec`. **Syntax 1:** -exec(string SQL) +execSync(sql) + +**Parameters** + +- **sql:** `string` is the sql statement to execute. + +**Returns:** + +- **resultSet:** `array` of `objects` each object represents a row of data. +- If an error occurred or there is no `resultSet` , `null` will be returned. **Syntax 2:** -exec(string SQL, function Callback(JsonObj)) +execSync(sql, callback(resultSet, error)) **Parameters** -- **SQL:** is the SQL statement string. +- **sql:** `string` is the sql statement to execute. -- **Callback(JsonObj):** is a callback function to process the result set of the SQL statement for callers. JsonObj is the result set of the SELECT SQL statement. It is in the JSON format. -**Comments:** +- **callback(resultSet, error):** `function` to process after `execSync` is complete. + - **resultSet:** `array` of `objects` each object represents a row of data. If an error occurred or there is no `resultSet` it is set to `null`. + + - **error:** `Error object` when `execSync` is unsuccessful. Otherwise `error` is set to `null`. -- If the SQL statement is UPDATE, INSERT, MERGE, SELECT from INSERT, or DELETE statement, nothing will be returned and it is recommended to use Syntax 1. And user can issue the numRows() function to get the affected row number. +**Comments:** -- It is recommended to invoke the numFields(), numRows(), fieldName() and other result set related functions in this callback function. Because they rely on the temporal result set in memory. After running execSync() the result set will be destroyed and cleaned up. +- It is recommended to invoke the `numFields`, `numRows`, `fieldName` and other result set related functions in this callback function, because they rely on the temporal result set in memory. +- After running `execSync` the result set will be destroyed and cleaned up. **DB2 CLI API:** SQLExecDirect **Valid Scope:** After calling the conn() function. -Example: -```javascript -var db = require('/QOpenSys/QIBM/ProdData/OPS/Node4/os400/db2i/lib/db2a'); -var sql = "SELECT STATE FROM QIWS.QCUSTCDT"; -var dbconn = new db.dbconn(); // Create a connection object. -dbconn.conn("*LOCAL"); // Connect to a database. -var stmt = new db.dbstmt(dbconn); // Create a statement object of the connection. -stmt.execSync(sql, function(result) { - console.log("Result: %s", JSON.stringify(result)); -}); -stmt.close(); -conn.disconn(); -conn.close(); -``` +**Example:** [Here](#markdown-header-sync-exec) -## prepare +___ + +## dbstmt.prepare(sql, callback) **Description:** -Associates an SQL statement with the input statement handle and sends the statement to the DBMS to be prepared. The application can reference this prepared statement by passing the statement handle to other functions. +Asynchronously associates an SQL statement with the input statement handle and sends the statement to the DBMS to be prepared. -**Syntax:** -prepare(string SQL, function Callback()) +**Syntax:** -prepare(string SQL, function Callback(Error)) +prepare(sql, callback) **Parameters** -- **SQL:** is the SQL statement string. +- **sql:** is the SQL statement string. + +- **callback(error)**: `function` to process after `prepare` is complete. + - **error**: `Error object` when `prepare` is unsuccessful. Otherwise `error` is set to `null`. -- **Callback([Error]):** is a callback function. Error is an optional parameter of the callback function. It is the error message when error happens. +**Comments:** -**Comments:** If the statement handler has been used with a SELECT statement, closeCursor() must be called to close the cursor, before calling prepare() again. +If the statement handler has been used with a SELECT statement, + +`closeCursor` must be called to close the cursor, before calling `prepare` again. **DB2 CLI API:** SQLPrepare @@ -428,197 +684,246 @@ prepare(string SQL, function Callback(Error)) - Before calling the execute() or bindParam() function. +**Example:** [Here](#markdown-header-async-prepare-bind-execute) +___ -## prepareSync +## dbstmt.prepareSync(sql [, callback]) **Description:** -The synchronized version of prepare(). This is a blocking API. +Synchronous version of `prepare`. + **Syntax 1:** -prepareSync(string SQL) +prepareSync(sql) + +**Parameters:** + +- **sql:** `string` the sql statement to prepare. + +**Returns:** + +`void` no return type, if an error occurred it will be thrown. **Syntax 2:** -prepareSync(string SQL, function Callback()) +prepareSync(sql, callback) **Parameters:** -- **SQL:** is the SQL statement string. +- **sql:** `string` the sql statement to prepare. + +- **callback(error)**: `function` to process after `prepareSync` is complete. + - **error**: `Error object` when `prepareSync` is unsuccessful. Otherwise `error` is set to `null`. -- **Callback():** is a callback function. +**Comments:** -**Comments:** If the statement handler has been used with a SELECT statement, closeCursor() must be called to close the cursor, before calling prepareSync() again. +If the statement handler has been used with a SELECT statement +`closeCursor` must be called first before calling `prepareSync` again. **DB2 CLI API:** SQLPrepare **Valid Scope:** -- After calling the conn() function. +- After calling the `conn` function. -- Before calling the executeSync() or bindParamSync() function. +- Before calling the `executeSync` or `bindParamSync` function. -**Example:** -```javascript -var db = require('/QOpenSys/QIBM/ProdData/OPS/Node4/os400/db2i/lib/db2a'); -var sql = "SELECT STATE FROM QIWS.QCUSTCDT"; -var dbconn = new db.dbconn(); // Create a connection object. -dbconn.conn("*LOCAL"); // Connect to a database. -var stmt = new db.dbstmt(dbconn); // Create a statement object of the connection. -stmt.prepareSync("call QXMLSERV.iPLUG512K(?,?,?,?)"); -stmt.bindParamSync([ - ["*NA", db.SQL_PARAM_INPUT, 1], - ["*here", db.SQL_PARAM_INPUT, 1], - ["", db.SQL_PARAM_INPUT, 0], - ["", db.SQL_PARAM_OUTPUT, 0], -]); -stmt.executeSync(function callback(out) { //out is an array of the output parameters. - console.log("Result: %s", JSON.stringify(out)); -}); -stmt.close(); -conn.disconn(); -conn.close(); -``` +**Example:** [Here](#markdown-header-sync-prepare-bind-execute) +___ -## bindParam +## dbstmt.bindParam(params, callback) **Description:** -Associate (bind) parameter markers in an SQL statement to application variables. Data is transferred from the application to the Database Management System (DBMS) when execute() is called. Data conversion might occur when the data is transferred. +Asynchronously associate (bind) parameter markers in an SQL statement to application variables. -This function must also be used to bind application storage to a parameter of a stored procedure where the parameter can be input, output. +Data is transferred from the application to the Database Management System (DBMS) when `execute` function is called. -This is a non-blocking API. +Data conversion might occur when the data is transferred. -**Syntax:** +This function must also be used to bind to a parameter of a stored procedure where the parameter can be: input, output, or both -bindParam(array ParamList, function Callback()) -bindParam(array ParamList, function Callback(Error)) +**Syntax:** -**Parameters** +bindParam(params, callback) -- **ParamList:** is a javascript array representing the binding parameter list. Each parameter has three attributes which are also represented as an array. The three attributes are Value, In/Out Type and Indicator. Value can be an integer value or a string. In/Out Type is an integer. If Value is an input value, please set it to 0. Otherwise, set it to 1. Indicator is an integer flag to tell the function how to process some special types of parameters. Different type of Value requires corresponding Indicator. If the parameter is CLOB string, set it to 0, if it is a NTS string, set it to 1, if it is an integer, set it to 2. +**Parameters:** -- **Callback([Error]):** is a callback function. Error is an optional parameter. It is the error message when error happens. +- **params**: `array` representing the binding parameter list. Each parameter element will also be an Array with 3 values `[value, io, indicator]`. + + - `value` is the parameter to bind. + - `io` specifies whether the parameter is for input, output, or both. + - `io` can be: + - SQL_PARAM_INPUT + - SQL_PARAM_OUTPUT + - SQL_PARAM_INPUT_OUTPUT + - Shorthand equivleants are: + - IN + - OUT + - INOUT + - `indicator` specifies how to process the parameter. For example to process a string as a CLOB set the indicator to CLOB. + - `indcator` can be: + - CHAR + - INT + - NUMERIC + - BINARY + - BLOB + - CLOB + - BOOLEAN + - NULL + + These values are constants which are attached to object returned when you `const idb = require('idb-connector')`. + + You can access the constants like: `idb.IN`. + +- **callback(error):** `function` to process after `bindParam` is complete. + - **error:** `Error object` when `bindParam` is unsuccessful. Otherwise `error` is set to `null`. **DB2 CLI API:** SQLBindParameter -**Valid Scope:** In the callback function of the prepare() function. +**Valid Scope:** In the callback function of the `prepare` function. +**Example:** [Here](#markdown-header-async-prepare-bind-execute) -## bindParamSync +___ + +## dbstmt.bindParamSync(params [, callback]) **Description:** -The synchronized version of bindParam(). -This is a blocking API. +Synchronous version of `bindParam`. **Syntax 1:** -bindParamSync(array ParamList) +bindParamSync(params) -**Syntax 2:** +**Parmeters:** -bindParamSync(array ParamList, function Callback()) +- **params**: as described in [bindParam](#dbstmt.bindParam()) -**Parameters** +**Returns:** -- **ParamList**: is a javascript array representing the binding parameter list. Each parameter has three attributes which are also represented as an array. The three attributes are Value, In/Out Type and Indicator. Value can be an integer value or a string. In/Out Type is an integer. If Value is an input value, please set it to 0. Otherwise, set it to 1. Indicator is an integer flag to tell the function how to process some special types of parameters. Different type of Value requires corresponding Indicator. If the parameter is CLOB string, set it to 0, if it is a NTS string, set it to 1, if it is an integer, set it to 2. +`void` no return type, if an error occurred it will be thrown. -- **Callback():** is a callback function. +**Syntax 2:** -**DB2 CLI API:** SQLBindParameter +bindParamSync(params, callback) -**Valid Scope:** +**Parameters** -- After calling the prepareSync() function. -- Before calling the executeSync() function. +- **params**: as described in [bindParam()](#dbstmt.bindParam()) -**Example:** See the example of prepareSync(). +- **callback(error)**: `function` to process after `bindParamSync` is complete. + - **error**: `Error object` when `bindParamSync` is unsuccessful. Otherwise `error` is set to `null`. -## execute -**Description:** +**Example:** [Here](#markdown-header-sync-prepare-bind-execute) -Runs a statement that was successfully prepared using prepare() once or multiple times. The statement is processed with the current values of any application variables that were bound to parameters markers by bindParam(). +**DB2 CLI API:** SQLBindParameter -This is a non-blocking API. +**Valid Scope:** -**Syntax 1:** +- After calling the `prepareSync` function. +- Before calling the `executeSync` function. -execute(function Callback()) +___ -**Syntax 2:** +## dbstmt.execute(callback) -execute(function Callback(Out)) +**Description:** -**Syntax 3:** +Asynchronously Runs a statement that was successfully prepared using `prepare`. + +The statement is processed with the current values of any application variables that were bound to parameters markers by `bindParam`. + +**Syntax:** -execute(function Callback(Error)) +execute(callback(outputParams, error)) **Parameters** -- **Callback(Out):** is a callback function. If the output contains parameters of the parameter markers, Out is a list of the output parameters in the java script array format. Otherwise, the callback function takes no output Parameters and is only for fetching the result set. Error is the error message when error happens. +- **callback(outputParams, error):** `function` to process after `execute` is complete. + - **outputParams**: an `array` of an output parameters. If an error occurred or no output parameters are available `outputParams` is set to `null`. + + - **error**: `Error object` when `execute` is unsuccessful. Otherwise `error` is set to `null`. **DB2 CLI API:** SQLExecute -**Valid Scope:** In the callback function of the prepare() or bindParam() function. +**Valid Scope:** In the callback function of the `prepare` or `bindParam` function. + +**Example:** [Here](#markdown-header-async-prepare-bind-execute) +___ -## executeSync +## dbstmt.executeSync([callback]) **Description:** -The synchronized version of execute(). -This is a blocking API. +The synchronized version of `execute`. **Syntax 1:** executeSync() +**Returns:** + - **outputParams**: an `array` of output parameters. If an error occured it is thrown. +- If no output parameters are available `null` is returned. + **Syntax 2:** -executeSync(function Callback(OutParamList)) +executeSync(callback) **Parameters:** -- **Callback(OutParamList):** is a callback function to process the output parameters of the parameter markers. OutParamList is a list of the output parameters. It is in the java script array format. +- **callback(outputParams, error):** `function` to process after `executeSync` is complete. + - **outputParams**: `array` of an output parameters. If an error occured or no output parameters are available `outputParams` is set to `null`. + + - **error**: `Error object` when `executeSync` is unsuccessful. Otherwise `error` is set to `null`. + -**Comments:** If the statement also return a result set, user can issue the fetch() function to retrieve the data row by row. +**Comments:** + +If the statement also returns a result set, user can issue the `fetch` function to retrieve the data row by row. **DB2 CLI API:** SQLExecute **Valid Scope:** After calling the prepareSync() function. -**Example:** See the example of prepareSync(). - +**Example:** [Here](#markdown-header-sync-prepare-bind-execute) +___ -## nextResult +## dbstmt.nextResult() **Description:** -Determines whether there is more information available on the statement handle that has been associated with a stored procedure that is returning result sets. +Determines whether there is more information available on the statement handle that has been associated with a stored procedure that is returning multiple result sets. **Syntax:** nextResult() -**Comments:** After completely processing the first result set, the application can call nextResult() to determine if another result set is available. If the current result set has unfetched rows, nextResult() discards them by closing the cursor. +**Comments:** + +After completely processing the first result set, the application can call `nextResult` to determine if another result set is available. + +If the current result set has unfetched rows, `nextResult` discards them by closing the cursor. **DB2 CLI API:** SQLMoreResults **Valid Scope:** After calling the execute() function. +___ -## commit +## dbstmt.commit() **Description:** -Commit all changes to the database that have been made on the connection since connect time or the previous call to commit(). +Commit all changes to the database that have been made on the connection since connect time or the previous call to `commit`. **Syntax:** @@ -628,12 +933,17 @@ commit() **Valid Scope:** After calling the execute() or exec() function. +**Comments:** + +Auto commit is enabled by default. -## rollback +___ + +## dbstmt.rollback() **Description:** -Rollback all changes to the database that have been made on the connection since connect time or the previous call to commit(). +Rollback all changes to the database that have been made on the connection since connect time or the previous call to `commit`. **Syntax:** @@ -641,14 +951,21 @@ rollback() **DB2 CLI API:** SQLTransact -**Valid Scope:** After calling the execute() or exec() function. +**Valid Scope:** After calling the `execute` or `exec` function. +___ -## closeCursor +## dbstmt.closeCursor() **Description:** -Calling closeCursor() closes any cursor associated with the dbstmt object and discards any pending results. If no open cursor is associated with the dbstmt object, the function has no effect. If the dbstmt object references a stored procedure that has multiple result sets, the closeCursor() closes only the current result set. Any additional result sets remain open and usable.If you want to reuse the dbstmt object, please call closeCursor() before calling exec() or prepare()for another SQL statement. Otherwise, you just need to call delete to completely remove it. +Calling `closeCursor` closes any cursor associated with the dbstmt object and discards any pending results. + +If no open cursor is associated with the dbstmt object, the function has no effect. + +If the dbstmt object references a stored procedure that has multiple result sets, `closeCursor` closes only the current result set. Any additional result sets remain open and usable. + +If you want to reuse the dbstmt object, please call `closeCursor` before calling `exec` or `prepare` for another SQL statement. **Syntax:** @@ -658,12 +975,15 @@ closeCursor() **Valid Scope:** After calling the fetch() or fetchAll() function. - -## close +___ + +## dbstmt.close() **Description:** -DB2 for i resources associated with the statement object are freed. The open cursor, if any, is closed and all pending results are discarded. +DB2 for i resources associated with the statement object are freed. + +The open cursor, if any, is closed and all pending results are discarded. **Syntax:** @@ -673,40 +993,35 @@ close() **Valid Scope:** After executing an SQL statement and processing the results. - -## fetch - -**Description:** - -Advances the cursor to the next row of the result set, and retrieves any bound columns. Or positions the cursor based on the requested orientation and then retrieves any bound columns. +___ -This is a non-blocking API. - -**Syntax 1:** +## dbstmt.fetch([orient,] [offset,] callback) -fetch() +**Description:** -**Syntax 2:** +Asynchronously advances the cursor to the next row of the result set, and retrieves any bound columns. -fetch(function Callback(Row)) +Or positions the cursor based on the requested orientation and then retrieves any bound columns. -fetch(function Callback(Row, Error)) -**Syntax 3:** +**Syntax 1:** -fetch(int Orient, int Offset) +fetch(callback) -**Syntax 4:** +**Parameters** -fetch(int Orient, int Offset, function Callback(Row)) +- **callback(row, error):** `function` to process after `fetchS` is complete. + - **row**: `object` representing a row of data. If an error occured or there is nothing to fetch `row` is set to `null`. + + - **error**: `Error object` when `fetch` is unsuccessful. Otherwise `error` is set to the return code from `SQLFETCH`. When error = `SQL_NO_DATA_FOUND` the end of the result set has been reached. -fetch(int Orient, int Offset, function Callback(Row, Error)) +**Syntax 2:** -**Parameters:** +fetch(orient, offset, callback) -- **Callback(Row, Error):** is a callback function to process the fetched row. Row is the fetched row represented in a key-value java script array. Error is the error message when error happens. +**Parameters** -- **Orient:** sets the fetch orientation. The valid values are below: +- **orient:** `number(integer)` sets the fetch orientation. The valid values are below: - `SQL_FETCH_ABSOLUTE`: Move to the row specified by the Offset argument. @@ -726,46 +1041,33 @@ fetch(int Orient, int Offset, function Callback(Row, Error)) - Zero, do not move the cursor. -- **Offset:** is the row offset for relative positioning. +- **Offset:** `number(integer)` is the row offset for relative positioning. **Note:** To use orientation `SQL_FETCH_RELATIVE` with `Offset`, the cursor must be **dynamic**. -```javascript -stmt.setStmtAttr(db.SQL_ATTR_CURSOR_TYPE, db.SQL_CURSOR_DYNAMIC); -``` + + +`stmt.setStmtAttr(idb.SQL_ATTR_CURSOR_TYPE, idb.SQL_CURSOR_DYNAMIC);` + +- **callback(row, rc):** `function` to process after `fetch` is complete. + - **row**: `object` representing a row of data. If an error occured or there is nothing to fetch `row` is set to `null`. + + - **rc**: `Error object` when `fetch` is unsuccessful. Otherwise `rc` is set to the return code from `SQLFETCH`. When error = `SQL_NO_DATA` the end of the result set has been reached. + + **DB2 CLI API:** SQLFetch or SQLFetchScroll **Valid Scope:** When the result set is available. -**Example:** -```javascript -stmt.prepare("SELECT * FROM ...", function(){ - stmt.execute(function(){ - function asyncFetch(){ - stmt.fetch(function callback(row, rc){ - assert(rc != db.SQL_ERROR); - console.log(row); - if(rc != db.SQL_NO_DATA_FOUND) - asyncFetch(); - else { // the last row. - stmt.close(); - conn.disconn(); - conn.close(); - } - }); - } - asyncFetch(); - }); -}); -``` +**Example:** [Here](#markdown-header-async-fetch) -## fetchSync +___ -**Description:** +## dbstmt.fetchSync() -The synchronized version of fetch(). +**Description:** -This is a blocking API. +Synchronous version of `fetch`. **Syntax 1:** @@ -785,275 +1087,267 @@ fetchSync(int Orient, int Offset, function Callback(Row)) **Parameters** -- **Callback(Row):** is a callback function to process the fetched row. Row is the fetched row represented in a key-value java script array. - -- **Orient:** sets the fetch orientation. The valid values are below: - - - `SQL_FETCH_ABSOLUTE`: Move to the row specified by the Offset argument. - - - `SQL_FETCH_FIRST`: Move to the first row of the result set. - - - `SQL_FETCH_LAST`: Move to the last row of the result set. - - - `SQL_FETCH_NEXT`: Move to the row following the current cursor position. - - - `SQL_FETCH_PRIOR`: Move to the row preceding the current cursor position. - - - `SQL_FETCH_RELATIVE` If Offset is: - - - Positive, advance the cursor that number of rows. - - - Negative, back up the cursor that number of rows. - - - Zero, do not move the cursor. +- **orient:** as described in `fetch` above -- **Offset:** is the row offset for relative positioning. +- **offset:** as described in `fetch` above. -**Note:** To use orientation `SQL_FETCH_RELATIVE` with `Offset`, the cursor must be **dynamic**. -```javascript -stmt.setStmtAttr(db.SQL_ATTR_CURSOR_TYPE, db.SQL_CURSOR_DYNAMIC); -``` +- **callback(row, error):** `function` to process after `fetchSync` is complete. + - **row**: `object` representing a row of data. If an error occured or there is nothing to fetch `row` is set to `null`. + + - **error**: `Error object` when `fetch` is unsuccessful. Otherwise `error` is set to the return code from `SQLFETCH`. When error = `SQL_NO_DATA` the end of the result set has been reached. **DB2 CLI API:** SQLFetch or SQLFetchScroll **Valid Scope:** When the result set is available. +**Example:** [Here](#markdown-header-sync-fetch) -## fetchAll +## dbstmt.fetchAll(callback) **Description:** -Fetch all the rows of data from the result set in one time. - -This is a non-blocking API. +Asynchronously retrieves all the rows from the result set if available. **Syntax:** -fetchAll(function Callback(Row)) - -fetchAll(function Callback(Row, Error)) +fetchAll(callback) **Parameters** -- **Callback(Row[ , Error]):** is a callback function to process the fetched row. Row is the fetched row represented in a key-value java script array. Error is an optional parameter. It is the error message when error happens. +- **callback(resultSet, error):** `function` to process after `fetchAll` is complete. + - **resultSet**: an `array` of `objects` each object represents a row of data. + - If an error occured or there is no `resultSet` it is set to `null` + + - **error**: `Error object` when `fetchAll` is unsuccessful. Otherwise `error` is set to `null`. **DB2 CLI API:** SQLFetch **Valid Scope:** When the result set is available. -**Example:** -```javascript -stmt.prepare("SELECT * FROM ...", function(){ - stmt.execute(function(){ - stmt.fetchAll(function(result){ - console.log(result); - stmt.close(); - }); - }); -}); -``` - +**Example:** [Here](#markdown-header-async-fetchAll) +___ -## fetchAllSync +## dbstmt.fetchAllSync([callback]) **Description:** -The synchronized version of fetchAll(). +Synchronous version of `fetchAll`. + +**Syntax 1:** +fetchAllSync() -This is a blocking API. +**Returns** -**Syntax:** + - **resultSet**: an `array` of `objects` each object represents a row of data. + - If there is no result set `null` is returned. + - If an error occurs it will be thrown. -fetchAllSync(function Callback(Row)) +**Syntax 2:** + +fetchAllSync(callback) **Parameters** -- **Callback(Row):** is a callback function to process the fetched row. Row is the fetched row represented in a key-value java script array. +- **callback(resultSet, error):** `function` to process after `fetchAll` is complete. + - **resultSet**: an `array` of `objects` each object represents a row of data. + - If an error occured `resultSet` is set to `null` + + - **error**: `Error object` when `fetchAllSync` is unsuccessful. Otherwise `error` is set to `null`. + +**Example:** [Here](#markdown-header-sync-fetchAll) + **DB2 CLI API:** SQLFetch **Valid Scope:** When the result set is available. -**Example:** -```javascript -stmt.prepareSync("SELECT * FROM ..."); -stmt.executeSync(); -stmt.fetchAllSync(function callback(rs){ - console.log(rs); -}); -stmt.close(); -``` - +___ -## numFields +## dbstmt.numFields() **Description:** -Returns the number of fields contained in a result set. +Retrieves number of fields contained in the result set if available. **Syntax:** numFields() -**Returns:** It returns an integer value indicating number of fields in the result set. +**Returns:** + +`number(integer)` indicating number of fields in the result set. **DB2 CLI API:** SQLNumResultCols **Valid Scope:** When the result set is available. +___ - -## numRows +## dbstmt.numRows() **Description:** -Returns the number of rows in a table affected by an UPDATE, INSERT, MERGE, SELECT from INSERT, or DELETE statement processed against the table. +Returns the number of rows in a table affected by the last executed sql statement if available. **Syntax:** numRows() -**Returns:** It returns an integer value indicating number of rows affected by the operation. +**Returns:** + +`number(integer)` indicating number of rows affected by the operation. **DB2 CLI API:** SQLRowCount **Valid Scope:** When the result set is available. +___ - -## fieldType +## dbstmt.fieldType(index) **Description:** -Returns the data type of the indicated column in a result set. +If a valid index is provided, `fieldType` returns the data type of the indicated field. **Syntax:** -fieldType(int Index) +fieldType(index) **Parameters:** -- **Index:** is the column number in a result set, ordered sequentially left to right, starting at 0. +- **index:** `number(integer)` the column number in a result set, ordered sequentially left to right, starting at 0. -**Returns:** It returns an integer value indicating the data type of the specified column in the result set. +**Returns:** + +`number(integer)` indicating the data type of the specified column in the result set. **DB2 CLI API:** SQLColAttribute **Valid Scope:** When the result set is available. +___ - -## fieldWidth +## dbstmt.fieldWidth(index) **Description:** -Returns the width of the indicated column in a result set. +If a valid index is provided, `fieldWidth` returns the field width of the indicated field. **Syntax:** -fieldWidth(int Index) +fieldWidth(index) **Parameters** -- **Index:** is the column number in a result set, ordered sequentially left to right, starting at 0. +- **index:** `number(integer)` the column number in a result set, ordered sequentially left to right, starting at 0. -**Returns:** It returns an integer value indicating the width of the specified column in the result set. +**Returns:** + +`number(integer)` indicating the width of the specified column in the result set. **DB2 CLI API:** SQLColAttribute **Valid Scope:** When the result set is available. +___ - -## fieldNullable +## dbstmt.fieldNullable(index) **Description:** -Returns if the indicated column in a result set can be NULL. +If a valid index is provided, fieldNullable returns true | false indicating if field can be set to null. **Syntax:** -fieldNullable(int Index) +fieldNullable(index) **Parameters** -- **Index:** is the column number in a result set, ordered sequentially left to right, starting at 0. +- **index:** `number(integer)` the column number in a result set, ordered sequentially left to right, starting at 0. -**Returns:** It returns an Boolean value indicating if the indicated column in a result set can be NULL. +**Returns:** + +`boolean` indicating if the column can be set to NULL. **DB2 CLI API:** SQLColAttribute **Valid Scope:** When the result set is available. - -## fieldName +___ +## dbstmt.fieldName(index) **Description:** -Returns the name of the indicated column in a result set. +If a valid index is provided, `fieldName` returns the name of the indicated field. **Syntax:** -fieldName(int Index) +fieldName(index) **Parameters** -- **Index:** is the column number in a result set, ordered sequentially left to right, starting at 0. +- **index:** `number(integer)` the column number in a result set, ordered sequentially left to right, starting at 0. -**Returns:** It returns an string value indicating the name of the specified column in the result set. +**Returns:** + +`string` indicating the name of the specified column in the result set. **DB2 CLI API:** SQLColAttribute **Valid Scope:** When the result set is available. +___ - -## fieldPrecise +## dbstmt.fieldPrecise(index) **Description:** -Returns the precision of the indicated column in a result set. +If a valid index is provided, `fieldPrecise` returns the precision of the indicated field. **Syntax:** -fieldPrecise(int Index) +fieldPrecise(index) **Parameters** -- **Index:** is the column number in a result set, ordered sequentially left to right, starting at 0. +- **index:** `number(integer)` the column number in a result set, ordered sequentially left to right, starting at 0. -**Returns:** It returns an integer value indicating the precision of the specified column in the result set. +**Returns:** + +`number(integer)` indicating the precision of the specified column in the result set. **DB2 CLI API:** SQLColAttribute **Valid Scope:** When the result set is available. +___ - -## fieldScale +## dbstmt.fieldScale(index) **Description:** -Returns the scale of the indicated column in a result set. +If a valid index is provided, `fieldScale` returns the scale of the indicated column. **Syntax:** -fieldScale(int Index) +fieldScale(index) **Parameters:** -- **Index:** is the column number in a result set, ordered sequentially left to right, starting at 0. +- **index:** `number(integer)` the column number in a result set, ordered sequentially left to right, starting at 0. -**Returns:** It returns an integer value indicating the scale of the specified column in the result set. +**Returns:** + +`number(integer)` indicating the scale of the specified column in the result set. **DB2 CLI API:** SQLColAttribute **Valid Scope:** When the result set is available. +___ - -## stmtError +## dbstmt.stmtError(callback) **Description:** Returns the diagnostic information associated with the most recently called function for a particular statement, connection, or environment handler. **Syntax:** -stmtError(int hType, int Recno, function Callback(ErrMsg)) +stmtError(hType, recno, callback) **Parameters** -- **hType:** indicates the handler type of diagnostic information. It can be following values: +- **hType:** `number(integer)` indicates the handler type of diagnostic information. It can be following values: - `SQL_HANDLE_ENV`: Retrieve the environment diagnostic information @@ -1061,15 +1355,16 @@ stmtError(int hType, int Recno, function Callback(ErrMsg)) - `SQL_HANDLE_STMT`: Retrieve the statement diagnostic information -- **Recno:** indicates which error should be retrieved. The first error record is number 1. +- **recno:** `number(integer)` indicates which error should be retrieved. The first error record is number 1. -- **Callback(ErrMsg):** is a callback function to process the retrieved error message. ErrMsg is the retrieved error message. The information consists of a standardized SQLSTATE, the error code, and a text message. +- **callback(errmsg):** is a callback function to process the retrieved error message. + - **errmsg:** `string` consists of a standardized SQLSTATE, the error code, and a text message. **DB2 CLI API:** SQLGetDiagRec **Valid Scope:** After calling conn() function -### ***Diagnostics*** +***Diagnostics*** | Error Code | Meaning|