-
Notifications
You must be signed in to change notification settings - Fork 8
/
db.js
78 lines (62 loc) · 1.59 KB
/
db.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
var pg = require('pg');
var conn = process.env.HEROKU_POSTGRESQL_BLUE_URL||"tcp://postgres:root@localhost/postgres";
var client = new pg.Client(conn);
client.connect();
console.log("Connected to POSTGRESQL " + conn);
module.exports = new (function(){
// Extend the default database
this.query = function(){
client.query.apply(client, arguments);
};
// default table
this.table = '';
this.insert = function(data,callback){
var keys = [],
values = [],
temp = [],
i=1;
for(var x in data){
keys.push(x);
temp.push('$'+ i++);
values.push(data[x]);
}
var sql = 'INSERT INTO '+ this.table + '('+ keys.join(',') +') VALUES( ' + temp.join(',') + ' ) RETURNING *';
console.log(sql);
this.query(sql, values, function(err,result){
callback(err,result);
});
};
this.update = function(data,cond,callback){
var set = [],
values = [],
where = [],
i=1;
for(var x in data){
set.push(x + " = $" + i++);
values.push(data[x]);
}
for(var x in cond){
where.push(x + " = $" + i++);
values.push(cond[x]);
}
var sql = 'UPDATE '+ this.table + ' SET '+ set.join(',') +' WHERE ' + where.join(' AND ');
console.log(sql);
this.query(sql, values, function(err,result){
callback(err,result);
});
};
this.delete = function(cond, callback){
var values = [],
where = [],
i=1;
for(var x in cond){
where.push(x + " = $" + i++);
values.push(cond[x]);
}
var sql = 'DELETE FROM '+ this.table + ' WHERE ' + where.join(' AND ');
console.log(sql);
this.query(sql, values, function(err,result){
callback(err,result);
});
};
})();