Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

idb-pconnector

Package Overview
Dependencies
Maintainers
4
Versions
21
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

idb-pconnector - npm Package Compare versions

Comparing version 0.0.8 to 0.1.0

test/connectionTest.js

48

docs/dbPool.md

@@ -13,3 +13,3 @@ # Class: DBPoolConnection

### DBPoolConnection.newConnection()
### DBPoolConnection.newConnection()

@@ -19,3 +19,3 @@ Instantiates a new Connection instance

### DBPoolConnection.newStatement()
### DBPoolConnection.newStatement()

@@ -27,3 +27,3 @@ Instantiates a new Statement instance for the Connection if one is not set and returns it.

### DBPoolConnection.getStatement()
### DBPoolConnection.getStatement()

@@ -34,3 +34,3 @@ Constructor to instantiate a new instance of a DBPoolConnection class given the `poolIndex` and `config`

### DBPoolConnection.close()
### DBPoolConnection.close()

@@ -40,3 +40,3 @@ Closes the connection

### DBPoolConnection.detach(retire)
### DBPoolConnection.detach(retire)

@@ -51,3 +51,3 @@ Creates a new statement

### DBPoolConnection.isAvailable()
### DBPoolConnection.isAvailable()

@@ -58,3 +58,3 @@ Constructor to instantiate a new instance of a DBPoolConnection class given the `poolIndex` and `config`

### DBPoolConnection.setAvailable(availability)
### DBPoolConnection.setAvailable(availability)

@@ -65,3 +65,3 @@ Constructor to instantiate a new instance of a DBPoolConnection class given the `poolIndex` and `config`

**availability**: `boolean`, true or false to set the availablilty flag of the connection.
**availability**: `boolean`, true or false to set the availability flag of the connection.

@@ -79,3 +79,3 @@ - - -

**database**: `object`, Object includes the `url`(databse name) defaults to *LOCAL, `username`, and `password`. `username` and `password` assumed blank if not specified with non-local URL.
**database**: `object`, Object includes the `url`(database name) defaults to *LOCAL, `username`, and `password`. `username` and `password` assumed blank if not specified with non-local URL.

@@ -85,3 +85,3 @@ **config**: `object` , Object includes the `incrementSize` and `debug`. IncrementSize sets the desired size of the DBPool. If none specified, defaults to 8 connections. Setting debug = true will display message logs.

### DBPool.createConnection(index)
### DBPool.createConnection(index)

@@ -96,3 +96,3 @@ Instantiates a new instance of DBPoolConnection with an `index` and appends it to the pool.

### DBPool.detachAll()
### DBPool.detachAll()

@@ -102,11 +102,11 @@ Frees all connections in the pool (Sets "Available" back to true for all)

**Returns**: `boolean`, - true if all were detached succesfully
**Returns**: `boolean`, - true if all were detached successfully
### DBPool.retireAll()
### DBPool.retireAll()
Retires (Removes) all connections from being used again
**Returns**: `boolean`, - true if all were retired succesfully
**Returns**: `boolean`, - true if all were retired successfully
### DBPool.detach(connection)
### DBPool.detach(connection)

@@ -122,3 +122,3 @@ Frees a connection (Returns the connection "Available" back to true)

### DBPool.retire(connection)
### DBPool.retire(connection)

@@ -132,3 +132,3 @@ Retires a connection from being used and removes it from the pool

### DBPool.attach()
### DBPool.attach()

@@ -139,3 +139,3 @@ Finds and returns the first available Connection.

### DBPool.log(message)
### DBPool.log(message)

@@ -149,3 +149,3 @@ Internal function used to log debug information.

### DBPool.runSql(sql)
### DBPool.runSql(sql)

@@ -156,8 +156,8 @@ Shorthand to exec a statement , just provide the sql to run.

**sql**: `string`, the sql statment to execute.
**sql**: `string`, the sql statement to execute.
**Returns**: `array`, - if the SQL returns a result set it is returned as an array of objects.
else if no result set is available null is returned. caller should check if null is returned.
else if no result set is available null is returned. caller should check if null is returned.
### DBPool.prepareExecute(sql, params)
### DBPool.prepareExecute(sql, params)

@@ -176,3 +176,3 @@ Shortcut to prepare ,bind, and execute. Just provide the sql and the params as an array.

### DBPool.formatParams(params)
### DBPool.formatParams(params)

@@ -185,3 +185,3 @@ Internal helper function to format params and set Param Indicator & Bind Type

**Returns**: `array`, - an array of bounded params properly formated to use.
**Returns**: `array`, - an array of bounded params properly formatted to use.

@@ -188,0 +188,0 @@

# Class: Connection
## Connection.connect(dbname)
## Connection.connect(dbname)

@@ -14,9 +14,9 @@ Establishes a Connection to the database.

## Connection.getStatement()
## Connection.getStatement()
returns a Statment Object intialized to the current dbConn Conection.
returns a Statement Object initialized to the current dbConn Connection.
**Returns**: `object`, - a new Statement intialized with the current dbconn.
**Returns**: `object`, - a new Statement initialized with the current dbconn.
## Connection.close()
## Connection.close()

@@ -27,9 +27,9 @@ closes the Connection to the DB and frees the connection object.

## Connection.disconn()
## Connection.disconn()
disconnects an exsisting connection to the datbase.
disconnects an existing connection to the database.
**Returns**: `Promise`, - Promise object represents the disconnect of the Connection.
## Connection.debug(choice)
## Connection.debug(choice)

@@ -44,51 +44,17 @@ prints more detailed info if choice = true. Turned off by setting choice = false.

