Skip to content

Commit

Permalink
Merge pull request #3 from vitaly-t/v.0.2
Browse files Browse the repository at this point in the history
V.0.2
  • Loading branch information
vitaly-t committed Mar 6, 2015
2 parents 4e1cc67 + f809ab3 commit 0b1e627
Show file tree
Hide file tree
Showing 3 changed files with 382 additions and 328 deletions.
57 changes: 34 additions & 23 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,17 @@ $ npm install pg-promise

### 1. Load the library
```javascript
var pgpLib = require('pg-promise');
var pgpLib = require('pg-promise'); // loading the library;
```
### 2. Configure database connection
Use one of the two ways to specify connection:
### 2. Initialize the library
```javascript
var pgp = pgpLib(/*options*/); // initializing the library, with optional global settings;
```
You can pass additional ```options``` parameter when initilizing the library (see chapter Advanced for details).

<b>NOTE:</b> Only one instance of such ```pgp``` object should exist throughout the application.
### 3. Configure database connection
Use one of the two ways to specify connection details:
* Configuration object:
```javascript
var cn = {
Expand All @@ -35,19 +42,23 @@ var cn = "postgres://username:password@host:port/database";
This library doesn't use any of the connection's details, it simply passes them on to [PG] when opening a new connection.
For more details see [ConnectionParameters] class in [PG], such as additional connection properties supported.

### 3. Initialize the library
### 4. Instantiate your database
```javascript
var pgp = pgpLib(cn);
var db = new pgp(cn); // create a new database instance based on the connection details
```
NOTE: Only one global instance should be used throughout the application.
There can be multiple database objects instantiated in the application from different connection details.

See also chapter <b>Advanced</b> for the use of parameter ```options``` during initialization. But for now you are ready to use the library.
You are now ready to make queries against the database.

# Usage
### The basics
In order to eliminate the chances of unexpected query results and make code more robust, each request is parametrized with the expected/supported
<i>Query Result Mask</i>, using type ```queryResult``` as shown below:
```javascript
///////////////////////////////////////////////////////
// Query Result Mask flags;
//
// Any combination is supported, except for one + many.
queryResult = {
one: 1, // single-row result is expected;
many: 2, // multi-row result is expected;
Expand All @@ -56,18 +67,17 @@ queryResult = {
```
In the following generic-query example we indicate that the call can return any number of rows:
```javascript
pgp.query("select * from users", queryResult.none | queryResult.many);
db.query("select * from users", queryResult.none | queryResult.many);
```
which is equivalent to calling:
```javascript
pgp.manyOrNone("select * from users");
db.manyOrNone("select * from users");
```

This usage pattern is facilitated through result-specific methods that can be used instead of the generic query:
```javascript
pgp.many("select * from users"); // one or more records are expected
pgp.one("select * from users limit 1"); // one record is expected
pgp.none("update users set active=TRUE where id=1"); // no records expected
db.many("select * from users"); // one or more records are expected
db.one("select * from users limit 1"); // one record is expected
db.none("update users set active=TRUE where id=1"); // no records expected
```
The mixed-result methods are:
* ```oneOrNone``` - expects 1 or 0 rows to be returned;
Expand All @@ -76,7 +86,7 @@ The mixed-result methods are:
Each of the query calls returns a [Promise] object, as shown below, to be used in the standard way.
And when the expected and actual results do not match, the call will be rejected.
```javascript
pgp.many("select * from users")
db.many("select * from users")
.then(function(data){
console.log(data); // printing the data returned
}, function(reason){
Expand All @@ -89,7 +99,7 @@ In PostgreSQL stored procedures are just functions that usually do not return an
Suppose we want to call function ```findAudit``` to find audit records by <i>user id</i> and maximum timestamp.
We can make such call as shown below:
```javascript
pgp.func('findAudit', [123, new Date()])
db.func('findAudit', [123, new Date()])
.then(function(data){
console.log(data); // printing the data returned
}, function(reason){
Expand All @@ -99,7 +109,7 @@ pgp.func('findAudit', [123, new Date()])
We passed it <i>user id</i> = 123, plus current Date/Time as the timestamp. We assume that the function signature matches the parameters that we passed.
All values passed are serialized automatically to comply with PostgreSQL type formats.

And when you are not expecting any return results, call ```pgp.proc``` instead. Both methods return a [Promise] object.
And when you are not expecting any return results, call ```db.proc``` instead. Both methods return a [Promise] object.

### Transactions
Every call shown in chapters above would acquire a new connection from the pool and release it when done. In order to execute a transaction on the same
Expand All @@ -109,7 +119,7 @@ Example:
```javascript
var promise = require('promise');

var tx = new pgp.tx(); // creating a new transaction object
var tx = new db.tx(); // creating a new transaction object

tx.exec(function(/*client*/){

Expand All @@ -133,7 +143,7 @@ we want both queries inside the transaction to resolve before executing a <i>COM

<b>Notes</b>
* While inside a transaction, we make calls to the same-named methods as outside of transactions, except we do it on the transaction object instance now,
as opposed to the global ```pgp``` object, which gives us access to the shared connection object. The same goes for calling functions and procedures within
as opposed to the database object ```db```, which gives us access to the shared connection object. The same goes for calling functions and procedures within
transactions, using ```tx.func``` and ```tx.proc``` accordingly.
* Just for flexibility, the transaction call-back function takes parameter ```client``` - the connection object.

Expand All @@ -149,7 +159,7 @@ pgp.as.text(value); // returns proper PostgreSQL text presentation,
pgp.as.date(value); // returns proper PostgreSQL date/time presentation,
// wrapped in quotes.
```
As these helpers are not associated with a connection, and thus can be called from anywhere.
As these helpers are not associated with a database, they can be called from anywhere.

# Advanced

Expand All @@ -166,7 +176,7 @@ var options = {
console.log("Disconnected from database '" + cp.database + "'");
}
};
var pgp = pgpLib(cn, options);
var pgp = pgpLib(options);
```
Two events supported at the moment - ```connect``` and ```disconnect```, to notify of virtual connections being established or released accordingly.
Each event takes parameter ```client```, which is the client connection object. These events are mostly for connection monitoring, while debugging your application.
Expand All @@ -185,13 +195,13 @@ doing it for you automatically.

Usage example:
```javascript
pgp.connect().then(function(db){
db.connect().then(function(info){
// connection was established successfully;

// do stuff with the connection object (db.client) and/or queries;
// do stuff with the connection object (info.client) and/or queries;

// when done with all the queries, call done():
db.done();
info.done();

}, function(reason){
// failed to connect;
Expand All @@ -201,6 +211,7 @@ pgp.connect().then(function(db){
<b>NOTE:</b> When using the direct connection, events ```connect``` and ```disconnect``` won't be fired.

# History
* Version 0.2.0 introduced on March 6th, 2015, supporting multiple databases
* A refined version 0.1.4 released on March 5th, 2015.
* First solid Beta, 0.1.2 on March 4th, 2015.
* It reached first Beta version 0.1.0 on March 4th, 2015.
Expand Down
Loading

0 comments on commit 0b1e627

Please sign in to comment.