Skip to content
This repository has been archived by the owner on Nov 9, 2017. It is now read-only.

fix getLastInsertId() for postgres #22

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions lib/adapters/adapter--pg.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,12 @@ Adapter.prototype.query = function( sql, bind, callback )
var origSql = sql;
sql = this.ensureStandardSql(sql);
sql = this._format(sql, bind);
if ( sql.substr(0,6).toLowerCase() === 'insert' ) {
var isInsert = true;
if (sql.substr(sql.length - 15).toLowerCase().indexOf('returning id') === -1) {
sql += ' RETURNING id';
}
}
if( this._debug )
console.log('sql='+sql);

Expand Down Expand Up @@ -165,8 +171,9 @@ Adapter.prototype.query = function( sql, bind, callback )
else
{

//if( this.lastID && ! isNaN(this.lastID) && this.lastID>0 )
// me._lastInsertId = this.lastID;
if( isInsert && res.rows[0] && res.rows[0].id && !isNaN(res.rows[0].id) && res.rows[0].id>0 ) {
me._lastInsertId = res.rows[0].id;
}

// TODO could save OID here

Expand Down
6 changes: 1 addition & 5 deletions test/adapters-simple-operations.js
Original file line number Diff line number Diff line change
Expand Up @@ -224,10 +224,6 @@ var adapterTestSuite = function (adapterName) {
});

it('should be able to retrieve the last inserted id', function () {
// pg doesn't support getLastInsertId()
if (-1 < adapterName.indexOf('pg')) {
return;
}
expect(dbWrapper.getLastInsertId()).to.equal(2);
});

Expand Down Expand Up @@ -346,4 +342,4 @@ describe('PgSQL adapter', function () {

// ------------------------------------------ end tests

// vim: ts=2 sw=2 et
// vim: ts=2 sw=2 et