This repository has been archived by the owner on Dec 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plv8_func.cc
293 lines (255 loc) · 5.95 KB
/
plv8_func.cc
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
/*
* plv8_func.cc : PL/v8 built-in functions.
*/
#include "plv8.h"
#include <sstream>
extern "C" {
#define delete delete_
#define namespace namespace_
#define typeid typeid_
#define typename typename_
#define using using_
#include "catalog/pg_type.h"
#include "executor/spi.h"
#include "utils/builtins.h"
#undef delete
#undef namespace
#undef typeid
#undef typename
#undef using
} // extern "C"
using namespace v8;
static Handle<v8::Value> PrintInternal(const Arguments& args);
static Handle<v8::Value> ExecuteSqlInternal(const Arguments& args);
static Handle<v8::Value> ExecuteSqlWithArgs(const Arguments& args);
static Handle<v8::Value> YieldInternal(const Arguments& args);
/*
* v8 is not exception-safe! We cannot throw C++ exceptions over v8 functions.
* So, we catch C++ exceptions and convert them to JavaScript ones.
*/
static Handle<v8::Value>
SafeCall(InvocationCallback fn, const Arguments& args) throw()
{
HandleScope handle_scope;
MemoryContext ctx = CurrentMemoryContext;
try
{
return fn(args);
}
catch (js_error& e)
{
return ThrowError("internal exception");
}
catch (pg_error& e)
{
MemoryContextSwitchTo(ctx);
ErrorData *edata = CopyErrorData();
Handle<String> message = ToString(edata->message);
// XXX: add other fields? (detail, hint, context, internalquery...)
FlushErrorState();
FreeErrorData(edata);
return ThrowException(Exception::Error(message));
}
}
Handle<v8::Value>
Print(const Arguments& args) throw()
{
return SafeCall(PrintInternal, args);
}
static Handle<v8::Value>
PrintInternal(const Arguments& args)
{
if (args.Length() < 2)
return ThrowError("usage: print(elevel, ...)");
int elevel = args[0]->Int32Value();
switch (elevel)
{
case DEBUG5:
case DEBUG4:
case DEBUG3:
case DEBUG2:
case DEBUG1:
case LOG:
case INFO:
case NOTICE:
case WARNING:
break;
default:
return ThrowError("invalid error level for print()");
}
if (args.Length() == 2)
{
// fast path for single argument
elog(elevel, "%s", CString(args[1]).str(""));
}
else
{
std::ostringstream stream;
for (int i = 1; i < args.Length(); i++)
{
if (i > 1)
stream << ' ';
stream << CString(args[i]);
}
elog(elevel, "%s", stream.str().c_str());
}
return Undefined();
}
Handle<v8::Value>
ExecuteSql(const Arguments& args) throw()
{
if (args.Length() != 1 && (args.Length() != 2 || !args[1]->IsArray()))
return ThrowError("usage: executeSql(sql [, args])");
Handle<v8::Value> result;
SPI_connect();
if (args.Length() == 1)
result = SafeCall(ExecuteSqlInternal, args);
else
result = SafeCall(ExecuteSqlWithArgs, args);
SPI_finish();
return result;
}
static Handle<v8::Value>
SPIResultToValue(int status)
{
Handle<v8::Value> result;
if (status < 0)
return ThrowError("SPI failed");
switch (status)
{
case SPI_OK_SELECT:
case SPI_OK_INSERT_RETURNING:
case SPI_OK_DELETE_RETURNING:
case SPI_OK_UPDATE_RETURNING:
{
int nrows = SPI_processed;
Converter conv(SPI_tuptable->tupdesc);
Handle<Array> rows = Array::New(nrows);
for (uint32 r = 0; r < nrows; r++)
rows->Set(r, conv.ToValue(SPI_tuptable->vals[r]));
result = rows;
break;
}
default:
result = Int32::New(SPI_processed);
break;
}
return result;
}
/*
* executeSql(string sql) returns array<json> for query, or integer for command.
*/
static Handle<v8::Value>
ExecuteSqlInternal(const Arguments& args)
{
SPI_connect();
int status;
CString sql(args[0]);
PG_TRY();
{
status = SPI_exec(sql, 0);
}
PG_CATCH();
{
throw pg_error();
}
PG_END_TRY();
return SPIResultToValue(status);
}
static Handle<v8::Value>
ExecuteSqlWithArgs(const Arguments& args)
{
int status;
CString sql(args[0]);
Handle<Array> array = Handle<Array>::Cast(args[1]);
int nargs = array->Length();
Datum *values = (Datum *) palloc(sizeof(Datum) * nargs);
char *nulls = (char *) palloc(sizeof(char) * nargs);
Oid *argtypes = (Oid *) palloc(sizeof(Oid) * nargs);
memset(nulls, ' ', sizeof(char) * nargs);
for (int i = 0; i < nargs; i++)
{
Handle<v8::Value> value = array->Get(i);
if (value->IsNull() || value->IsUndefined())
{
nulls[i] = 'n';
argtypes[i] = TEXTOID;
}
else if (value->IsBoolean())
{
values[i] = BoolGetDatum(value->ToBoolean()->Value());
argtypes[i] = BOOLOID;
}
else if (value->IsInt32())
{
values[i] = Int32GetDatum(value->ToInt32()->Value());
argtypes[i] = INT4OID;
}
else if (value->IsUint32())
{
values[i] = Int64GetDatum(value->ToUint32()->Value());
argtypes[i] = INT8OID;
}
else if (value->IsNumber())
{
values[i] = Float8GetDatum(value->ToNumber()->Value());
argtypes[i] = FLOAT8OID;
}
else if (value->IsDate())
{
// TODO: Date
return ThrowError("Date is not supported as arguments for executeSql()");
}
else if (value->IsObject())
{
// TODO: Object
return ThrowError("Object is not supported as arguments for executeSql()");
}
else if (value->IsArray())
{
// TODO: Array
return ThrowError("Array is not supported as arguments for executeSql()");
}
else
{
CString str(value);
values[i] = CStringGetTextDatum(str);
argtypes[i] = TEXTOID;
}
}
PG_TRY();
{
status = SPI_execute_with_args(sql, nargs,
argtypes, values, nulls, false, 0);
}
PG_CATCH();
{
throw pg_error();
}
PG_END_TRY();
return SPIResultToValue(status);
}
Handle<v8::Value>
Yield(const Arguments& args) throw()
{
return SafeCall(YieldInternal, args);
}
static Handle<v8::Value>
YieldInternal(const Arguments& args)
{
Handle<Array> data = Handle<Array>::Cast(args.Data());
Converter *conv = static_cast<Converter *>(
External::Unwrap(data->Get(0)));
Tuplestorestate *tupstore = static_cast<Tuplestorestate *>(
External::Unwrap(data->Get(1)));
conv->ToDatum(args[0], tupstore);
return Undefined();
}
Handle<Function>
CreateYieldFunction(Converter *conv, Tuplestorestate *tupstore)
{
Handle<Array> data = Array::New(2);
data->Set(0, External::Wrap(conv));
data->Set(1, External::Wrap(tupstore));
return FunctionTemplate::New(Yield, data)->GetFunction();
}