Postgresjs

Postgresjs

For use with Postgresql databases.

Created by Phanxgames

Requirements:

- ECMAScript 2015 (ES6)
- Node.JS 6.2.2 or later (tested on 6.2.2)

Installation:

     npm install postgresjs

Note: the dictionaryjs, pg and suspend modules should be automatically installed as dependencies, but you may need to install these as well.

Copy the dbConfig.ex.json file into your project source folder, rename to dbConfig.json, and update with your database connection information.

Important:

You may only use one connection with each instance of this class. Close any opened connection before opening a new one. You may reuse an instance with a new connection if you close the previous.

Asynchronous nature:

All methods that include a callback (cb) have been designed to be used with the suspend library and may be placed behind a yield command. Be sure to leave the cb parameter null to use the suspend.resume functionality automatically.

IMPORTANT: You will also need to set the resume reference in the constructor or the Postgresjs#setResume method, before the suspend.resume functionality will be enabled.

If you do provide a callback, the 3rd parameter, "next" (ex: cb(err,result, next)) will be the suspend.resume function reference so you may resume execution to move past the next yield command.

Example:

  var suspend = require("suspend");
  var Postgresjs = require("postgresjs");

  //Attach your dbConfig to the Postgresjs module
  Postgresjs.config = require('./dbConfig.json');

  var db = new Postgresjs(suspend.resume);

  suspend(function*() {
     yield db.start();

     //find all users' email with a username that contains "phanx"
     yield db.query("select email from users where username LIKE ? ;",["%phanx%"]);

     if (db.error()) {
         console.error("Error:",db.error());
         return;
     }

     console.log(db.rowCount + " rows found!");

     for (let row of db.rows) {
         console.log(row);
         if (row.email == "test@test.com") {
             //..
         }
     }

     //..place other below examples here..

     yield db.end();

  })();

Constructor

new Postgresjs(resumeopt, configopt)

Source:
Pass in a unique config just for this instance by using require to get the JSON contents.

Example:

    //..
    var suspend = require("suspend");

    var myconfig = require("./dbConfig2.json");
    var db = new Postgresjs(suspend.resume,myconfig);
    //..
Parameters:
Name Type Attributes Default Description
resume function <optional>
null set to suspend.resume from generator context to use suspend library with yields. See setResume.
config Object <optional>
null Overwrite the global config for just this instance.

Members

(static) config

Source:
Required to set this before you first initalize this class.
This should be static across your entire project and only needs to be set once.
Set to the Contents of dbConfig.json as Object.

Example:

    var Postgresjs = require("postgresjs");
    Postgresjs.config = require("./dbConfig.json");
    //..

connectionString

Source:
Returns connection string with dbConfig values inserted inline.

rowCount

Source:
Returns number of rows last affected by last query

rows

Source:
Returns an array of objects as rows from last query

throwErrors

Source:
Disabling throwErrors will stop suspend from throwing errors on callbacks. This is enabled by default.

Methods

asyncForEach(cbIterator, cbFinalopt, enableCallbackopt)

Source:
Loops over the rows from the last query. Non-blocking.

Example:

  //..
  yield db.asyncForEach((index,item,next) => {
     console.log(index + ") ",item);
     //..
     next();
  });
 //..
Parameters:
Name Type Attributes Default Description
cbIterator Postgresjs~cbAsyncForEachIterator Returns cb(index,item,cbNext).
Must call cbNext() to continue.
cbFinal Postgresjs~cbAsyncForEachFinal <optional>
null Returns cb().
enableCallback Boolean <optional>
true Set to false to disable default callback handling (used to disable suspend.resume on loop completion).

begin(cbopt)

Source:
Begins a transaction.
Parameters:
Name Type Attributes Default Description
cb Postgresjs~cbOnError <optional>
null Use callback or leave null to use suspend.resume.
Returns cb(err)

commit(cbopt)

Source:
Commits the transaction.
Parameters:
Name Type Attributes Default Description
cb Postgresjs~cbOnError <optional>
null Use callback or leave null to use suspend.resume.
Returns cb(err)

deleteHelper(options, cbopt)

Source:
Delete Statement Helper

Example:

Deletes user record with the username "tester".
    //..
    yield db.deleteHelper({
         table: "users",
         where: db.whereHelper({
             "username":"tester"
         })
    });
    //..
Parameters:
Name Type Attributes Default Description
options Object Required. See properties:
Properties
Name Type Attributes Default Description
table String Table name
where String <optional>
null where clause sql statement segment (ie: name=? OR id=? )
You may also use Postgresjs#whereHelper
whereParas Array <optional>
null Array of values to replace parameters in where SQL
Not needed if you use whereHelper.
limit int <optional>
null Number of records to delete, or null for infinite.
cb Postgresjs~cbOnError <optional>
null Use callback or leave null to use suspend.resume.
Returns cb(err)

end(cbopt)

Source:
Closes the connection. You must call this when you are done with this database connection. If you do not end the connection the pool will be exhausted.