## Connection.getConnAttr(attribute)
## Connection.getConnAttr(attribute)
if connection attribute exsits should return type String or Int depending on the attribute type
if connection attribute exists should return type String or Int depending on the attribute type
**Parameters**
**attribute**: `number`, if connection attribute exsits should return type String or Int depending on the attribute type
**attribute**: `number`, if connection attribute exists should return type String or Int depending on the attribute type
**Returns**: `Promise`, - Promise object represents the the current settings for the specified connection attribute.
**Example**:
```js
Available Set & Get Connection Attributes:
SQL_ATTR_2ND_LEVEL_TEXT
SQL_ATTR_AUTOCOMMIT
SQL_ATTR_CONCURRENT_ACCESS_RESOLUTION
SQL_ATTR_CONN_SORT_SEQUENCE
SQL_ATTR_COMMIT
SQL_ATTR_DBC_DEFAULT_LIB
SQL_ATTR_DECFLOAT_ROUNDING_MODE
SQL_ATTR_DECIMAL_SEP
SQL_ATTR_EXTENDED_COL_INFO
SQL_ATTR_EXTENDED_INDICATORS
SQL_ATTR_FREE_LOCATORS
SQL_ATTR_HEX_LITERALS
SQL_ATTR_INFO_ACCTSTR
SQL_ATTR_INFO_APPLNAME
SQL_ATTR_INFO_PROGRAMID
SQL_ATTR_INFO_USERID
SQL_ATTR_INFO_WRKSTNNAME
SQL_ATTR_MAX_PRECISION
SQL_ATTR_MAX_SCALE
SQL_ATTR_MIN_DIVIDE_SCALE
SQL_ATTR_OLD_MTADTA_BEHAVIOR
SQL_ATTR_NULLT_ARRAY_RESULTS
SQL_ATTR_NULLT_OUTPUT_PARMS
SQL_ATTR_QUERY_OPTIMIZE_GOAL
SQL_ATTR_SAVEPOINT_NAME
SQL_ATTR_TIME_FMT
SQL_ATTR_TIME_SEP
SQL_ATTR_TIMESTAMP_PREC
SQL_ATTR_TXN_EXTERNAL
SQL_ATTR_TXN_INFO
SQL_ATTR_UCS2
```
[Further Documentaion ON Connection Attributes](https://www.ibm.com/support/knowledgecenter/en/ssw\_ibm\_i_73/cli/rzadpfnsconx.htm)
## Connection.setConnAttr(attribute, value)
**Link**:
[Further Documentation ON Connection Attributes](https://www.ibm.com/support/knowledgecenter/en/ssw\_ibm\_i_73/cli/rzadpfnsconx.htm)
## Connection.setConnAttr(attribute, value)
Sets the ConnAttr , Attrubte should be INT.
Sets the ConnAttr , Attribute should be INT.

@@ -103,5 +69,5 @@ **Parameters**

### Connection.validStmt(sql)
### Connection.validStmt(sql)
Checks if the given SQL is valid and nterprets vendor escape clauses.
Checks if the given SQL is valid and interprets vendor escape clauses.

@@ -118,3 +84,3 @@ **Parameters**

## Statement.bindParam(params)
## Statement.bindParam(params)

@@ -131,18 +97,19 @@ associates parameter markers in an SQL statement to app variables.

```js
bStmt.bindParam([
[2099, dba.SQL_PARAM_INPUT, dba.SQL_BIND_NUMERIC],
['Node.Js', dba.SQL_PARAM_INPUT,dba.SQL_BIND_CHAR]
statement.bindParam([
[2099, dba.SQL_PARAM_INPUT, dba.SQL_BIND_NUMERIC],
['Node.Js', dba.SQL_PARAM_INPUT,dba.SQL_BIND_CHAR]
]);
IN/OUT TYPE CAN BE:
1.SQL_PARAM_INPUT
2.SQL_PARAM_OUTPUT
3.SQL_PARAM_INPUT_OUTPUT
INDICATORS CAN BE:
1. SQL_BIND_CLOB
2. SQL_BIND_CHAR
3. SQL_BIND_NUMERIC
4. SQL_BIND_NULL_DATA
IN/OUT TYPE CAN BE:
1.SQL_PARAM_INPUT
2.SQL_PARAM_OUTPUT
3.SQL_PARAM_INPUT_OUTPUT
INDICATORS CAN BE:
1. SQL_BIND_CLOB
2. SQL_BIND_CHAR
3. SQL_BIND_NUMERIC
4. SQL_BIND_NULL_DATA
```
## Statement.bind(params)
## Statement.bind(params)

@@ -156,3 +123,3 @@ Shorthand for bindParam

## Statement.close()
## Statement.close()

@@ -163,3 +130,3 @@ Ends and frees the statement object.

## Statement.closeCursor()
## Statement.closeCursor()

@@ -170,3 +137,3 @@ closes the cursor associated with the dbstmt object and discards any pending results.

## Statement.commit()
## Statement.commit()

@@ -177,3 +144,3 @@ adds all changes to the database that have been made on the connection since connect time.

## Statement.exec(sqlString)
## Statement.exec(sqlString)

@@ -187,5 +154,5 @@ performs action of given SQL String. The exec() method does not work with stored procedure calls use execute() instead.

**Returns**: , the result set as an array.
**Returns**: `Promise`, - Promise object represents the result set from the exection of exec().
**Returns**: `Promise`, - Promise object represents the result set from the execution of exec().
## Statement.execute()
## Statement.execute()

@@ -200,88 +167,54 @@ Runs a statement that was successfully prepared using prepare().

- Calling a stored Procedure that returns a result set with execute() & displaying the result set.
try{
var dba = require("idb-pconnector");
try{
let db = require('idb-pconnector');
// note that that calling the new Statement() without the DbConn as a parameter
// creates a new connection automatically and uses that for the Statment.
var dbStmt = new dba.Statement();
var sql = "call QIWS.sampleProc";
await dbStmt.prepare(sql);
await dbStmt.execute();
var res = await dbStmt.fetchAll();
console.log(`Result is\n: ${JSON.stringify(res)}`);
// note that that calling the new Statement() without the DbConn as a parameter
// creates a new connection implicitly and uses that for the Statement.
let statement = new db.Statement(),
sql = 'CALL MYSCHEMA.SAMPLEPROC';
await statement.prepare(sql);
await statement.execute();
let result = await statement.fetchAll();
console.log(`Result is\n: ${JSON.stringify(result)}`);
}
catch(error){
console.log(error.stack);
}
catch(dbError){
console.log(dbError.stack);
},- Insert Example With Prepare , Binding Parameter , and Execution
try {
var dba = require("idb-pconnector");
// note that that calling the new Statement() without the DbConn as a parameter
// creates a new connection automatically and uses that for the Statment.
var dbStmt = new dba.Statement();
await dbStmt.prepare("INSERT INTO AMUSSE.TABLE1 VALUES (?,?)");
await dbStmt.bind([ [2018,dba.SQL_PARAM_INPUT,dba.SQL_BIND_NUMERIC], [ ,dba.PARM_TYPE_INPUT, dba.SQL_BIND_NULL_DATA ] ]);
await dbStmt.execute();
var res = await dbStmt.exec("SELECT * FROM AMUSSE.TABLE1");
console.log("Select results: "+JSON.stringify(res));
}
catch (dbError) {
console.log("Error is " + dbError);
console.log(error.stack);
}
```
**Example**:
```js
- Calling a stored Procedure that returns a result set with execute() & displaying the result set.
try{
var dba = require("idb-pconnector");
- Insert Example With Prepare , Binding Parameter , and Execution
try {
let db = require('idb-pconnector');
// note that that calling the new Statement() without the DbConn as a parameter
// creates a new connection implicitly and uses that for the Statement.
let statement = new db.Statement();
await statement.prepare('INSERT INTO MYSCHEMA.MYTABLE VALUES (?,?)');
await statement.bind([ [2018,db.SQL_PARAM_INPUT,db.SQL_BIND_NUMERIC], [null ,db.PARM_TYPE_INPUT, dba.SQL_BIND_NULL_DATA ] ]);
await dbStmt.execute();
// note that that calling the new Statement() without the DbConn as a parameter
// creates a new connection automatically and uses that for the Statment.
var dbStmt = new dba.Statement();
var sql = "call QIWS.sampleProc";
await dbStmt.prepare(sql);
await dbStmt.execute();
var res = await dbStmt.fetchAll();
console.log(`Result is\n: ${JSON.stringify(res)}`);
}
catch(dbError){
console.log(dbError.stack);
},- Insert Example With Prepare , Binding Parameter , and Execution
try {
var dba = require("idb-pconnector");
// note that that calling the new Statement() without the DbConn as a parameter
// creates a new connection automatically and uses that for the Statment.
var dbStmt = new dba.Statement();
await dbStmt.prepare("INSERT INTO AMUSSE.TABLE1 VALUES (?,?)");
await dbStmt.bind([ [2018,dba.SQL_PARAM_INPUT,dba.SQL_BIND_NUMERIC], [ ,dba.PARM_TYPE_INPUT, dba.SQL_BIND_NULL_DATA ] ]);
await dbStmt.execute();
var res = await dbStmt.exec("SELECT * FROM AMUSSE.TABLE1");
console.log("Select results: "+JSON.stringify(res));
}
catch (dbError) {
console.log("Error is " + dbError);
console.log(error.stack);
}
let result = await dbStmt.exec('SELECT * FROM MYSCHEMA.MYTABLE');
console.log(`Select results: \nJSON.stringify(result)`);
}
catch (error) {
console.log(error.stack);
}
```
## Statement.fetch()
## Statement.fetch()
if a result exsits , retrieves a row from the result set
if a result exists , retrieves a row from the result set
**Returns**: `Promise`, - Promise object represents the row that was retrieved from the execution of fetch().
**Returns**: `Promise | null`, - Promise object represents the row that was retrieved from the execution of fetch(). If there is no data to be fetched null will be returned indicating the end of the result set.
## Statement.fetchAll()
## Statement.fetchAll()
if a result set exsits , retrieves all the rows of data from the result set.
if a result set exists , retrieves all the rows of data from the result set.
**Returns**: `Promise`, - Promise object represents the the an array containing the result that was retrieved from the execution of fetchAll().
## Statement.fieldName(index)
## Statement.fieldName(index)

@@ -292,7 +225,7 @@ requires an int index parameter. If a valid index is provided, returns the name of the indicated field.

**index**: `number`, the postion of the field within the table. It is 0 based.
**index**: `number`, the position of the field within the table. It is 0 based.
**Returns**: `Promise`, - Promise object represents the the String that was retrieved from the execution of fieldName().
## Statement.fieldNullable(index)
## Statement.fieldNullable(index)

@@ -303,7 +236,7 @@ requires an int index parameter. If a valid index is provided, returns t/f if the indicated field can be Null

**index**: `number`, the postion of the field within the table. It is 0 based.
**index**: `number`, the position of the field within the table. It is 0 based.
**Returns**: `Promise`, - Promise object represents the the boolean that was retrieved from the execution of fieldNullable().
## Statement.fieldPrecise(index)
## Statement.fieldPrecise(index)

@@ -314,7 +247,7 @@ requires an int index parameter. If a valid index is provided, returns the precision of the indicated field

**index**: `number`, the postion of the field within the table. It is 0 based.
**index**: `number`, the position of the field within the table. It is 0 based.
**Returns**: `Promise`, - Promise object represents the the Number that was retrieved from the execution of fieldPrecisie().
## Statement.fieldScale(index)
## Statement.fieldScale(index)

@@ -325,7 +258,7 @@ requires an int index parameter. If a valid index is provided, returns the scale of the indicated column

**index**: `number`, the postion of the field within the table. It is 0 based.
**index**: `number`, the position of the field within the table. It is 0 based.
**Returns**: `Promise`, - Promise object represents the the Number that was retrieved from the execution of fieldScale().
## Statement.fieldType(index)
## Statement.fieldType(index)

@@ -336,7 +269,7 @@ requires an int index parameter. If a valid index is provided, returns the data type of the indicated field

**index**: `number`, the postion of the field within the table. It is 0 based.
**index**: `number`, the position of the field within the table. It is 0 based.
**Returns**: `Promise`, - Promise object represents the the Number that was retrieved from the execution of fieldType().
## Statement.fieldWidth(index)
## Statement.fieldWidth(index)

@@ -347,9 +280,9 @@ requires an int index parameter. If a valid index is provided, returns the field width of the indicated field

**index**: `number`, the postion of the field within the table. It is 0 based.
**index**: `number`, the position of the field within the table. It is 0 based.
**Returns**: `Promise`, - Promise object represents the the Number that was retrieved from the execution of fieldWidth().
## Statement.getStmtAttr(attribute)
## Statement.getStmtAttr(attribute)
If a valid Statment attribute is provided , returns the current settings for the specified Statement attribute.
If a valid Statement attribute is provided , returns the current settings for the specified Statement attribute.
Refer to the list below for valid Statement Attributes.

@@ -363,27 +296,5 @@

**Example**:
```js
Available Set & Get Statement Attributes
SQL_ATTR_APP_PARAM_DESC
SQL_ATTR_APP_ROW_DESC
SQL_ATTR_BIND_TYPE
SQL_ATTR_CURSOR_HOLD
SQL_ATTR_CURSOR_SCROLLABLE
SQL_ATTR_CURSOR_SENSITIVITY
SQL_ATTR_CURSOR_TYPE
SQL_ATTR_EXTENDED_COL_INFO
SQL_ATTR_FOR_FETCH_ONLY
SQL_ATTR_FULL_OPEN
SQL_ATTR_NUMBER_RESULTSET_ROWS_PTR
SQL_ATTR_PARAM_BIND_TYPE
SQL_ATTR_PARAM_STATUS_PTR
SQL_ATTR_PARAMS_PROCESSED_PTR
SQL_ATTR_PARAMSET_SIZE
SQL_ATTR_ROW_BIND_TYPE
SQL_ATTR_ROW_STATUS_PTR
SQL_ATTR_ROWS_FETCHED_PTR
SQL_ATTR_ROWSET_SIZE
```
**Link**:
[Further Documentaion On Statement Attributes](https://www.ibm.com/support/knowledgecenter/en/ssw_ibm_i_73/cli/rzadpfnsstma.htm)
## Statement.nextResult()
## Statement.nextResult()

@@ -394,3 +305,3 @@ Determines whether there is more information available on the statement

## Statement.numFields()
## Statement.numFields()

@@ -401,9 +312,9 @@ if a result is available , retrieves number of fields contained in result.

## Statement.numRows()
## Statement.numRows()
if a query was performed ,retrieves number of rows that were effected by a query
if a query was performed ,retrieves number of rows that were affected by a query
**Returns**: `Promise`, - Promise object represents the Number returned from the execution of numRows().
## Statement.prepare(sqlString)
## Statement.prepare(sqlString)

@@ -420,6 +331,6 @@ If valid SQL is provided . prepares SQL and sends it to the DBMS, if the input SQL Statement cannot be prepared error is thrown.

```js
- view the examples located at the excute() method.
- view the examples located at the execute() method.
```
## Statement.rollback()
## Statement.rollback()

@@ -429,9 +340,9 @@ Reverts changes to the database that have been made on the connection since connect time or the previous call to commit().

## Statement.setStmtAttr(attribute, value)
## Statement.setStmtAttr(attribute, value)
if a valid attribute and value is providied , sets StmtAttr indicate Attrubte. Refer to the example @getStmtAttr for a list of valid Statement Attributes.
if a valid attribute and value is provided , sets StmtAttr indicate Attribute. Refer to the example @getStmtAttr for a list of valid Statement Attributes.
**Parameters**
**attribute**: `number`, musbt be an int INT.
**attribute**: `number`, must be an int INT.

@@ -442,3 +353,3 @@ **value**: `string | number`, can String or Int depending on the attribute

## Statement.stmtError(hType, recno)
## Statement.stmtError(hType, recno)

@@ -457,6 +368,6 @@ Returns the diagnostic information associated with the most recently called function for a particular statement, connection, or environment handler.

```js
hType can be following values:
SQL_HANDLE_ENV:Retrieve the environment diagnostic information
SQL_HANDLE_DBC:Retrieve the connection diagnostic information
SQL_HANDLE_STMT:Retrieve the statement diagnostic information
hType can be following values:
SQL_HANDLE_ENV: Retrieve the environment diagnostic information
SQL_HANDLE_DBC: Retrieve the connection diagnostic information
SQL_HANDLE_STMT: Retrieve the statement diagnostic information
```

@@ -463,0 +374,0 @@

@@ -215,3 +215,3 @@ const dba = require('idb-connector');

return new Promise((resolve, reject) => {
stmt.bindParamSync(params, (result, error) => {
stmt.bindParam(params, (error, result) => {
if (error) {

@@ -297,3 +297,3 @@ reject(error);

return new Promise((resolve, reject) => {
stmt.execSync(sqlString, (result, error) => {
stmt.exec(sqlString, function (result, error){
if (error) {

@@ -358,3 +358,3 @@ reject(error);

return new Promise((resolve, reject) => {
stmt.executeSync((result, error) => {
stmt.execute((result, error) => {
if (error) {

@@ -371,3 +371,4 @@ reject(error);

* If a result exists, retrieve a row from the result set
* @returns {Promise} - Promise object represents the row that was retrieved from the execution of fetch().
* @returns {Promise | null} - Promise object represents the row that was retrieved from the execution of fetch().
* when no data is found null is returned , indicating there ws nothing to return from fetch call.
* @memberof Statement

@@ -379,8 +380,9 @@ */

return new Promise((resolve, reject) => {
stmt.fetchSync((result, error) => {
if (error) {
reject(error);
} else {
stmt.fetch((result, rc) => {
if (rc === dba.SQL_SUCCESS ){ //dba.SQL_SUCCESS == 0
resolve(result);
} else if (rc === dba.SQL_NO_DATA_FOUND){
resolve(null); //Indicates the end of the Data Set
}
reject('Error');
});

@@ -399,3 +401,3 @@ });

return new Promise((resolve, reject) => {
stmt.fetchAllSync((result, error) => {
stmt.fetchAll((result, error) => {
if (error) {

@@ -603,3 +605,3 @@ reject(error);

return new Promise((resolve, reject) => {
stmt.prepareSync(sqlString, (result, error) => {
stmt.prepare(sqlString, (error, result) => {
if (error) {

@@ -606,0 +608,0 @@ reject(error);

{
"name": "idb-pconnector",
"version": "0.0.8",
"version": "0.1.0",
"description": "Promised-based Db2 Connector for IBM i (pre-alpha, NOT PRODUCTION READY)",
"main": "lib/idb-pconnector.js",
"scripts": {
"test": "mocha"
"test": "node node_modules/.bin/mocha"
},

@@ -21,9 +21,8 @@ "repository": {

"dependencies": {
"idb-connector": "^1.0.10"
"idb-connector": "^1.0.12"
},
"devDependencies": {
"mocha": "^5.1.0",
"chai": "^4.1.2"
"chai": "^4.1.2",
"mocha": "^5.2.0"
}
}

@@ -1,11 +0,7 @@

# idb-pconnector Package
# idb-pconnector
Promised-based Db2 Connector for IBM i (pre-alpha, NOT PRODUCTION READY)
The objective of this project is to provide a database connector for Db2 on i that enables usage of the "await" keyword.
As Well As Providing Connection Pooling Support. The `DBPool` has integrated aggregates that make it easier to Prepare & Execute, Prepare, Bind, & Execute, and Quickly Execute SQL.
Promised-based Db2 Connector for IBM i (production-ready as a "technology preview")
The objective of this project is to provide a database connector for Db2 on i that enables usage of the "await" keyword.
As Well As Providing Connection Pooling Support. The `DBPool` has integrated aggregates that make it easier to Prepare & Execute, Prepare, Bind, & Execute, and Quickly Execute SQL.
## Examples
Simple example of using a prepared statement to insert some values into a table, then querying all contents of that table:

@@ -15,15 +11,19 @@

const idbp = require('idb-pconnector');
async function runInsertAndSelect() {
try {
let statement = new idbp.Connection().connect().getStatement();
await statement.prepare('INSERT INTO MYSCHEMA.TABLE VALUES (?,?)');
await statement.bind([ [2018,idbp.SQL_PARAM_INPUT, idbp.SQL_BIND_NUMERIC],
['Dog' ,idbp.SQL_PARAM_INPUT, idbp.SQL_BIND_CHAR]
]);
await statement.execute();
let result = await statement.exec('SELECT * FROM MYSCHEMA.TABLE');
console.log(`Select results: \n${JSON.stringify(result)}`);
} catch(err) {
console.log(`Error was: \n${err.stack}`);
}
try {
let statement = new idbp.Connection().connect().getStatement();
await statement.prepare('INSERT INTO MYSCHEMA.TABLE VALUES (?,?)');
await statement.bind([ [2018, idbp.SQL_PARAM_INPUT, idbp.SQL_BIND_NUMERIC],
['Dog', idbp.SQL_PARAM_INPUT, idbp.SQL_BIND_CHAR]
]);
await statement.execute();
let result = await statement.exec('SELECT * FROM MYSCHEMA.TABLE');
console.log(`Select results: \n${JSON.stringify(result)}`);
} catch(err) {
console.log(`Error was: \n${err.stack}`);
}
}

@@ -35,3 +35,3 @@

Example Using DBPool to attach a connection , execute a stored procedure , and executing a simple select statement. Finally detach the connection.
Example Using DBPool to attach a connection , execute a stored procedure , and executing a simple select statement. Finally detach the connection.

@@ -44,25 +44,24 @@ ```javascript

async function poolExample(){
//attach() returns an available connection from the pool.
let connection = pool.attach(),
statement = connection.getStatement(),
results = null;
//attach() returns an available connection from the pool.
let connection = pool.attach(),
statement = connection.getStatement(),
results = null;
try {
await statement.prepare("CALL QIWS.GET_MEMBERS('QIWS','QCUSTCDT')");
await statement.execute();
results = await statement.fetchAll();
try {
await statement.prepare("CALL QIWS.GET_MEMBERS('QIWS','QCUSTCDT')");
await statement.execute();
results = await statement.fetchAll();
if (results !== null){
console.log(`\n\nResults: \n${JSON.stringify(results)}`);
}
//closes statements makes the Connection available for reuse.
await pool.detach(connection);
if (results !== null){
console.log(`\n\nResults: \n${JSON.stringify(results)}`);
}
//closes statments makes the Connection available for reuse.
await pool.detach(connection);
} catch (err){
console.log(`Error was: \n\n${err.stack}`);
pool.retire(connection);
}
}
} catch (err){
console.log(`Error was: \n\n${err.stack}`);
pool.retire(connection);
}
};
poolExample();

@@ -80,37 +79,35 @@

async function aggregatesRun(){
//Prepare and execute an SQL statement.
try {
console.log('\nPrepare and Execute\n');
let results = await pool.prepareExecute("CALL QIWS.GET_MEMBERS('QIWS','QCUSTCDT')");
//Prepare and execute an SQL statement.
try {
console.log('\Prepare and Execute\n');
let results = await pool.prepareExecute("CALL QIWS.GET_MEMBERS('QIWS','QCUSTCDT')");
if (results !== null) {
console.log(`\n\n${JSON.stringify(results)}\n\n`);
}
/*
Params are passed as an array values.
The order of the params indexed in the array should map to the order of the parameter markers(i.e. '?').
*/
console.log('\nPrepare Bind & Execute\n');
let sql = 'INSERT INTO QIWS.QCUSTCDT VALUES (?,?,?,?,?,?,?,?,?,?,?) with NONE',
params = [4949, 'Johnson', 'T J', '452 Broadway', 'MSP', 'MN', 9810, 2000, 1, 250, 0.00],
results2 = await pool.prepareExecute(sql, params);
console.log(`\n\n${JSON.stringify(results)}\n\n`);
}
/*
Params are passed as an array values.
The order of the params indexed in the array should map to the order of the parameter markers(i.e. '?').
*/
console.log('\nPrepare Bind & Execute\n');
let sql = 'INSERT INTO QIWS.QCUSTCDT VALUES (?,?,?,?,?,?,?,?,?,?,?) with NONE',
params = [4949, 'Johnson', 'T J', '452 Broadway', 'MSP', 'MN', 9810, 2000, 1, 250, 0.00],
results2 = await pool.prepareExecute(sql, params);
if (results2 !== null){
console.log(`\n\n${JSON.stringify(results2)}\n\n`);
}
/*
Quickly execute a statement by providing the SQL to the runSql() function
NOTE: Stored Procedures should use the prepareExecute() method instead.
*/
console.log('\nRun a Query\n');
let results3 = await pool.runSql(`SELECT * FROM QIWS.QCUSTCDT WHERE CUSNUM = ${params[0]}`);
if (results2 !== null){
console.log(`\n\n${JSON.stringify(results2)}\n\n`);
}
/*
Quickly execute a statement by providing the SQL to the runSql() function
NOTE: Stored Procedures should use the prepareExecute() method instead.
*/
console.log('\nRun a Query\n');
let results3 = await pool.runSql(`SELECT * FROM QIWS.QCUSTCDT WHERE CUSNUM = ${params[0]}`);
if (results3 !== null) {
console.log(`\n${JSON.stringify(results3)}`);
}
console.log('\nDone');
console.log(`\n${JSON.stringify(results3)}`);
}
console.log('\nDone');
} catch (err){
console.log(`Error was: ${err.stack}`);
}
} catch (err){
console.log(`Error was: ${err.stack}`);
}
}

