Created
March 29, 2015 21:19
-
-
Save danieloneill/2605640f020c89fb806a to your computer and use it in GitHub Desktop.
node.js + nodedbi, convenience methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var dbi = require('nodedbi'); | |
var sql = { | |
query: function( queryStr, args ) | |
{ | |
var q = this.db.query( queryStr, args ); | |
if( !q ) | |
{ | |
console.log( " *** Query Failed: " + this.db.lastError() ); | |
return false; | |
} | |
// For convenience/efficiency, store these: | |
q.rc = q.count(); | |
q.fc = q.fieldCount(); | |
q.fna = []; | |
for( var x=0; x < q.fc; x++ ) | |
{ | |
var fn = q.fieldName(x+1); | |
q.fna.push( fn ); | |
} | |
// Convenient! var rowData = q.row( index ); | |
q.row = function(idx) | |
{ | |
if( idx <= 0 || idx > q.rc ) | |
{ | |
console.log("Row: Out of bounds!"); | |
return false; | |
} | |
q.seek(idx); | |
var result = {}; | |
for( var x=0; x < this.fc; x++ ) | |
{ | |
var v = this.value(x+1); | |
result[ this.fna[x] ] = v; // By field name | |
} | |
return result; | |
}; | |
q.toArray = function() | |
{ | |
var rows = []; | |
if( q.rc == 0 ) | |
return rows; | |
q.seek(1); | |
do | |
{ | |
var result = {}; | |
for( var x=0; x < this.fc; x++ ) | |
{ | |
var v = this.value(x+1); | |
result[ this.fna[x] ] = v; // By field name | |
//result[ x ] = v; // By field index | |
} | |
rows.push(result); | |
} while( q.nextRow() ); | |
return rows; | |
}; | |
return q; | |
}, | |
lastInsertId: function() { return this.db.lastInsertId(); } | |
}; | |
module.exports = sql; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment