forked from JerrySievert/mongolike
-
Notifications
You must be signed in to change notification settings - Fork 0
/
save.sql
28 lines (22 loc) · 847 Bytes
/
save.sql
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
CREATE OR REPLACE FUNCTION save(collection varchar, data json) RETURNS
BOOLEAN AS $$
var obj = JSON.parse(data);
var id = obj._id;
// if there is no id, naively assume an insert
if (id === undefined) {
var seq = plv8.prepare("SELECT nextval('seq_col_" + collection + "') AS id");
var rows = seq.execute([ ]);
id = rows[0].id;
obj._id = id;
seq.free();
var insert = plv8.prepare("INSERT INTO col_" + collection +
" (col_" + collection + "_id, data) VALUES ($1, $2)", [ 'int', 'json']);
insert.execute([ id, JSON.stringify(obj) ]);
insert.free();
} else {
var update = plv8.prepare("UPDATE col_" + collection +
" SET data = $1 WHERE col_" + collection + "_id = $2", [ 'json', 'int' ]);
update.execute([ data, id ]);
}
return true;
$$ LANGUAGE plv8 IMMUTABLE STRICT;