Squel – A SQL Query Builder for JavaScript


… Yes! You’ve read correctly. For JavaScript. OK, there has been quite a bit traction around server-side JavaScript through node.js. The brave ones among you brave enough to actually write JavaScript, writing SQL in JavaScript might seem like a good idea, then. So I have discovered this library called squel.js, which has a nice-looking GitHub-style website and a big fat disclaimer almost at the top:

NOTE: It is recommended that you do NOT create queries browser-side to run on the server as this massively increases your exposure to SQL Injection attacks.

Again. If such a disclaimer needs to be added at the top of your website, is it really a good idea to proceed, then? But it may be for the node.js folks. So let’s have a look at the syntax of Squel.

squel.select().from("students")

Does this look familiar? So far, it could also be jOOQ code. With this SQL builder API, you can also create select from derived tables:

alert(
    squel.select()
        .from(squel.select().from('students'), 's')
        .field('s.id')
);
/* SELECT s.id FROM (SELECT * FROM students) `s` */

Or perform JOINs:

alert(
    squel.select()
        .field("students.id")
        .from("students")
        .left_join("teachers", null, 
             "students.id = teachers.student_id")
        .right_join("jailed", "j", 
             "j.student_id = students.id")
);
/*  SELECT students.id FROM students
        LEFT JOIN teachers 
        ON (students.id = teachers.student_id)
        RIGHT JOIN jailed `j` 
        ON (j.student_id = students.id)
*/

Obviously, unlike Java SQL builders, this API is not typesafe, but it’s still interesting to see fluent APIs in other languages as well.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s