@@ -121,4 +118,2 @@ aggregatesRun();

```
# API

@@ -129,3 +124,3 @@

## Connection.connect(dbname)
## Connection.connect(dbname)

@@ -140,9 +135,9 @@ Establishes a Connection to the database.

## Connection.getStatement()
## Connection.getStatement()
returns a Statment Object intialized to the current dbConn Conection.
returns a Statement Object initialized to the current dbConn Connection.
**Returns**: `object`, - a new Statement intialized with the current dbconn.
**Returns**: `object`, - a new Statement initialized with the current dbconn.
## Connection.close()
## Connection.close()

@@ -153,9 +148,9 @@ closes the Connection to the DB and frees the connection object.

## Connection.disconn()
## Connection.disconn()
disconnects an exsisting connection to the datbase.
disconnects an existing connection to the database.
**Returns**: `Promise`, - Promise object represents the disconnect of the Connection.
## Connection.debug(choice)
## Connection.debug(choice)

@@ -170,51 +165,17 @@ prints more detailed info if choice = true. Turned off by setting choice = false.

## Connection.getConnAttr(attribute)
## Connection.getConnAttr(attribute)
if connection attribute exsits should return type String or Int depending on the attribute type
if connection attribute exists should return type String or Int depending on the attribute type
**Parameters**
**attribute**: `number`, if connection attribute exsits should return type String or Int depending on the attribute type
**attribute**: `number`, if connection attribute exists should return type String or Int depending on the attribute type
**Returns**: `Promise`, - Promise object represents the the current settings for the specified connection attribute.
**Example**:
```js
Available Set & Get Connection Attributes:
SQL_ATTR_2ND_LEVEL_TEXT
SQL_ATTR_AUTOCOMMIT
SQL_ATTR_CONCURRENT_ACCESS_RESOLUTION
SQL_ATTR_CONN_SORT_SEQUENCE
SQL_ATTR_COMMIT
SQL_ATTR_DBC_DEFAULT_LIB
SQL_ATTR_DECFLOAT_ROUNDING_MODE
SQL_ATTR_DECIMAL_SEP
SQL_ATTR_EXTENDED_COL_INFO
SQL_ATTR_EXTENDED_INDICATORS
SQL_ATTR_FREE_LOCATORS
SQL_ATTR_HEX_LITERALS
SQL_ATTR_INFO_ACCTSTR
SQL_ATTR_INFO_APPLNAME
SQL_ATTR_INFO_PROGRAMID
SQL_ATTR_INFO_USERID
SQL_ATTR_INFO_WRKSTNNAME
SQL_ATTR_MAX_PRECISION
SQL_ATTR_MAX_SCALE
SQL_ATTR_MIN_DIVIDE_SCALE
SQL_ATTR_OLD_MTADTA_BEHAVIOR
SQL_ATTR_NULLT_ARRAY_RESULTS
SQL_ATTR_NULLT_OUTPUT_PARMS
SQL_ATTR_QUERY_OPTIMIZE_GOAL
SQL_ATTR_SAVEPOINT_NAME
SQL_ATTR_TIME_FMT
SQL_ATTR_TIME_SEP
SQL_ATTR_TIMESTAMP_PREC
SQL_ATTR_TXN_EXTERNAL
SQL_ATTR_TXN_INFO
SQL_ATTR_UCS2
```
[Further Documentaion ON Connection Attributes](https://www.ibm.com/support/knowledgecenter/en/ssw\_ibm\_i_73/cli/rzadpfnsconx.htm)
## Connection.setConnAttr(attribute, value)
**Link**:
[Further Documentation ON Connection Attributes](https://www.ibm.com/support/knowledgecenter/en/ssw\_ibm\_i_73/cli/rzadpfnsconx.htm)
## Connection.setConnAttr(attribute, value)
Sets the ConnAttr , Attrubte should be INT.
Sets the ConnAttr , Attribute should be INT.

@@ -229,5 +190,5 @@ **Parameters**

### Connection.validStmt(sql)
### Connection.validStmt(sql)
Checks if the given SQL is valid and nterprets vendor escape clauses.
Checks if the given SQL is valid and interprets vendor escape clauses.

@@ -244,3 +205,3 @@ **Parameters**

## Statement.bindParam(params)
## Statement.bindParam(params)

@@ -257,18 +218,19 @@ associates parameter markers in an SQL statement to app variables.

```js
bStmt.bindParam([
[2099, dba.SQL_PARAM_INPUT, dba.SQL_BIND_NUMERIC],
['Node.Js', dba.SQL_PARAM_INPUT,dba.SQL_BIND_CHAR]
]);
IN/OUT TYPE CAN BE:
1.SQL_PARAM_INPUT
2.SQL_PARAM_OUTPUT
3.SQL_PARAM_INPUT_OUTPUT
INDICATORS CAN BE:
1. SQL_BIND_CLOB
2. SQL_BIND_CHAR
3. SQL_BIND_NUMERIC
4. SQL_BIND_NULL_DATA
statement.bindParam([
[2099, dba.SQL_PARAM_INPUT, dba.SQL_BIND_NUMERIC],
['Node.Js', dba.SQL_PARAM_INPUT,dba.SQL_BIND_CHAR]
]);
IN/OUT TYPE CAN BE:
1.SQL_PARAM_INPUT
2.SQL_PARAM_OUTPUT
3.SQL_PARAM_INPUT_OUTPUT
INDICATORS CAN BE:
1. SQL_BIND_CLOB
2. SQL_BIND_CHAR
3. SQL_BIND_NUMERIC
4. SQL_BIND_NULL_DATA
```
## Statement.bind(params)
## Statement.bind(params)

@@ -282,3 +244,3 @@ Shorthand for bindParam

## Statement.close()
## Statement.close()

@@ -289,3 +251,3 @@ Ends and frees the statement object.

## Statement.closeCursor()
## Statement.closeCursor()

@@ -296,3 +258,3 @@ closes the cursor associated with the dbstmt object and discards any pending results.

## Statement.commit()
## Statement.commit()

@@ -303,3 +265,3 @@ adds all changes to the database that have been made on the connection since connect time.

## Statement.exec(sqlString)
## Statement.exec(sqlString)

@@ -313,5 +275,5 @@ performs action of given SQL String. The exec() method does not work with stored procedure calls use execute() instead.

**Returns**: , the result set as an array.
**Returns**: `Promise`, - Promise object represents the result set from the exection of exec().
**Returns**: `Promise`, - Promise object represents the result set from the execution of exec().
## Statement.execute()
## Statement.execute()

@@ -326,88 +288,93 @@ Runs a statement that was successfully prepared using prepare().

- Calling a stored Procedure that returns a result set with execute() & displaying the result set.
try{
var dba = require("idb-pconnector");
const idbp = require('idb-pconnector');
// note that that calling the new Statement() without the DbConn as a parameter
// creates a new connection automatically and uses that for the Statment.
var dbStmt = new dba.Statement();
var sql = "call QIWS.sampleProc";
await dbStmt.prepare(sql);
await dbStmt.execute();
var res = await dbStmt.fetchAll();
console.log(`Result is\n: ${JSON.stringify(res)}`);
}
catch(dbError){
console.log(dbError.stack);
},- Insert Example With Prepare , Binding Parameter , and Execution
try {
var dba = require("idb-pconnector");
async function storedProcedure(){
try {
// note that that calling the new Statement() without the DbConn as a parameter
// creates a new connection implicitly and uses that for the Statement.
let statement = new idbp.Statement(),
sql = 'CALL MYSCHEMA.SAMPLEPROC';
await statement.prepare(sql);
await statement.execute();
//if a result set exists you can fetch it
let result = await statement.fetchAll();
console.log(`Result is\n: ${JSON.stringify(result)}`);
} catch(error){
console.log(error.stack);
}
}
storedProcedure();
- Insert Example With Prepare , Binding Parameter , and Execution
// note that that calling the new Statement() without the DbConn as a parameter
// creates a new connection automatically and uses that for the Statment.
var dbStmt = new dba.Statement();
await dbStmt.prepare("INSERT INTO AMUSSE.TABLE1 VALUES (?,?)");
await dbStmt.bind([ [2018,dba.SQL_PARAM_INPUT,dba.SQL_BIND_NUMERIC], [ ,dba.PARM_TYPE_INPUT, dba.SQL_BIND_NULL_DATA ] ]);
await dbStmt.execute();
var res = await dbStmt.exec("SELECT * FROM AMUSSE.TABLE1");
console.log("Select results: "+JSON.stringify(res));
}
catch (dbError) {
console.log("Error is " + dbError);
console.log(error.stack);
}
```
const idbp = require('idb-pconnector');
async function prepareBindExecute(){
try {
let statement = new idbp.Statement(),
sql = 'INSERT INTO MYSCHEMA.MYTABLE VALUES (?,?)';
**Example**:
```js
- Calling a stored Procedure that returns a result set with execute() & displaying the result set.
try{
var dba = require("idb-pconnector");
await statement.prepare(sql);
//binding a number and null data types
await statement.bind([ [2018,idbp.SQL_PARAM_INPUT,idbp.SQL_BIND_NUMERIC], [null ,idbp.PARM_TYPE_INPUT, idbp.SQL_BIND_NULL_DATA ] ]);
await statement.execute();
// note that that calling the new Statement() without the DbConn as a parameter
// creates a new connection automatically and uses that for the Statment.
var dbStmt = new dba.Statement();
var sql = "call QIWS.sampleProc";
await dbStmt.prepare(sql);
await dbStmt.execute();
var res = await dbStmt.fetchAll();
console.log(`Result is\n: ${JSON.stringify(res)}`);
}
catch(dbError){
console.log(dbError.stack);
},- Insert Example With Prepare , Binding Parameter , and Execution
try {
var dba = require("idb-pconnector");
// note that that calling the new Statement() without the DbConn as a parameter
// creates a new connection automatically and uses that for the Statment.
var dbStmt = new dba.Statement();
await dbStmt.prepare("INSERT INTO AMUSSE.TABLE1 VALUES (?,?)");
await dbStmt.bind([ [2018,dba.SQL_PARAM_INPUT,dba.SQL_BIND_NUMERIC], [ ,dba.PARM_TYPE_INPUT, dba.SQL_BIND_NULL_DATA ] ]);
await dbStmt.execute();
var res = await dbStmt.exec("SELECT * FROM AMUSSE.TABLE1");
console.log("Select results: "+JSON.stringify(res));
}
catch (dbError) {
console.log("Error is " + dbError);
console.log(error.stack);
}
let result = await statement.exec('SELECT * FROM MYSCHEMA.MYTABLE');
console.log(`Select results: \nJSON.stringify(result)`);
} catch(error){
console.log(error.stack);
}
}
prepareBindExecute();
```
## Statement.fetch()
## Statement.fetch()
if a result exsits , retrieves a row from the result set
if a result exists , retrieves a row from the result set
**Returns**: `Promise`, - Promise object represents the row that was retrieved from the execution of fetch().
**Returns**: `Promise`, - Promise object represents the row that was retrieved from the execution of fetch(). If there is no data to be fetched null will be returned indicating the end of the result set.
## Statement.fetchAll()
```javascript
if a result set exsits , retrieves all the rows of data from the result set.
- Example Fetching a result set until there is no more data to fetch.
const idbp = require('idb-pconnector');
async function fetch(){
try {
let sql = 'SELECT * FROM QIWS.QCUSTCDT',
connection = new idbp.Connection();
connection.debug(true);
let statement = connection.connect().getStatement();
await statement.prepare(sql);
await statement.execute();
let result = await statement.fetch();
while (result !== null ){
console.log(`Fetch result:\n ${JSON.stringify(result)}`);
result = await statement.fetch();
}
} catch(error){
console.log(error.stack);
}
}
fetch();
```
## Statement.fetchAll()
if a result set exists , retrieves all the rows of data from the result set.
**Returns**: `Promise`, - Promise object represents the the an array containing the result that was retrieved from the execution of fetchAll().
## Statement.fieldName(index)
## Statement.fieldName(index)

@@ -418,7 +385,7 @@ requires an int index parameter. If a valid index is provided, returns the name of the indicated field.

**index**: `number`, the postion of the field within the table. It is 0 based.
**index**: `number`, the position of the field within the table. It is 0 based.
**Returns**: `Promise`, - Promise object represents the the String that was retrieved from the execution of fieldName().
## Statement.fieldNullable(index)
## Statement.fieldNullable(index)

@@ -429,7 +396,7 @@ requires an int index parameter. If a valid index is provided, returns t/f if the indicated field can be Null

**index**: `number`, the postion of the field within the table. It is 0 based.
**index**: `number`, the position of the field within the table. It is 0 based.
**Returns**: `Promise`, - Promise object represents the the boolean that was retrieved from the execution of fieldNullable().
## Statement.fieldPrecise(index)
## Statement.fieldPrecise(index)

@@ -440,7 +407,7 @@ requires an int index parameter. If a valid index is provided, returns the precision of the indicated field

**index**: `number`, the postion of the field within the table. It is 0 based.
**index**: `number`, the position of the field within the table. It is 0 based.
**Returns**: `Promise`, - Promise object represents the the Number that was retrieved from the execution of fieldPrecisie().
## Statement.fieldScale(index)
## Statement.fieldScale(index)

@@ -451,7 +418,7 @@ requires an int index parameter. If a valid index is provided, returns the scale of the indicated column

**index**: `number`, the postion of the field within the table. It is 0 based.
**index**: `number`, the position of the field within the table. It is 0 based.
**Returns**: `Promise`, - Promise object represents the the Number that was retrieved from the execution of fieldScale().
## Statement.fieldType(index)
## Statement.fieldType(index)

@@ -462,7 +429,7 @@ requires an int index parameter. If a valid index is provided, returns the data type of the indicated field

**index**: `number`, the postion of the field within the table. It is 0 based.
**index**: `number`, the position of the field within the table. It is 0 based.
**Returns**: `Promise`, - Promise object represents the the Number that was retrieved from the execution of fieldType().
## Statement.fieldWidth(index)
## Statement.fieldWidth(index)

@@ -473,9 +440,9 @@ requires an int index parameter. If a valid index is provided, returns the field width of the indicated field

**index**: `number`, the postion of the field within the table. It is 0 based.
**index**: `number`, the position of the field within the table. It is 0 based.
**Returns**: `Promise`, - Promise object represents the the Number that was retrieved from the execution of fieldWidth().
## Statement.getStmtAttr(attribute)
## Statement.getStmtAttr(attribute)
If a valid Statment attribute is provided , returns the current settings for the specified Statement attribute.
If a valid Statement attribute is provided , returns the current settings for the specified Statement attribute.
Refer to the list below for valid Statement Attributes.

@@ -489,27 +456,5 @@

**Example**:
```js
Available Set & Get Statement Attributes
SQL_ATTR_APP_PARAM_DESC
SQL_ATTR_APP_ROW_DESC
SQL_ATTR_BIND_TYPE
SQL_ATTR_CURSOR_HOLD
SQL_ATTR_CURSOR_SCROLLABLE
SQL_ATTR_CURSOR_SENSITIVITY
SQL_ATTR_CURSOR_TYPE
SQL_ATTR_EXTENDED_COL_INFO
SQL_ATTR_FOR_FETCH_ONLY
SQL_ATTR_FULL_OPEN
SQL_ATTR_NUMBER_RESULTSET_ROWS_PTR
SQL_ATTR_PARAM_BIND_TYPE
SQL_ATTR_PARAM_STATUS_PTR
SQL_ATTR_PARAMS_PROCESSED_PTR
SQL_ATTR_PARAMSET_SIZE
SQL_ATTR_ROW_BIND_TYPE
SQL_ATTR_ROW_STATUS_PTR
SQL_ATTR_ROWS_FETCHED_PTR
SQL_ATTR_ROWSET_SIZE
```
**Link**:
[Further Documentaion On Statement Attributes](https://www.ibm.com/support/knowledgecenter/en/ssw_ibm_i_73/cli/rzadpfnsstma.htm)
## Statement.nextResult()
## Statement.nextResult()

@@ -520,3 +465,3 @@ Determines whether there is more information available on the statement

## Statement.numFields()
## Statement.numFields()

@@ -527,9 +472,9 @@ if a result is available , retrieves number of fields contained in result.

## Statement.numRows()
## Statement.numRows()
if a query was performed ,retrieves number of rows that were effected by a query
if a query was performed ,retrieves number of rows that were affected by a query
**Returns**: `Promise`, - Promise object represents the Number returned from the execution of numRows().
## Statement.prepare(sqlString)
## Statement.prepare(sqlString)

@@ -546,6 +491,6 @@ If valid SQL is provided . prepares SQL and sends it to the DBMS, if the input SQL Statement cannot be prepared error is thrown.

```js
- view the examples located at the excute() method.
- view the examples located at the execute() method.
```
## Statement.rollback()
## Statement.rollback()

@@ -555,9 +500,9 @@ Reverts changes to the database that have been made on the connection since connect time or the previous call to commit().

## Statement.setStmtAttr(attribute, value)
## Statement.setStmtAttr(attribute, value)
if a valid attribute and value is providied , sets StmtAttr indicate Attrubte. Refer to the example @getStmtAttr for a list of valid Statement Attributes.
if a valid attribute and value is provided , sets StmtAttr indicate Attribute. Refer to the example @getStmtAttr for a list of valid Statement Attributes.
**Parameters**
**attribute**: `number`, musbt be an int INT.
**attribute**: `number`, must be an int INT.

@@ -568,3 +513,3 @@ **value**: `string | number`, can String or Int depending on the attribute

## Statement.stmtError(hType, recno)
## Statement.stmtError(hType, recno)

@@ -583,6 +528,6 @@ Returns the diagnostic information associated with the most recently called function for a particular statement, connection, or environment handler.

```js
hType can be following values:
SQL_HANDLE_ENV:Retrieve the environment diagnostic information
SQL_HANDLE_DBC:Retrieve the connection diagnostic information
SQL_HANDLE_STMT:Retrieve the statement diagnostic information
hType can be following values:
SQL_HANDLE_ENV: Retrieve the environment diagnostic information
SQL_HANDLE_DBC: Retrieve the connection diagnostic information
SQL_HANDLE_STMT: Retrieve the statement diagnostic information
```

@@ -603,3 +548,3 @@

**database**: `object`, Object includes the `url`(databse name) defaults to *LOCAL, `username`, and `password`. `username` and `password` assumed blank if not specified with non-local URL.
**database**: `object`, Object includes the `url`(database name) defaults to *LOCAL, `username`, and `password`. `username` and `password` assumed blank if not specified with non-local URL.

@@ -609,3 +554,3 @@ **config**: `object` , Object includes the `incrementSize` and `debug`. IncrementSize sets the desired size of the DBPool. If none specified, defaults to 8 connections. Setting debug = true will display message logs.

### DBPool.createConnection(index)
### DBPool.createConnection(index)

@@ -620,3 +565,3 @@ Instantiates a new instance of DBPoolConnection with an `index` and appends it to the pool.

### DBPool.detachAll()
### DBPool.detachAll()

@@ -626,11 +571,11 @@ Frees all connections in the pool (Sets "Available" back to true for all)

**Returns**: `boolean`, - true if all were detached succesfully
**Returns**: `boolean`, - true if all were detached successfully
### DBPool.retireAll()
### DBPool.retireAll()
Retires (Removes) all connections from being used again
**Returns**: `boolean`, - true if all were retired succesfully
**Returns**: `boolean`, - true if all were retired successfully
### DBPool.detach(connection)
### DBPool.detach(connection)

@@ -646,3 +591,3 @@ Frees a connection (Returns the connection "Available" back to true)

### DBPool.retire(connection)
### DBPool.retire(connection)

@@ -656,3 +601,3 @@ Retires a connection from being used and removes it from the pool

### DBPool.attach()
### DBPool.attach()

@@ -665,3 +610,3 @@ Finds and returns the first available Connection.

### DBPool.runSql(sql)
### DBPool.runSql(sql)

@@ -672,8 +617,8 @@ Shorthand to exec a statement , just provide the sql to run.

**sql**: `string`, the sql statment to execute.
**sql**: `string`, the sql statement to execute.
**Returns**: `array`, - if the SQL returns a result set it is returned as an array of objects.
else if no result set is available null is returned. caller should check if null is returned.
else if no result set is available null is returned. caller should check if null is returned.
### DBPool.prepareExecute(sql, params)
### DBPool.prepareExecute(sql, params)

@@ -680,0 +625,0 @@ Shortcut to prepare ,bind, and execute. Just provide the sql and the params as an array.

@@ -0,1 +1,6 @@

/**
* Like The Other Tests these are not behaving as expected
* See Notes in mocha-issue.txt
*/
const expect = require('chai').expect;

@@ -11,5 +16,5 @@ const idbp = require('../lib/idb-pconnector');

let lenBefore = connPool.connections.length;
//call the createConnection
connPool.createConnection();
//check the new length
//verify the connection was added by checking the new length
expect(connPool.connections.length).to.be.equal(lenBefore +1);

@@ -23,3 +28,7 @@ });

log(JSON.stringify(conn) );
//verify that the conn returned is of type DBPoolConnection
expect(conn).to.be.an.instanceOf(DBPoolConnection);
//verify that it is set to unavailable in the Pool
expect(conn.available).to.be.false;

@@ -29,26 +38,34 @@ connPool.detach(conn);

});
describe('detach', async () => {
it('should make the connection available again and clear stmts', async () => {
//get the conn
let conn = await connPool.attach();
//perform some stmts
await conn.getStatement().exec('SELECT * FROM QIWS.QCUSTCDT');
log(`\n${JSON.stringify(conn)}`);
let stmtBefore = conn.statement;
let id = conn.poolIndex;
await conn.detach();
let detached = connPool.connections[id];
let stmtAfter = detached.statement;
stmtBefore === stmtAfter ? log('Yes') : log('no');
//after being detached available should be true again
expect(detached.available).to.be.true;
//make sure the statement was cleared
expect(stmtBefore).to.not.equal(stmtAfter);
//could give assertion error (red herring?) , see detatch test in manualTest.js
describe.only('detach', async () => {
it('should make the connection available again and clear stmts', async (done) => {
new Promise( async (resolve, reject) =>{
//get the conn
let conn = await connPool.attach();
//perform some stmts
await conn.getStatement().exec('SELECT * FROM QIWS.QCUSTCDT');
console.log(`\n${JSON.stringify(conn)}`);
let stmtBefore = conn.statement,
id = conn.poolIndex;
await conn.detach();
let detached = connPool.connections[id],
stmtAfter = detached.statement;
//after being detached available should be true again
expect(detached.available).to.be.true;
//make sure the statement was cleared
expect(stmtBefore).to.not.equal(stmtAfter);
await connPool.detach(conn);
});
done();
});
});
describe('detachAll', async () => {
describe.only('detachAll', async () => {
it('should return all connections back to available', async () => {
//first attach all 8 connections
log(connPool.connections.length);
//make all of th
//ensure all connections reset before attaching all
await connPool.detachAll();
//make all of the connections unavailable
for ( connection of connPool.connections){

@@ -58,3 +75,2 @@ //all of the conns should be unavailable

}
log(connPool.connections);
for ( connection of connPool.connections){

@@ -75,3 +91,3 @@ //all of the conns should be unavailable

});
describe('retire', async () => {
describe.only('retire', async () => {
it('should remove a connection from the pool', async () => {

@@ -81,4 +97,7 @@ let conn = await connPool.attach(),

lenBefore = connPool.connections.length;
await connPool.retire(conn);
//verify that conn was removed
expect(connPool.connections.length).to.be.equal(lenBefore - 1);
connPool.connections.forEach(element => {

@@ -89,6 +108,7 @@ expect(element.poolIndex).to.not.equal(id);

});
describe('retireAll', async () => {
describe.only('retireAll', async () => {
it('should remove all connection from the pool', async () => {
log('Length Before: '+ connPool.connections.length);
await connPool.retireAll();
log('Length After: '+ connPool.connections.length);

@@ -98,18 +118,27 @@ expect(connPool.connections.length).to.equal(0);

});
describe('runSql', async () => {
it('should execute sql and return result set as an array if available , or return null', async () => {
let results = await connPool.runSql('SELECT * FROM QIWS.QCUSTCDT');
expect(results).to.be.an('array') && expect(results.length).to.be.gt(0) || expect(result.to.be.null);
describe.only('runSql', async () => {
it('should execute sql and return result set as an array if available , or return null', async (done) => {
new Promise(async () => {
let results = await connPool.runSql('SELECT * FROM QIWS.QCUSTCDT');
expect(results).to.be.an('array');
expect(results.length).to.be.gt(0);
});
done();
});
});
//could give assertion error (red herring?) , try manual prepareExecute test in manualTest.js
describe.only('prepare, bind, execute', async () => {
it('should prepare bind and execute , return output params if available or result set if available',
async (done) => {
new Promise(async (resolve, reject) =>{
let cusNum = 938472,
results = await connPool.prepareExecute('SELECT * FROM QIWS.QCUSTCDT WHERE CUSNUM = ?', [cusNum]);
describe('prepare, bind, execute', async () => {
it('should prepare bind and execute , return output params if available or result set if available',
async () => {
let cusNum = 938472,
results = await connPool.prepareExecute('SELECT * FROM QIWS.QCUSTCDT WHERE CUSNUM = ?', [cusNum]);
console.log(results);
expect(results).to.be.an('array') && expect(results.length).to.be.gt(0) || expect(result).to.be.null;
console.log(results);
expect(results).to.be.an('array');
expect(results.length).to.be.gt(0);
});
done();
});
});
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc