Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Dan Harbin committed Mar 21, 2013
0 parents commit ff4a824
Show file tree
Hide file tree
Showing 8 changed files with 314 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .gitignore
@@ -0,0 +1,5 @@
.DS_Store
node_modules
npm_debug.log
.vagrant
*.swp
3 changes: 3 additions & 0 deletions .gitmodules
@@ -0,0 +1,3 @@
[submodule "lib/swig"]
path = lib/swig
url = git://github.com/paularmstrong/swig.git
19 changes: 19 additions & 0 deletions LICENSE
@@ -0,0 +1,19 @@
Copyright (c) 2013 Civitas Learning Inc

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
125 changes: 125 additions & 0 deletions README.md
@@ -0,0 +1,125 @@
# swigql

[swig](https://github.com/paularmstrong/swig) templating for SQL

## Installation

npm install swigql

## Examples

### Template code

```
SELECT
id
, first_name
, last_name
FROM person
WHERE
first_name = {% bind fn %}
AND (
{%- for ln in last_names -%}
{% if loop.index > 1 %}OR {% endif %}{% bind ln %}
{% endfor -%}
)
```

### node.js code

```javascript
var swigql = require('swigql');

var tmpl = swigql.compileFile('/path/to/template.html');
var results = tmpl.render({
fn: 'James',
last_names: ['Franklin', 'Cooper', 'Smitty', 'Black']
});

console.log(results);
```

### Output

```
[ 'SELECT\n id\n , first_name\n , last_name\nFROM person\nWHERE\n first_name = $1\n AND ($2\n OR $3\n OR $4\n OR $5\n )',
[ 'James', 'Franklin', 'Cooper', 'Smitty', 'Black' ] ]
```

## Notes

swigql is simply a wrapper around swig with two differences:

1. swigql adds a custom tag to swig named `bind`. This tag will substitute the
variable with the appropriate positional parameter (ex. $1).

2. Instead of returning just the output of the template, it also returns the
bind parameters in an array suitable for passing to a database driver such
as [node-postgres](https://github.com/brianc/node-postgres/wiki/pg).

Bringing some powerful features of swig templating, such as [template
inheritance](http://paularmstrong.github.com/swig/docs/#inheritance) opens the
door for some interesting possibilities for writing reusable sql queries. For
example, you could have a base query that you can extend to add more fields to
the SELECT, or more conditions to the WHERE clause.

### Example base query template

```
SELECT
{% block select %}
id
{% endblock %}
FROM tbl
{% block joins %}
{% endblock %}
WHERE 1=1
{% block where %}
{% endblock %}
```

### Example sub query template

```
{% extends 'base.html' %}
{% block select %}
{% parent %}
, my_fk
{% endblock %}
{% block joins %}
{% parent %}
INNER JOIN other_tbl USING (my_fk)
{% endblock %}
{% block where %}
AND my_fk = {% bind myVal %}
{% endblock %}
```

## See also

[swig](https://github.com/paularmstrong/swig)

## License

Copyright (c) 2013 Civitas Learning Inc

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
65 changes: 65 additions & 0 deletions lib/index.js
@@ -0,0 +1,65 @@
/*
* swigql
* Copyright (c) 2013 Civitas Learning Inc
* MIT Licensed
*/

/** @module swigql */

var swig = require('./swig/lib/swig.js');
var helpers = require('./swig/lib/helpers');
var _ = require('underscore');

/* Add a "bind" tag to swig */
var tags = {
bind: function (indent, parser) {
var myArg = parser.parseVariable(this.args[0]);
return helpers.setVar('__myArg', myArg)
+ 'o = _ext.swigql;'
+ 'if (! o.argMap.hasOwnProperty(__myArg)) {'
+ ' o.counter++;'
+ ' o.argMap[__myArg] = o.counter;'
+ ' o.bind[o.counter - 1] = __myArg;'
+ '}'
+ '_output += "$" + o.argMap[__myArg];';
}
};
tags.bind.ends = false; // No need to close the tag, just {% bind var %} will suffice.

// create an extension that can map named-variables to bind variables
var extensions = {
swigql: {}
};

// configure swig
var config = {
tags: tags,
extensions: extensions
};
swig.init(config);

/** wrap swig's init */
exports.init = function (options) {
var opts = _.extend({}, options, config);
swig.init(opts);
};

// wrap the render method to return the sql text AND the bind values
var wrap = function (render, source, options) {
extensions.swigql = { bind: [], argMap: {}, counter: 0 };
var txt = render.call(undefined, source, options);
var bind = extensions.swigql.bind;
return [txt, bind];
};

// inject a new render method onto the template
var inject = function (template) {
template.render = _.wrap(template.render, wrap);
return template;
};

/** wrap swig's compileFile */
exports.compileFile = _.compose(inject, swig.compileFile);

/** wrap swig's compile */
exports.compile = _.compose(function (r) { return _.wrap(r, wrap); }, swig.compile);
1 change: 1 addition & 0 deletions lib/swig
Submodule swig added at 4ad0b8
32 changes: 32 additions & 0 deletions package.json
@@ -0,0 +1,32 @@
{
"name": "swigql",
"version": "0.0.1",
"description": "swig templating for SQL",
"contributors": [
{
"name": "Dan Harbin",
"web": "https://github.com/RasterBurn"
}
],

"keywords": [
"postgres",
"pg",
"swig",
"template",
"sql"
],
"author": "Dan Harbin <dan.harbin@civitaslearning.com>",
"main": "./lib",
"repository": {
"type": "git",
"url": "https://github.com/civitaslearning/swigql.git"
},
"dependencies": {
"underscore": "~1.4.4"
},
"devDependencies": {
"nodeunit": "*"
},
"license": "MIT"
}
64 changes: 64 additions & 0 deletions test/test.js
@@ -0,0 +1,64 @@
var swigql = require('../lib/index.js');

swigql.init({
root: '.',
allowErrors: true
});


exports["simple replacement"] = function (test) {
test.expect(2);
var txt = 'x {% bind test1 %} y',
render = swigql.compile(txt, { filename: 'simple_replacement.sql' }),
results = render({ test1: 'works' });

test.strictEqual(results[0], 'x $1 y');
test.deepEqual(results[1], ['works']);

test.done();
};

exports["repeated replacement"] = function (test) {
test.expect(2);

var txt = 'x {% bind test1 %} {% bind test1 %} y',
render = swigql.compile(txt, { filename: 'repeated_replacement.sql' }),
results = render({ test1: 'works' });

test.strictEqual(results[0], 'x $1 $1 y');
test.deepEqual(results[1], ['works']);

test.done();
};

exports["multi replacement"] = function (test) {
test.expect(2);

var txt = 'x {% bind test1 %} {% bind test2 %} y',
render = swigql.compile(txt, { filename: 'multi_replacement.sql' }),
results = render({ test1: 'works', test2: 'also' });

test.strictEqual(results[0], 'x $1 $2 y');
test.deepEqual(results[1], ['works', 'also']);

test.done();
};

exports["repeated use"] = function (test) {
test.expect(4);

var txt = 'x {% bind test1 %} y',
render = swigql.compile(txt, { filename: 'repeated_use.sql' }),
results = render({ test1: 'works' });

test.strictEqual(results[0], 'x $1 y');
test.deepEqual(results[1], ['works']);

results = render({ test1: 'again' });

test.strictEqual(results[0], 'x $1 y');
test.deepEqual(results[1], ['again']);

test.done();

};

0 comments on commit ff4a824

Please sign in to comment.