Created
March 29, 2015 22:01
-
-
Save danieloneill/d069be8e02e852008cbd to your computer and use it in GitHub Desktop.
Nodejs + libdbi + paging results
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 LibDBI = require('nodedbi'); | |
var db = LibDBI.DBConnection({'type':'mysql', 'dbname':'mysql', 'username':'root'}); | |
function getResultHandle(query, args) | |
{ | |
var q = db.query(query, args); | |
if( !q ) | |
{ | |
console.log( "Query error: " + db.lastError() ); | |
return false; | |
} | |
q.getRows = function(start, end) | |
{ | |
var rows = []; | |
var rowCount = this.count(); | |
var colCount = this.fieldCount(); | |
if( !end ) | |
end = start; | |
if( start < 1 || start > rowCount ) | |
{ | |
console.log( "getRows(): 'start' is outside of valid result range!"); | |
return false; | |
} | |
if( end < 1 || end > rowCount ) | |
{ | |
console.log( "getRows(): 'end' is outside of valid result range!"); | |
return false; | |
} | |
if( start > end ) | |
{ | |
console.log( "getRows(): for now, 'start' must be a lower index than 'end'"); | |
return false; | |
} | |
for( var x=start; x <= end; x++ ) | |
{ | |
if( !this.seek(x) ) | |
{ | |
console.log( "getRows(): seek failed at index "+x); | |
return false; | |
} | |
var row = []; | |
for( var y=1; y <= colCount; y++ ) | |
row.push( this.value(y) ); | |
rows.push( row ); | |
} | |
return rows; | |
} | |
return q; | |
} | |
var q = getResultHandle("SELECT * FROM user"); | |
var rowCount = q.count(); | |
// Store q somewhere, it takes very little RAM. | |
// Eventually you may want a row, in this case the second: | |
// Methods on the handle need not be prototype or wrapped members. It can also be done procedurally. | |
// I prefer this method since the method conveniently follows the handle: | |
var row = q.getRows(2); | |
console.log( JSON.stringify(row, null, 2) ); | |
// Handle is destroyed when it goes out of scope, or you can destroy it manually: | |
delete q; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment