-
Notifications
You must be signed in to change notification settings - Fork 9
/
functions.sql
235 lines (194 loc) · 5.93 KB
/
functions.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
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
CREATE OR REPLACE FUNCTION mongres_find(collection text, terms json, lim int, skip int) RETURNS json[] AS $$
if (/\.\$cmd$/.test(collection)) {
// for now...
return [];
}
var sql = "SELECT data FROM " + collection;
var where_clause = plv8.find_function("mongres_where_clause");
var where = where_clause(terms);
sql += " " + where.sql;
if (lim > -1 )
{
sql += "limit " + lim;
}
if (skip > 0)
{
sql += "offset " + skip;
}
try {
plv8.subtransaction(function(){
var plan = plv8.prepare(sql, where.types);
rows = plan.execute(where.binds);
plan.free();
});
}
catch(err) {
if (err=='Error: relation "' + collection + '" does not exist')
{
rows = []
}
}
var ret = [ ];
for (var i = 0; i < rows.length; i++) {
ret.push(rows[i].data);
}
return ret;
$$ LANGUAGE plv8;
CREATE OR REPLACE FUNCTION mongres_find_in_obj(data json, key varchar) RETURNS
VARCHAR AS $$
var obj = data;
var parts = key.split('.');
var part = parts.shift();
while (part && (obj = obj[part]) !== undefined) {
part = parts.shift();
}
return obj;
$$ LANGUAGE plv8 IMMUTABLE STRICT;
CREATE OR REPLACE FUNCTION mongres_find_in_obj_int(data json, key varchar) RETURNS
INT AS $$
var obj = data;
var parts = key.split('.');
var part = parts.shift();
while (part && (obj = obj[part]) !== undefined) {
part = parts.shift();
}
return Number(obj);
$$ LANGUAGE plv8 IMMUTABLE STRICT;
CREATE OR REPLACE FUNCTION mongres_find_in_obj_exists(data json, key varchar) RETURNS
BOOLEAN AS $$
var obj = data;
var parts = key.split('.');
var part = parts.shift();
while (part && (obj = obj[part]) !== undefined) {
part = parts.shift();
}
return (obj === undefined ? 'f' : 't');
$$ LANGUAGE plv8 IMMUTABLE STRICT;
CREATE OR REPLACE FUNCTION mongres_where_clause (terms json) RETURNS
VARCHAR AS $$
var sql = '';
var c = [ ];
var t = [ ];
var b = [ ];
var count = 1;
function build_clause (key, value, type) {
var clauses = [ ],
binds = [ ],
types = [ ];
if (typeof(value) === 'object') {
if (key === '$or') {
var tclauses = [ ];
for (var i = 0; i < value.length; i++) {
var ret = build_clause(Object.keys(value[i])[0], value[i][Object.keys(value[i])[0]]);
tclauses = tclauses.concat(ret.clauses);
binds = binds.concat(ret.binds);
types = types.concat(ret.types);
}
clauses.push('( ' + tclauses.join(' OR ') + ' )');
} else {
var keys = Object.keys(value);
for (var i = 0; i < keys.length; i++) {
var ret;
if (keys[i] === '$gt') {
ret = build_clause(key, value[keys[i]], '>');
} else if (keys[i] === '$lt') {
ret = build_clause(key, value[keys[i]], '<');
} else if (keys[i] === '$gte') {
ret = build_clause(key, value[keys[i]], '>=');
} else if (keys[i] === '$lte') {
ret = build_clause(key, value[keys[i]], '<=');
} else if (keys[i] === '$exists') {
ret = build_clause(key, value[keys[i]], 'exists');
}
clauses = clauses.concat(ret.clauses);
binds = binds.concat(ret.binds);
types = types.concat(ret.types);
}
}
} else {
type = type || '=';
var lval;
if (type === 'exists') {
clauses.push("mongres_find_in_obj_exists(data, '" + key + "') = $" + count);
types.push('boolean');
value = value ? 't' : 'f';
} else {
switch (typeof(value)) {
case 'number':
clauses.push("mongres_find_in_obj_int(data, '" + key + "') " + type + " $" + count);
types.push('int');
break;
case 'string':
clauses.push("mongres_find_in_obj(data, '" + key + "') " + type + " $" + count);
types.push('varchar');
break;
default:
console.log("unknown type: " + typeof(value));
}
}
binds.push(value);
count++;
}
return { clauses: clauses, binds: binds, types: types };
}
if (terms !== undefined) {
var obj = terms; //JSON.parse(terms);
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i ++) {
var ret = build_clause(keys[i], obj[keys[i]]);
c = c.concat(ret.clauses);
b = b.concat(ret.binds);
t = t.concat(ret.types);
}
if (c.length) {
sql += " WHERE ";
sql += c.join(" AND ");
}
}
// return JSON.stringify({ types: t, binds: b, sql: sql });
return { types: t, binds: b, sql: sql };
$$ LANGUAGE plv8 STRICT;
CREATE OR REPLACE FUNCTION mongres_insert(collection text, docs json) RETURNS int AS $$
var names = collection.split(".");
var schema = names[0], table = names[1];
var count = plv8.execute(
"SELECT count(*) FROM pg_namespace WHERE nspname = $1",
[schema]).shift().count;
if (count == 0) {
plv8.execute(
"CREATE SCHEMA " + schema);
}
var count = plv8.execute(
"SELECT count(*) FROM pg_class" +
" INNER JOIN pg_namespace ON pg_namespace.oid = relnamespace" +
" WHERE nspname = $1 AND relname = $2", [schema, table]).shift().count;
if (count == 0) {
plv8.execute(
"CREATE TABLE " + collection +
" (id varchar primary key, data json)");
}
for (var i = 0; i < docs.length; i++) {
var elm = docs[i];
// Since BSON misses top-level Array definition, elm is always an
// object, but could be an array. Sigh, just convert it...
var ary = [elm];
if ("0" in elm) {
for (var key in elm) {
ary[key - 0] = elm[key];
}
}
for (var j = 0; j < ary.length; j++) {
var doc = ary[j];
var id = doc._id;
if (id == void 0) {
id = plv8.execute(
"SELECT substring(md5(random()::text), 1, 24) as id").shift().id;
doc._id = id;
}
plv8.execute(
"INSERT INTO " + collection + " VALUES($1, $2)", [id, doc]);
}
}
// OidFunctionCall does not like NULL output
return 0;
$$ LANGUAGE plv8;