Alias: close(cb)

Parameters:
Name Type Attributes Default Description
cb Postgresjs~cbOnEmpty <optional>
null Use callback or leave null to use suspend.resume.
Returns cb(err)

error()

Source:
Returns an error object from the last executed command on this db conn.
Returns:
Error object or null if no error

insertHelper(options, cbopt)

Source:
Insert Statement Helper

Example:

Insert new user into users table.
    //..
    yield db.insertHelper({
         table:"users",
         columns:{
             "username":"tester",
             "email":"oldemail@test.com"
         }
    });
    //..
Parameters:
Name Type Attributes Default Description
options Object Required. See properties:
Properties
Name Type Attributes Default Description
table String Table name
columns Array <optional>
null Leave null to use table order of columns.
Array of column names to update, use with options.values property to specifiy values.
columns Object <optional>
null Or Object where keys are column names and values are values. Note: options.values property not needed.
values Array <optional>
null Array of values used with options.columns (Array) property.
cb Postgresjs~cbOnError <optional>
null Use callback or leave null to use suspend.resume.
Returns cb(err)

merge(sqlInsert, parasInsertopt, sqlUpdate, parasUpdateopt, cbopt)

Source:
Merge allows you to insert or update a record by proving insert and update sql statements.

Try using instead the Postgresjs#mergeHelper to generate the two sql statements.

Parameters:
Name Type Attributes Default Description
sqlInsert String sql statement with unnamed parameters (ie: ?)
parasInsert Array <optional>
null array of parameters to replace ? in sql
sqlUpdate String sql statement with unnamed parameters (ie: ?)
parasUpdate Array <optional>
null array of parameters to replace ? in sql
cb Postgresjs~cbOnMerge <optional>
null Use callback or leave null to use suspend.resume.
Returns cb(err,result) where result will be either "insert" or "update" depending on which action was used.

mergeHelper(options, cbopt)

Source:
Helper function of Merge method.

Merge is a smart method that uses insert or update internally. See Postgresjs#merge for more information.

Example:

Inserts a new user in the users table or updates their email if already found.
    //..
    yield db.mergeHelper({
         table: "users",
         columns: {
             "username":"tester",
             "email":"test@test.com"
         },
         where: db.whereHelper({
             "username":"tester"
         })
    });
    //..
Parameters:
Name Type Attributes Default Description
options Object Required. See properties:
Properties
Name Type Attributes Default Description
table String Table name
columns Array Array of column names to update, use with options.values property to specifiy values.
columns Object Or Object where keys are column names and values are values. Note: options.values property not needed.
values Array <optional>
null Array of values used with options.columns (Array) property.
where String <optional>
null where clause sql statement segment (ie: name=? OR id=? )
You may also use Postgresjs#whereHelper
whereParas Array <optional>
null Array of values to replace parameters in where SQL
Not needed if you use whereHelper.
cb Postgresjs~cbOnMerge <optional>
null Use callback or leave null to use suspend.resume.
Returns cb(err,result) where result is either "update" or "insert" depending on which operation was needed.

orderByHelper(options)

Source:
Returns a string to be used in the "orderBy" field in other helpers. See Postgresjs#selectHelper.

Sort options are either "ASC" or "DESC".

Parameters:
Name Type Description
options Object Required. See properties:
Properties
Name Type Attributes Default Description
columns Array Array of column names, or
Array of Objects: [{name:"column name",sort:"ASC"}, ..], or
Array of Arrays: [["column name","ASC"], ..]
defaultSort String <optional>
"ASC" Used if sort is not specified.
Returns:
string of sql (the order by clause)

query(sql, parasopt, cbopt)

Source:
Executes SQL statement on database.

Use question-marks (ie: ?) as unnamed parameters within the SQL statement.

Example:

    //..
    yield db.query("select username from users where email=?;",["test@test.com"]);
    for (let row of db.rows) {
        console.log(row.username);
    }
    //..
Parameters:
Name Type Attributes Default Description
sql string sql statement to execute
paras Array <optional>
null array of parameters, replacing "?" in SQL
cb Postgresjs~cbOnQuery <optional>
null Use callback or leave null to use suspend.resume.
Returns cb(err,results) where result is an array of rows.

rollback(cbopt)

Source:
Rolls back the transaction.
Parameters:
Name Type Attributes Default Description
cb Postgresjs~cbOnError <optional>
null Use callback or leave null to use suspend.resume.
Returns cb(err)

selectArray(sql, parasopt, cbopt)

Source:
Executes SQL statement on database and returns the array of rows.

Use question-marks (ie: ?) as unnamed parameters within the SQL statement.

Example:

    //..
    let arr = yield db.selectArray("select username from users where email=?;",["test@test.com"]);
    //..
Parameters:
Name Type Attributes Default Description
sql string sql statement to execute
paras Array <optional>
null array of parameters, replacing "?" in SQL
cb Postgresjs~cbOnQuery <optional>
null Use callback or leave null to use suspend.resume.
Returns cb(err,results) where result is an array of rows.

