-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.ls
100 lines (78 loc) · 2.43 KB
/
db.ls
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/**
* user: gisborne
* date: 9/13/14
* time: 16:11
*/
require! pg
require! hstore: 'node-postgres-hstore'
require! Q: q
require! path
require! _: 'prelude-ls'
require! stringify: 'csv-stringify'
require! dbM: './dbModel'
dbModel = dbM.dbModel
pgTypes = pg.types
constring = "postgres://gisborne:@localhost/functional"
#memoizing
model_scopes = {}
with_connection = (handler) ->
deferred = Q.defer()
pg.connect constring, (err, client, done) ->
handler err, client
done
deferred.resolve()
deferred.promise
export params_query = (q, params, handle) ->
with_connection (err, client) ->
client.query q, params, (e, r) ->
raise new Error e if e
handle r
export quick_query = (q, handle) ->
with_connection (err, client) ->
client.query q, (e, r) ->
throw new Error e if e
handle r
export getRelation = (name, handle) ->
params_query "SELECT fields FROM relations WHERE name = $1", [name], handle
export quickInsert = (name, vals, succeed) ->
with_connection (e, client) ->
throw new Error e if e
ks = _.keys vals
stream = client.copyFrom "COPY predicates (id, fields) FROM STDIN WITH CSV"
stream.on 'error', (error) ->
throw new Error error
stringify _.values(vals), (err, output) ->
raise new Error if e
stream.write output
stream.end
succeed()
export quickInsertOne = (name, vals, succeed) ->
with_connection (e, client) ->
ks = _.keys vals
insert_placeholders = (_.map ((x) -> "$#{x}"), [1 to ks.length]) * ','
sql = "INSERT INTO #name(#{ks * ','}) values(#insert_placeholders)"
client.query sql, _.values(vals), (e, r) ->
throw new Error e if e
succeed()
export query = (model, req, handler) ->
quick_query "SELECT * FROM predicates WHERE name = '#model'", handler
#Create a scope object for a model declared in our database
#We use model_scopes to memoize
export getModelScope = (name) ->
handle: (r) ->
r.model_name = name
if (model = model_scopes[name])
model.handle r
else
getRelation name, (result) ->
rows = result.rows
if rows.length > 0
model = new dbModel name, rows[0].fields
model_scopes[name] = model
model.handle r
else
r.call_next
/* required for hstore module */
quick_query "SELECT oid FROM pg_type WHERE typname = 'hstore'", (r) ->
export hstore_oid = r.rows[0].oid
pgTypes.setTypeParser hstore_oid, hstore.parse