1 |
|
2 | module.exports = function(cb){
|
3 |
|
4 | var createURL = function(conf){
|
5 | var cr = "";
|
6 | if(conf.username && conf.password) cr = conf.username+":"+conf.password+"@";
|
7 | return "postgres://"+cr+(conf.host||"localhost")+":"+(conf.port||"5432")+"/"+(conf.database||conf.db);
|
8 | };
|
9 |
|
10 | var _ = require("underscore");
|
11 | var env = this;
|
12 | var config = this.config;
|
13 |
|
14 | if(!config.postgres) return cb();
|
15 | var pg = require("pg");
|
16 | var connectURL = createURL(config.postgres);
|
17 | pg.connect(connectURL, function(err, client, release) {
|
18 | if(err) return cb(err);
|
19 | client.format = queryFormat;
|
20 | env.engines.postgres = client;
|
21 | env.engines.postgres.release = release;
|
22 | env.i.do("log.sys", "postgres", "Connected to PostgreSQL on "+(config.postgres.host || "localhost")+":"+(config.postgres.port||5432)+"/"+(config.postgres.database||config.postgres.db) );
|
23 | cb();
|
24 | });
|
25 |
|
26 |
|
27 | function queryFormat(template, data){
|
28 | if (!data) return template;
|
29 | var self = this;
|
30 |
|
31 | if(data.options) template = template.replace(/(@\w+)/g, function (txt, key){
|
32 | key = key.slice(1);
|
33 | if(data.options.hasOwnProperty(key)) {
|
34 | return data.options[key];
|
35 | }
|
36 | return txt;
|
37 | });
|
38 |
|
39 | if(data.options) template = template.replace(/(%\w+)/g, function (txt, key){
|
40 | key = key.slice(1);
|
41 | if(data.options.hasOwnProperty(key)) {
|
42 | if(typeof data.options[key] === "function") {return self.escapeIdentifier(data.options[key].call(data.context,data.values, data.options));}
|
43 | else if(data.options[key] === "" || typeof data.options[key] === "undefined") return "";
|
44 | else if(key === "fields" && data.options[key] === "*") return "*";
|
45 | else {
|
46 | return Array.isArray(data.options[key])?
|
47 | data.options[key].map(function(identifier){return identifier.split(".")}).map(function(identifier_parts){
|
48 | return identifier_parts.map(self.escapeIdentifier).join(".");
|
49 | }).join(",") : data.options[key].split(".").map(self.escapeIdentifier).join(".");
|
50 | }
|
51 | }
|
52 | return txt;
|
53 | });
|
54 |
|
55 | if(data.values) template = template.replace(/([#]\w+)/g, function (txt, key){
|
56 | key = key.slice(1);
|
57 | if(data.values.hasOwnProperty(key)){
|
58 | return Array.isArray(data.values[key])?data.values[key].map(function(v){return v.toString();}).map(self.escapeLiteral).join(","):self.escapeLiteral(data.values[key].toString());
|
59 | }
|
60 | return txt;
|
61 | });
|
62 |
|
63 | return template;
|
64 |
|
65 |
|
66 | }
|
67 |
|
68 |
|
69 |
|
70 | };
|