selectHelper(options, cbopt)

Source:
Select Statement Helper.

Example:

Select emails from users table that have a username that starts with the letter "h":
    //..
    yield db.selectHelper({
         table:"users",
         columns:["username","email"],
         where: db.whereHelper({
             "username -like":"h%"
         }),
         orderBy: db.orderByHelper({
             "email":"ASC"
         })
    });

    for (let row of db.rows) {
         console.log(row);
         //Output example: {username:"Tester",email:"test@test.com"}
    }

    //..
Parameters:
Name Type Attributes Default Description
options Object Required. See properties:
Properties
Name Type Attributes Default Description
table String Table name
columns Array Array of column names to select.
where String <optional>
null where clause sql statement segment (ie: name=? OR id=? )
You may also use Postgresjs#whereHelper
whereParas Array <optional>
null Array of values to replace parameters in where SQL
Not needed if you use whereHelper.
orderBy String <optional>
null order clause sql statement segment (ie: name ASC)
You may also use Postgresjs#orderByHelper
limit int <optional>
null Number of records to return, or null for infinite.
start int <optional>
0 Start row index position.
cb Postgresjs~cbOnQuery <optional>
null Use callback or leave null to use suspend.resume.
Returns cb(err,results) where result is an array of rows.

selectRow(sql, parasopt, cbopt)

Source:
Executes SQL statement on database and returns the first row.

Use question-marks (ie: ?) as unnamed parameters within the SQL statement.

Example:

    //..
    let row = yield db.selectRow("select username from users where email=?;",["test@test.com"]);
    //..
Parameters:
Name Type Attributes Default Description
sql string sql statement to execute
paras Array <optional>
null array of parameters, replacing "?" in SQL
cb Postgresjs~cbOnQuery <optional>
null Use callback or leave null to use suspend.resume.
Returns cb(err,results) where result is an array of rows.

setLocalConfig(config)

Source:
Parameters:
Name Type Description
config Object

setResume(resume)

Source:
Enables automatic calling of suspend.resume on all methods with optional callbacks. See Class comment at top of file.
Parameters:
Name Type Description
resume function set to suspend.resume, set to null to disable

start(cbopt)

Source:
Opens a database connection. Must be called before using any other method.

Alias: open(cb)

Parameters:
Name Type Attributes Default Description
cb Postgresjs~cbOnError <optional>
null Use callback or leave null to use suspend.resume.
Returns cb()

updateHelper(options, cbopt)

Source:
Update Statement Helper

Example:

Updates user's email by username.
    //..
    yield db.updateHelper({
         table: "users",
         columns: {
             "email":"newemail@test.com"
         },
         where: db.whereHelper({
             "username":"tester"
         })
    });
    //..
Parameters:
Name Type Attributes Default Description
options Object Required. See properties:
Properties
Name Type Attributes Default Description
table String Table name
columns Array Array of column names to update, use with options.values property to specifiy values.
columns Object Or Object where keys are column names and values are values. Note: options.values property not needed.
values Array <optional>
null Array of values used with options.columns (Array) property.
where String <optional>
null where clause sql statement segment (ie: name=? OR id=? )
You may also use Postgresjs#whereHelper
whereParas Array <optional>
null Array of values to replace parameters in where SQL
Not needed if you use whereHelper.
cb Postgresjs~cbOnError <optional>
null Use callback or leave null to use suspend.resume.
Returns cb(err)

whereHelper(variables, defaultLogicopt)

Source:
Builds the where option for use with "where" option in other helpers. See Postgresjs#selectHelper, Postgresjs#deleteHelper, Postgresjs#updateHelper, Postgresjs#mergeHelper.

Example:

    //..
    db.whereHelper({
      "name -like":"%Smith",
      "banned":false
    });
    //..
Parameters:
Name Type Attributes Default Description
variables Object Set keys as column names and values as desired value.
Special flags may be appended to key string:
-like : uses the LIKE comparator
-notlike : uses the NOT LIKE comparator
-not : uses the != comparator
default : uses the = comparator
defaultLogic String <optional>
"AND" logic seperator (ie: OR)
Returns:
object for use with the "where" option in other helpers.

Type Definitions

cbOnEmpty()

Source:
Callback returns no parameters.

cbOnError(err)

Source:
Parameters:
Name Type Description
err Error Returns an error if there was one, or null.

cbOnMerge(err, result)

Source:
Returns the result of the merge.
Parameters:
Name Type Description
err Error An error if there was one, or null.
result String Either "insert" or "update" depending on what was used.

cbOnQuery(err, result)

Source:
Returns the result of the query as an array of rows. Example:
    [
         {id: 1, name: "Bob"},
         {id: 2, name: "John"}
    ]
Parameters:
Name Type Description
err Error An error if there was one, or null.
result Array An array of objects, where each object represents a row, or null.