Wednesday, 4 March, 2015 UTC


Summary

If you've read some of my other posts you'll know that I don't really like full blown ORMs. They take too much away and give back so little. I'm just not that averse to writing SQL.
It turns out I'm not the only one, Rob Conery, has been telling ORMs to get off his lawn just lately, and I've been quietly watching and eating popcorn in amusement.
Today he announced a new version of his totally-not-an-orm MassiveJS. I've been messing with it, and I love it, and I want to write about it now.
Disclaimer: This is still in pre-alpha, it might change quite a lot in the future.
Let's write some queries against the dvdrental database thats floating around on the interweb.
SELECT * FROM Actor LIMIT 10;   
I know, its so complex!
I'm going to save this in a folder called db. Note that I'm giving it this filename: topTenActors.sql (this is important)
Okay, grabbing massive from Github (the v2 branch) I can require it in my app.js file, and write out the usual postgresql connection string:
var massive = require('massive');
var dbConnection = "postgres://<user>@localhost/dvdrental";
Next I need to flex massive to get me a db object, telling it the connection string and where my queries are:
massive.connect({
    connectionString: dbConnection,
    scripts: './db'
}, function (err, db) {
    // query magic here    
}
Now for the MIND BLOW.
I can call my SQL file as if it were a function, right here, in JavaScript.
massive.connect({
    connectionString: dbConnection,
    scripts: './db'
}, function (err, db) {
    // query magic here 
    db.topTenActors(function (err, actors) {
        console.log(actors);
    });
}
... and it works, it returns the data from the query.
If you need to parametize your queries, well, it's got you covered...
I'll name this file actorById.sql and put it in the db folder with the other one.
SELECT * FROM actor WHERE actor_id = $1;
...and then connect to the database and run it as a function
massive.connect({
    connectionString: dbConnection,
    scripts: './db'
}, function (err, db) {
    // query magic here 
    db.actorById("10", function (err, actor) {
        if(err) throw err;
        console.log(actor);
    });
}
This returns just the one actor where the ID is 10, just like the SQL foretold!
Running SQL files as functions! Madness! Why didn't I think of this? I'm probably more exited about this than I should be.
You can check out the new version of massive on github, under the v2 branch. I highly suggest you do, it actually does a lot more than what I've shown here. This was just the feature I got most exited about.