webmcp

view libraries/mondelefant/mondelefant_native.c @ 410:92406e7b25cf

Replaced mondelefant_cleanup function with local cleanup code
author jbe
date Thu Jan 07 01:44:38 2016 +0100 (2016-01-07)
parents ebe9416db4e0
children 7d43be9afa56
line source
1 #include <lua.h>
2 #include <lauxlib.h>
3 #include <libpq-fe.h>
4 #include <postgres.h>
5 #include <catalog/pg_type.h>
6 #include <stdint.h>
7 #include <time.h>
9 // NOTE: Comments with format "// <number>" denote the Lua stack position
11 // prefix for all Lua registry entries of this library:
12 #define MONDELEFANT_REGKEY "mondelefant_"
14 // registry key of module "mondelefant_native":
15 #define MONDELEFANT_MODULE_REGKEY (MONDELEFANT_REGKEY "module")
16 // registry key of meta-table for database connections:
17 #define MONDELEFANT_CONN_MT_REGKEY (MONDELEFANT_REGKEY "connection")
18 // registry key of meta-table for database result lists and objects:
19 #define MONDELEFANT_RESULT_MT_REGKEY (MONDELEFANT_REGKEY "result")
20 // registry key of meta-table for database error objects:
21 #define MONDELEFANT_ERROROBJECT_MT_REGKEY (MONDELEFANT_REGKEY "errorobject")
22 // registry key of meta-table for models (named classes here):
23 #define MONDELEFANT_CLASS_MT_REGKEY (MONDELEFANT_REGKEY "class")
24 // registry key of default prototype for models/classes:
25 #define MONDELEFANT_CLASS_PROTO_REGKEY (MONDELEFANT_REGKEY "class_proto")
27 // C-structure for database connection userdata:
28 typedef struct {
29 PGconn *pgconn;
30 int server_encoding;
31 void *todo_PQfreemem;
32 PGresult *todo_PQclear;
33 } mondelefant_conn_t;
34 #define MONDELEFANT_SERVER_ENCODING_ASCII 0
35 #define MONDELEFANT_SERVER_ENCODING_UTF8 1
37 // transform codepoint-position to byte-position for a given UTF-8 string:
38 static size_t utf8_position_to_byte(const char *str, size_t utf8pos) {
39 size_t bytepos;
40 for (bytepos = 0; utf8pos > 0; bytepos++) {
41 uint8_t c;
42 c = ((const uint8_t *)str)[bytepos];
43 if (!c) break;
44 if (c <= 0x7f || c >= 0xc0) utf8pos--;
45 }
46 return bytepos;
47 }
49 // PostgreSQL's OID for binary data type (bytea):
50 #define MONDELEFANT_POSTGRESQL_BINARY_OID ((Oid)17)
52 // mapping a PostgreSQL type given by its OID to a string identifier:
53 static const char *mondelefant_oid_to_typestr(Oid oid) {
54 switch (oid) {
55 case 16: return "bool";
56 case 17: return "bytea";
57 case 18: return "char";
58 case 19: return "name";
59 case 20: return "int8";
60 case 21: return "int2";
61 case 23: return "int4";
62 case 25: return "text";
63 case 26: return "oid";
64 case 27: return "tid";
65 case 28: return "xid";
66 case 29: return "cid";
67 case 114: return "json";
68 case 600: return "point";
69 case 601: return "lseg";
70 case 602: return "path";
71 case 603: return "box";
72 case 604: return "polygon";
73 case 628: return "line";
74 case 700: return "float4";
75 case 701: return "float8";
76 case 705: return "unknown";
77 case 718: return "circle";
78 case 790: return "money";
79 case 829: return "macaddr";
80 case 869: return "inet";
81 case 650: return "cidr";
82 case 1042: return "bpchar";
83 case 1043: return "varchar";
84 case 1082: return "date";
85 case 1083: return "time";
86 case 1114: return "timestamp";
87 case 1184: return "timestamptz";
88 case 1186: return "interval";
89 case 1266: return "timetz";
90 case 1560: return "bit";
91 case 1562: return "varbit";
92 case 1700: return "numeric";
93 case 3802: return "jsonb";
94 default: return NULL;
95 }
96 }
98 // This library maps PostgreSQL's error codes to CamelCase string
99 // identifiers, which consist of CamelCase identifiers and are seperated
100 // by dots (".") (no leading or trailing dots).
101 // There are additional error identifiers which do not have a corresponding
102 // PostgreSQL error associated with it.
104 // matching start of local variable 'pgcode' against string 'incode',
105 // returning string 'outcode' on match:
106 #define mondelefant_errcode_item(incode, outcode) \
107 if (!strncmp(pgcode, (incode), strlen(incode))) return outcode; else
109 // additional error identifiers without corresponding PostgreSQL error:
110 #define MONDELEFANT_ERRCODE_UNKNOWN "unknown"
111 #define MONDELEFANT_ERRCODE_CONNECTION "ConnectionException"
112 #define MONDELEFANT_ERRCODE_RESULTCOUNT_LOW "WrongResultSetCount.ResultSetMissing"
113 #define MONDELEFANT_ERRCODE_RESULTCOUNT_HIGH "WrongResultSetCount.TooManyResults"
114 #define MONDELEFANT_ERRCODE_QUERY1_NO_ROWS "NoData.OneRowExpected"
115 #define MONDELEFANT_ERRCODE_QUERY1_MULTIPLE_ROWS "CardinalityViolation.OneRowExpected"
117 // mapping PostgreSQL error code to error code as returned by this library:
118 static const char *mondelefant_translate_errcode(const char *pgcode) {
119 if (!pgcode) abort(); // should not happen
120 mondelefant_errcode_item("02", "NoData")
121 mondelefant_errcode_item("03", "SqlStatementNotYetComplete")
122 mondelefant_errcode_item("08", "ConnectionException")
123 mondelefant_errcode_item("09", "TriggeredActionException")
124 mondelefant_errcode_item("0A", "FeatureNotSupported")
125 mondelefant_errcode_item("0B", "InvalidTransactionInitiation")
126 mondelefant_errcode_item("0F", "LocatorException")
127 mondelefant_errcode_item("0L", "InvalidGrantor")
128 mondelefant_errcode_item("0P", "InvalidRoleSpecification")
129 mondelefant_errcode_item("21", "CardinalityViolation")
130 mondelefant_errcode_item("22", "DataException")
131 mondelefant_errcode_item("23001", "IntegrityConstraintViolation.RestrictViolation")
132 mondelefant_errcode_item("23502", "IntegrityConstraintViolation.NotNullViolation")
133 mondelefant_errcode_item("23503", "IntegrityConstraintViolation.ForeignKeyViolation")
134 mondelefant_errcode_item("23505", "IntegrityConstraintViolation.UniqueViolation")
135 mondelefant_errcode_item("23514", "IntegrityConstraintViolation.CheckViolation")
136 mondelefant_errcode_item("23", "IntegrityConstraintViolation")
137 mondelefant_errcode_item("24", "InvalidCursorState")
138 mondelefant_errcode_item("25", "InvalidTransactionState")
139 mondelefant_errcode_item("26", "InvalidSqlStatementName")
140 mondelefant_errcode_item("27", "TriggeredDataChangeViolation")
141 mondelefant_errcode_item("28", "InvalidAuthorizationSpecification")
142 mondelefant_errcode_item("2B", "DependentPrivilegeDescriptorsStillExist")
143 mondelefant_errcode_item("2D", "InvalidTransactionTermination")
144 mondelefant_errcode_item("2F", "SqlRoutineException")
145 mondelefant_errcode_item("34", "InvalidCursorName")
146 mondelefant_errcode_item("38", "ExternalRoutineException")
147 mondelefant_errcode_item("39", "ExternalRoutineInvocationException")
148 mondelefant_errcode_item("3B", "SavepointException")
149 mondelefant_errcode_item("3D", "InvalidCatalogName")
150 mondelefant_errcode_item("3F", "InvalidSchemaName")
151 mondelefant_errcode_item("40", "TransactionRollback")
152 mondelefant_errcode_item("42", "SyntaxErrorOrAccessRuleViolation")
153 mondelefant_errcode_item("44", "WithCheckOptionViolation")
154 mondelefant_errcode_item("53", "InsufficientResources")
155 mondelefant_errcode_item("54", "ProgramLimitExceeded")
156 mondelefant_errcode_item("55", "ObjectNotInPrerequisiteState")
157 mondelefant_errcode_item("57", "OperatorIntervention")
158 mondelefant_errcode_item("58", "SystemError")
159 mondelefant_errcode_item("F0", "ConfigurationFileError")
160 mondelefant_errcode_item("P0", "PlpgsqlError")
161 mondelefant_errcode_item("XX", "InternalError")
162 return "unknown";
163 }
165 // C-function, checking if a given error code (as defined by this library)
166 // is belonging to a certain class of errors (strings are equal or error
167 // code begins with error class followed by a dot):
168 static int mondelefant_check_error_class(
169 const char *errcode, const char *errclass
170 ) {
171 size_t i = 0;
172 while (1) {
173 if (errclass[i] == 0) {
174 if (errcode[i] == 0 || errcode[i] == '.') return 1;
175 else return 0;
176 }
177 if (errcode[i] != errclass[i]) return 0;
178 i++;
179 }
180 }
182 // pushing first line of a string on Lua's stack (without trailing CR/LF):
183 static void mondelefant_push_first_line(lua_State *L, const char *str) {
184 size_t i = 0;
185 if (!str) abort(); // should not happen
186 while (1) {
187 char c = str[i];
188 if (c == '\n' || c == '\r' || c == 0) {
189 lua_pushlstring(L, str, i);
190 return;
191 }
192 i++;
193 }
194 }
196 // "connect" function of library, which establishes a database connection
197 // and returns a database connection handle:
198 static int mondelefant_connect(lua_State *L) {
199 const char *conninfo; // string for PQconnectdb function
200 mondelefant_conn_t *conn; // C-structure for userdata
201 // check if string is given as first argument:
202 if (lua_type(L, 1) != LUA_TSTRING) {
203 // expect a table as first argument if no string is given:
204 luaL_checktype(L, 1, LUA_TTABLE);
205 // extract conninfo string for PQconnectdb if possible:
206 lua_getfield(L, 1, "conninfo");
207 if (!lua_isnil(L, -1)) {
208 // if yes, use that value but check its type:
209 luaL_argcheck(L, lua_type(L, -1) == LUA_TSTRING, 1, "\"conninfo\" value is not a string");
210 } else {
211 // otherwise assemble conninfo string from the named options:
212 luaL_Buffer buf;
213 int need_seperator = 0;
214 const char *value;
215 size_t value_len;
216 size_t value_pos = 0;
217 lua_settop(L, 1);
218 lua_pushnil(L); // slot for key at stack position 2
219 lua_pushnil(L); // slot for value at stack position 3
220 luaL_buffinit(L, &buf);
221 while (lua_pushvalue(L, 2), lua_next(L, 1)) {
222 luaL_argcheck(L, lua_isstring(L, -2), 1, "key in table is not a string");
223 luaL_argcheck(L, lua_isstring(L, -1), 1, "value in table is not a string");
224 value = lua_tolstring(L, -1, &value_len);
225 lua_replace(L, 3);
226 lua_pop(L, 1);
227 lua_replace(L, 2);
228 if (need_seperator) luaL_addchar(&buf, ' ');
229 // NOTE: numbers will be converted to strings automatically here,
230 // but perhaps this will change in future versions of lua
231 lua_pushvalue(L, 2);
232 luaL_addvalue(&buf);
233 luaL_addchar(&buf, '=');
234 luaL_addchar(&buf, '\'');
235 do {
236 char c;
237 c = value[value_pos++];
238 if (c == '\'') luaL_addchar(&buf, '\\');
239 luaL_addchar(&buf, c);
240 } while (value_pos < value_len);
241 luaL_addchar(&buf, '\'');
242 need_seperator = 1;
243 }
244 luaL_pushresult(&buf);
245 }
246 // ensure that string is on stack position 1 which is the top of stack:
247 lua_replace(L, 1);
248 }
249 // use conninfo string on stack position 1:
250 conninfo = lua_tostring(L, 1);
251 // create userdata on stack position 2:
252 lua_settop(L, 1);
253 conn = lua_newuserdata(L, sizeof(*conn)); // 2
254 // call PQconnectdb function of libpq:
255 conn->pgconn = PQconnectdb(conninfo);
256 // try emergency garbage collection on first failure:
257 if (!conn->pgconn) {
258 lua_gc(L, LUA_GCCOLLECT, 0);
259 conn->pgconn = PQconnectdb(conninfo);
260 // throw error in case of (unexpected) error of PQconnectdb call:
261 if (!conn->pgconn) return luaL_error(L,
262 "Error in libpq while creating 'PGconn' structure."
263 );
264 }
265 // set metatable for userdata (ensure PQfinish on unexpected error below):
266 luaL_setmetatable(L, MONDELEFANT_CONN_MT_REGKEY);
267 // check result of PQconnectdb call:
268 if (PQstatus(conn->pgconn) != CONNECTION_OK) {
269 lua_pushnil(L); // 3
270 mondelefant_push_first_line(L, PQerrorMessage(conn->pgconn)); // 4
271 lua_newtable(L); // 5
272 luaL_setmetatable(L, MONDELEFANT_ERROROBJECT_MT_REGKEY);
273 lua_pushliteral(L, MONDELEFANT_ERRCODE_CONNECTION);
274 lua_setfield(L, 5, "code");
275 lua_pushvalue(L, 4);
276 lua_setfield(L, 5, "message");
277 // manual PQfinish (do not wait until garbage collection):
278 PQfinish(conn->pgconn);
279 conn->pgconn = NULL;
280 return 3;
281 }
282 // set 'server_encoding' in C-struct of userdata:
283 {
284 const char *charset;
285 charset = PQparameterStatus(conn->pgconn, "server_encoding");
286 if (charset && !strcmp(charset, "UTF8")) {
287 conn->server_encoding = MONDELEFANT_SERVER_ENCODING_UTF8;
288 } else {
289 conn->server_encoding = MONDELEFANT_SERVER_ENCODING_ASCII;
290 }
291 }
292 // create and associate userdata table:
293 lua_newtable(L);
294 lua_setuservalue(L, 2);
295 // store key "fd" with file descriptor of connection:
296 lua_pushinteger(L, PQsocket(conn->pgconn));
297 lua_setfield(L, 2, "fd");
298 // store key "engine" with value "postgresql" as connection specific data:
299 lua_pushliteral(L, "postgresql");
300 lua_setfield(L, 2, "engine");
301 // return userdata:
302 return 1;
303 }
305 // returns pointer to libpq handle 'pgconn' of userdata at given index
306 // (or throws error, if database connection has been closed):
307 static mondelefant_conn_t *mondelefant_get_conn(lua_State *L, int index) {
308 mondelefant_conn_t *conn;
309 conn = luaL_checkudata(L, index, MONDELEFANT_CONN_MT_REGKEY);
310 if (!conn->pgconn) {
311 luaL_error(L, "PostgreSQL connection has been closed.");
312 return NULL;
313 }
314 return conn;
315 }
317 // meta-method "__index" of database handles (userdata):
318 static int mondelefant_conn_index(lua_State *L) {
319 // try table for connection specific data:
320 lua_settop(L, 2);
321 lua_getuservalue(L, 1); // 3
322 lua_pushvalue(L, 2); // 4
323 lua_gettable(L, 3); // 4
324 if (!lua_isnil(L, 4)) return 1;
325 // try to use prototype stored in connection specific data:
326 lua_settop(L, 3);
327 lua_getfield(L, 3, "prototype"); // 4
328 if (lua_toboolean(L, 4)) {
329 lua_pushvalue(L, 2); // 5
330 lua_gettable(L, 4); // 5
331 if (!lua_isnil(L, 5)) return 1;
332 }
333 // try to use "postgresql_connection_prototype" of library:
334 lua_settop(L, 2);
335 lua_getfield(L, LUA_REGISTRYINDEX, MONDELEFANT_MODULE_REGKEY); // 3
336 lua_getfield(L, 3, "postgresql_connection_prototype"); // 4
337 if (lua_toboolean(L, 4)) {
338 lua_pushvalue(L, 2); // 5
339 lua_gettable(L, 4); // 5
340 if (!lua_isnil(L, 5)) return 1;
341 }
342 // try to use "connection_prototype" of library:
343 lua_settop(L, 3);
344 lua_getfield(L, 3, "connection_prototype"); // 4
345 if (lua_toboolean(L, 4)) {
346 lua_pushvalue(L, 2); // 5
347 lua_gettable(L, 4); // 5
348 if (!lua_isnil(L, 5)) return 1;
349 }
350 // give up and return nothing:
351 return 0;
352 }
354 // meta-method "__newindex" of database handles (userdata):
355 static int mondelefant_conn_newindex(lua_State *L) {
356 // store key-value pair in table for connection specific data:
357 lua_settop(L, 3);
358 lua_getuservalue(L, 1); // 4
359 lua_pushvalue(L, 2);
360 lua_pushvalue(L, 3);
361 lua_settable(L, 4);
362 // return nothing:
363 return 0;
364 }
366 // meta-method "__gc" of database handles:
367 static int mondelefant_conn_free(lua_State *L) {
368 mondelefant_conn_t *conn;
369 conn = luaL_checkudata(L, 1, MONDELEFANT_CONN_MT_REGKEY);
370 if (conn->todo_PQfreemem) {
371 PQfreemem(conn->todo_PQfreemem);
372 conn->todo_PQfreemem = NULL;
373 }
374 if (conn->todo_PQclear) {
375 PQclear(conn->todo_PQclear);
376 conn->todo_PQclear = NULL;
377 }
378 if (conn->pgconn) {
379 PQfinish(conn->pgconn);
380 conn->pgconn = NULL;
381 }
382 return 0;
383 }
385 // method "close" of database handles:
386 static int mondelefant_conn_close(lua_State *L) {
387 mondelefant_conn_t *conn;
388 conn = mondelefant_get_conn(L, 1);
389 PQfinish(conn->pgconn);
390 conn->pgconn = NULL;
391 lua_pushnil(L);
392 lua_setfield(L, 1, "fd"); // set "fd" attribute to nil
393 return 0;
394 }
396 // method "is_okay" of database handles:
397 static int mondelefant_conn_is_ok(lua_State *L) {
398 mondelefant_conn_t *conn;
399 conn = mondelefant_get_conn(L, 1);
400 lua_pushboolean(L, PQstatus(conn->pgconn) == CONNECTION_OK);
401 return 1;
402 }
404 // method "get_transaction_status" of database handles:
405 static int mondelefant_conn_get_transaction_status(lua_State *L) {
406 mondelefant_conn_t *conn;
407 conn = mondelefant_get_conn(L, 1);
408 switch (PQtransactionStatus(conn->pgconn)) {
409 case PQTRANS_IDLE:
410 lua_pushliteral(L, "idle");
411 break;
412 case PQTRANS_ACTIVE:
413 lua_pushliteral(L, "active");
414 break;
415 case PQTRANS_INTRANS:
416 lua_pushliteral(L, "intrans");
417 break;
418 case PQTRANS_INERROR:
419 lua_pushliteral(L, "inerror");
420 break;
421 default:
422 lua_pushliteral(L, "unknown");
423 }
424 return 1;
425 }
427 // method "try_wait" of database handles:
428 static int mondelefant_conn_try_wait(lua_State *L) {
429 mondelefant_conn_t *conn;
430 int infinite, nonblock = 0;
431 struct timespec wakeup;
432 int fd;
433 fd_set fds;
434 conn = mondelefant_get_conn(L, 1);
435 infinite = lua_isnoneornil(L, 2);
436 if (!infinite) {
437 lua_Number n;
438 int isnum;
439 n = lua_tonumberx(L, 2, &isnum);
440 if (isnum && n>0 && n<=86400*366) {
441 if (clock_gettime(CLOCK_MONOTONIC, &wakeup)) {
442 return luaL_error(L, "Could not access CLOCK_MONOTONIC");
443 }
444 wakeup.tv_sec += n;
445 wakeup.tv_nsec += 1000000000 * (n - (time_t)n);
446 if (wakeup.tv_nsec >= 1000000000) {
447 wakeup.tv_sec += 1;
448 wakeup.tv_nsec -= 1000000000;
449 }
450 } else if (isnum && n==0) {
451 nonblock = 1;
452 } else {
453 luaL_argcheck(L, 0, 2, "not a valid timeout");
454 }
455 }
456 lua_settop(L, 1);
457 if (!nonblock) {
458 fd = PQsocket(conn->pgconn);
459 FD_ZERO(&fds);
460 FD_SET(fd, &fds);
461 }
462 while (true) {
463 {
464 PGnotify *notify;
465 if (!PQconsumeInput(conn->pgconn)) {
466 lua_newtable(L); // 2
467 luaL_setmetatable(L, MONDELEFANT_ERROROBJECT_MT_REGKEY);
468 lua_pushliteral(L, MONDELEFANT_ERRCODE_CONNECTION);
469 lua_setfield(L, 2, "code");
470 mondelefant_push_first_line(L, PQerrorMessage(conn->pgconn)); // 3
471 lua_setfield(L, 2, "message");
472 return 1;
473 }
474 notify = PQnotifies(conn->pgconn);
475 if (notify) {
476 lua_pushnil(L);
477 lua_pushstring(L, notify->relname);
478 lua_pushstring(L, notify->extra);
479 lua_pushinteger(L, notify->be_pid);
480 PQfreemem(notify);
481 return 4;
482 }
483 }
484 if (infinite) {
485 select(fd+1, &fds, NULL, NULL, NULL);
486 } else if (nonblock) {
487 break;
488 } else {
489 struct timespec tp;
490 struct timeval timeout = { 0, };
491 if (clock_gettime(CLOCK_MONOTONIC, &tp)) {
492 return luaL_error(L, "Could not access CLOCK_MONOTONIC");
493 }
494 tp.tv_sec = wakeup.tv_sec - tp.tv_sec;
495 tp.tv_nsec = wakeup.tv_nsec - tp.tv_nsec;
496 if (tp.tv_nsec < 0) {
497 tp.tv_sec -= 1;
498 tp.tv_nsec += 1000000000;
499 }
500 timeout.tv_sec = tp.tv_sec;
501 timeout.tv_usec = (tp.tv_nsec + 500) / 1000;
502 if (
503 timeout.tv_sec < 0 ||
504 (timeout.tv_sec == 0 && timeout.tv_usec == 0)
505 ) break;
506 select(fd+1, &fds, NULL, NULL, &timeout);
507 }
508 }
509 lua_pushnil(L);
510 lua_pushnil(L);
511 return 2;
512 }
514 // method "create_list" of database handles:
515 static int mondelefant_conn_create_list(lua_State *L) {
516 // ensure that first argument is a database connection:
517 luaL_checkudata(L, 1, MONDELEFANT_CONN_MT_REGKEY);
518 // if no second argument is given, use an empty table:
519 if (lua_isnoneornil(L, 2)) {
520 lua_settop(L, 1);
521 lua_newtable(L); // 2
522 } else {
523 luaL_checktype(L, 2, LUA_TTABLE);
524 lua_settop(L, 2);
525 }
526 // set meta-table for database result lists/objects:
527 luaL_setmetatable(L, MONDELEFANT_RESULT_MT_REGKEY);
528 // set "_connection" attribute to self:
529 lua_pushvalue(L, 1); // 3
530 lua_setfield(L, 2, "_connection");
531 // set "_type" attribute to string "list":
532 lua_pushliteral(L, "list"); // 3
533 lua_setfield(L, 2, "_type");
534 // return created database result list:
535 return 1;
536 }
538 // method "create_object" of database handles:
539 static int mondelefant_conn_create_object(lua_State *L) {
540 // ensure that first argument is a database connection:
541 luaL_checkudata(L, 1, MONDELEFANT_CONN_MT_REGKEY);
542 // if no second argument is given, use an empty table:
543 if (lua_isnoneornil(L, 2)) {
544 lua_settop(L, 1);
545 lua_newtable(L); // 2
546 } else {
547 luaL_checktype(L, 2, LUA_TTABLE);
548 lua_settop(L, 2);
549 }
550 // set meta-table for database result lists/objects:
551 luaL_setmetatable(L, MONDELEFANT_RESULT_MT_REGKEY);
552 // set "_connection" attribute to self:
553 lua_pushvalue(L, 1); // 3
554 lua_setfield(L, 2, "_connection");
555 // set "_type" attribute to string "object":
556 lua_pushliteral(L, "object"); // 3
557 lua_setfield(L, 2, "_type"); // "object" or "list"
558 // create empty tables for "_data", "_dirty" and "_ref" attributes:
559 lua_newtable(L); // 3
560 lua_setfield(L, 2, "_data");
561 lua_newtable(L); // 3
562 lua_setfield(L, 2, "_dirty");
563 lua_newtable(L); // 3
564 lua_setfield(L, 2, "_ref"); // nil=no info, false=nil, else table
565 // return created database result object:
566 return 1;
567 }
569 // method "quote_string" of database handles:
570 static int mondelefant_conn_quote_string(lua_State *L) {
571 mondelefant_conn_t *conn;
572 const char *input;
573 size_t input_len;
574 luaL_Buffer buf;
575 char *output;
576 size_t output_len;
577 // get database connection object:
578 conn = mondelefant_get_conn(L, 1);
579 // get second argument, which must be a string:
580 input = luaL_checklstring(L, 2, &input_len);
581 // throw error, if string is too long:
582 if (input_len > (SIZE_MAX / sizeof(char) - 3) / 2) {
583 return luaL_error(L, "String to be escaped is too long.");
584 }
585 // allocate memory for quoted string:
586 output = luaL_buffinitsize(L, &buf, (2 * input_len + 3) * sizeof(char));
587 // do escaping by calling PQescapeStringConn and enclosing result with
588 // single quotes:
589 output[0] = '\'';
590 output_len = PQescapeStringConn(
591 conn->pgconn, output + 1, input, input_len, NULL
592 );
593 output[output_len + 1] = '\'';
594 output[output_len + 2] = 0;
595 // create Lua string:
596 luaL_addsize(&buf, output_len + 2);
597 // return Lua string:
598 return 1;
599 }
601 // method "quote_binary" of database handles:
602 static int mondelefant_conn_quote_binary(lua_State *L) {
603 mondelefant_conn_t *conn;
604 const char *input;
605 size_t input_len;
606 char *output;
607 size_t output_len;
608 luaL_Buffer buf;
609 // get database connection object:
610 conn = mondelefant_get_conn(L, 1);
611 // get second argument, which must be a string:
612 input = luaL_checklstring(L, 2, &input_len);
613 // avoid cumulating memory leaks in case of previous out-of-memory errors:
614 if (conn->todo_PQfreemem) {
615 PQfreemem(conn->todo_PQfreemem);
616 conn->todo_PQfreemem = NULL;
617 }
618 // call PQescapeByteaConn, which allocates memory itself:
619 output = (char *)PQescapeByteaConn(
620 conn->pgconn, (const unsigned char *)input, input_len, &output_len
621 );
622 if (!output) {
623 lua_gc(L, LUA_GCCOLLECT, 0);
624 output = (char *)PQescapeByteaConn(
625 conn->pgconn, (const unsigned char *)input, input_len, &output_len
626 );
627 if (!output) {
628 return luaL_error(L, "Could not allocate memory for binary quoting.");
629 }
630 }
631 // ensure call of PQfreemem in case of repeated out-of-memory errors:
632 conn->todo_PQfreemem = output;
633 // create Lua string enclosed by single quotes:
634 luaL_buffinit(L, &buf);
635 luaL_addchar(&buf, '\'');
636 luaL_addlstring(&buf, output, output_len - 1);
637 luaL_addchar(&buf, '\'');
638 luaL_pushresult(&buf);
639 // free memory allocated by PQescapeByteaConn:
640 PQfreemem(output);
641 // avoid double call of PQfreemem later:
642 conn->todo_PQfreemem = NULL;
643 // return Lua string:
644 return 1;
645 }
647 // method "assemble_command" of database handles:
648 static int mondelefant_conn_assemble_command(lua_State *L) {
649 mondelefant_conn_t *conn;
650 int paramidx = 2;
651 const char *template;
652 size_t template_pos = 0;
653 luaL_Buffer buf;
654 // get database connection object:
655 conn = mondelefant_get_conn(L, 1);
656 // if second argument is a string, return this string:
657 if (lua_type(L, 2) == LUA_TSTRING) {
658 lua_settop(L, 2);
659 return 1;
660 }
661 // if second argument has __tostring meta-method,
662 // then use this method and return its result:
663 if (luaL_callmeta(L, 2, "__tostring")) return 1;
664 // otherwise, require that second argument is a table:
665 luaL_checktype(L, 2, LUA_TTABLE);
666 // set stack top:
667 lua_settop(L, 2);
668 // get first element of table, which must be a string:
669 lua_rawgeti(L, 2, 1); // 3
670 luaL_argcheck(L,
671 lua_isstring(L, 3),
672 2,
673 "First entry of SQL command structure is not a string."
674 );
675 template = lua_tostring(L, 3);
676 // get value of "input_converter" attribute of database connection:
677 lua_pushliteral(L, "input_converter"); // 4
678 lua_gettable(L, 1); // input_converter at stack position 4
679 // reserve space on Lua stack:
680 lua_pushnil(L); // free space at stack position 5
681 lua_pushnil(L); // free space at stack position 6
682 // initialize Lua buffer for result string:
683 luaL_buffinit(L, &buf);
684 // fill buffer in loop:
685 while (1) {
686 // variable declaration:
687 char c;
688 // get next character:
689 c = template[template_pos++];
690 // break, when character is NULL byte:
691 if (!c) break;
692 // question-mark and dollar-sign are special characters:
693 if (c == '?' || c == '$') { // special character found
694 // check, if same character follows:
695 if (template[template_pos] == c) { // special character is escaped
696 // consume two characters of input and add one character to buffer:
697 template_pos++;
698 luaL_addchar(&buf, c);
699 } else { // special character is not escaped
700 luaL_Buffer keybuf;
701 int subcmd;
702 // set 'subcmd' = true, if special character was a dollar-sign,
703 // set 'subcmd' = false, if special character was a question-mark:
704 subcmd = (c == '$');
705 // read any number of alpha numeric chars or underscores
706 // and store them on Lua stack:
707 luaL_buffinit(L, &keybuf);
708 while (1) {
709 c = template[template_pos];
710 if (
711 (c < 'A' || c > 'Z') &&
712 (c < 'a' || c > 'z') &&
713 (c < '0' || c > '9') &&
714 (c != '_')
715 ) break;
716 luaL_addchar(&keybuf, c);
717 template_pos++;
718 }
719 luaL_pushresult(&keybuf);
720 // check, if any characters matched:
721 if (lua_rawlen(L, -1)) {
722 // if any alpha numeric chars or underscores were found,
723 // push them on stack as a Lua string and use them to lookup
724 // value from second argument:
725 lua_pushvalue(L, -1); // save key on stack
726 lua_gettable(L, 2); // fetch value (raw-value)
727 } else {
728 // otherwise push nil and use numeric lookup based on 'paramidx':
729 lua_pop(L, 1);
730 lua_pushnil(L); // put nil on key position
731 lua_rawgeti(L, 2, paramidx++); // fetch value (raw-value)
732 }
733 // Lua stack contains: ..., <buffer>, key, raw-value
734 // branch according to type of special character ("?" or "$"):
735 if (subcmd) { // dollar-sign
736 size_t i;
737 size_t count;
738 // store fetched value (which is supposed to be sub-structure)
739 // on Lua stack position 5 and drop key:
740 lua_replace(L, 5);
741 lua_pop(L, 1);
742 // Lua stack contains: ..., <buffer>
743 // check, if fetched value is really a sub-structure:
744 luaL_argcheck(L,
745 !lua_isnil(L, 5),
746 2,
747 "SQL sub-structure not found."
748 );
749 luaL_argcheck(L,
750 lua_type(L, 5) == LUA_TTABLE,
751 2,
752 "SQL sub-structure must be a table."
753 );
754 // Lua stack contains: ..., <buffer>
755 // get value of "sep" attribute of sub-structure,
756 // and place it on Lua stack position 6:
757 lua_getfield(L, 5, "sep");
758 lua_replace(L, 6);
759 // if seperator is nil, then use ", " as default,
760 // if seperator is neither nil nor a string, then throw error:
761 if (lua_isnil(L, 6)) {
762 lua_pushstring(L, ", ");
763 lua_replace(L, 6);
764 } else {
765 luaL_argcheck(L,
766 lua_isstring(L, 6),
767 2,
768 "Seperator of SQL sub-structure has to be a string."
769 );
770 }
771 // iterate over items of sub-structure:
772 count = lua_rawlen(L, 5);
773 for (i = 0; i < count; i++) {
774 // add seperator, unless this is the first run:
775 if (i) {
776 lua_pushvalue(L, 6);
777 luaL_addvalue(&buf);
778 }
779 // recursivly apply assemble function and add results to buffer:
780 lua_pushcfunction(L, mondelefant_conn_assemble_command);
781 lua_pushvalue(L, 1);
782 lua_rawgeti(L, 5, i+1);
783 lua_call(L, 2, 1);
784 luaL_addvalue(&buf);
785 }
786 } else { // question-mark
787 if (lua_toboolean(L, 4)) {
788 // call input_converter with connection handle, raw-value and
789 // an info-table which contains a "field_name" entry with the
790 // used key:
791 lua_pushvalue(L, 4);
792 lua_pushvalue(L, 1);
793 lua_pushvalue(L, -3);
794 lua_newtable(L);
795 lua_pushvalue(L, -6);
796 lua_setfield(L, -2, "field_name");
797 lua_call(L, 3, 1);
798 // Lua stack contains: ..., <buffer>, key, raw-value, final-value
799 // remove key and raw-value:
800 lua_remove(L, -2);
801 lua_remove(L, -2);
802 // Lua stack contains: ..., <buffer>, final-value
803 // throw error, if final-value is not a string:
804 if (!lua_isstring(L, -1)) {
805 return luaL_error(L, "input_converter returned non-string.");
806 }
807 } else {
808 // remove key from stack:
809 lua_remove(L, -2);
810 // Lua stack contains: ..., <buffer>, raw-value
811 // branch according to type of value:
812 // NOTE: Lua automatically converts numbers to strings
813 if (lua_isnil(L, -1)) { // value is nil
814 // push string "NULL" to stack:
815 lua_pushliteral(L, "NULL");
816 } else if (lua_type(L, -1) == LUA_TBOOLEAN) { // value is boolean
817 // push strings "TRUE" or "FALSE" to stack:
818 lua_pushstring(L, lua_toboolean(L, -1) ? "TRUE" : "FALSE");
819 } else if (lua_isstring(L, -1)) { // value is string or number
820 // push output of "quote_string" method of database connection
821 // to stack:
822 lua_tostring(L, -1);
823 lua_pushcfunction(L, mondelefant_conn_quote_string);
824 lua_pushvalue(L, 1);
825 lua_pushvalue(L, -3);
826 lua_call(L, 2, 1);
827 } else { // value is of other type
828 // throw error:
829 return luaL_error(L,
830 "Unable to convert SQL value due to unknown type "
831 "or missing input_converter."
832 );
833 }
834 // Lua stack contains: ..., <buffer>, raw-value, final-value
835 // remove raw-value:
836 lua_remove(L, -2);
837 // Lua stack contains: ..., <buffer>, final-value
838 }
839 // append final-value to buffer:
840 luaL_addvalue(&buf);
841 }
842 }
843 } else { // character is not special
844 // just copy character:
845 luaL_addchar(&buf, c);
846 }
847 }
848 // return string in buffer:
849 luaL_pushresult(&buf);
850 return 1;
851 }
853 // max number of SQL statements executed by one "query" method call:
854 #define MONDELEFANT_MAX_COMMAND_COUNT 64
855 // max number of columns in a database result:
856 #define MONDELEFANT_MAX_COLUMN_COUNT 1024
857 // enum values for 'modes' array in C-function below:
858 #define MONDELEFANT_QUERY_MODE_LIST 1
859 #define MONDELEFANT_QUERY_MODE_OBJECT 2
860 #define MONDELEFANT_QUERY_MODE_OPT_OBJECT 3
862 // method "try_query" of database handles:
863 static int mondelefant_conn_try_query(lua_State *L) {
864 mondelefant_conn_t *conn;
865 int command_count;
866 int command_idx;
867 int modes[MONDELEFANT_MAX_COMMAND_COUNT];
868 luaL_Buffer buf;
869 int sent_success;
870 PGresult *res;
871 int rows, cols, row, col;
872 // get database connection object:
873 conn = mondelefant_get_conn(L, 1);
874 // calculate number of commands (2 arguments for one command):
875 command_count = lua_gettop(L) / 2;
876 // push nil on stack, which is needed, if last mode was ommitted:
877 lua_pushnil(L);
878 // throw error, if number of commands is too high:
879 if (command_count > MONDELEFANT_MAX_COMMAND_COUNT) {
880 return luaL_error(L, "Exceeded maximum command count in one query.");
881 }
882 // create SQL string, store query modes and push SQL string on stack:
883 luaL_buffinit(L, &buf);
884 for (command_idx = 0; command_idx < command_count; command_idx++) {
885 int mode;
886 int mode_idx; // stack index of mode string
887 if (command_idx) luaL_addchar(&buf, ' ');
888 lua_pushcfunction(L, mondelefant_conn_assemble_command);
889 lua_pushvalue(L, 1);
890 lua_pushvalue(L, 2 + 2 * command_idx);
891 lua_call(L, 2, 1);
892 luaL_addvalue(&buf);
893 luaL_addchar(&buf, ';');
894 mode_idx = 3 + 2 * command_idx;
895 if (lua_isnil(L, mode_idx)) {
896 mode = MONDELEFANT_QUERY_MODE_LIST;
897 } else {
898 const char *modestr;
899 modestr = luaL_checkstring(L, mode_idx);
900 if (!strcmp(modestr, "list")) {
901 mode = MONDELEFANT_QUERY_MODE_LIST;
902 } else if (!strcmp(modestr, "object")) {
903 mode = MONDELEFANT_QUERY_MODE_OBJECT;
904 } else if (!strcmp(modestr, "opt_object")) {
905 mode = MONDELEFANT_QUERY_MODE_OPT_OBJECT;
906 } else {
907 return luaL_argerror(L, mode_idx, "unknown query mode");
908 }
909 }
910 modes[command_idx] = mode;
911 }
912 luaL_pushresult(&buf); // stack position unknown
913 lua_replace(L, 2); // SQL command string to stack position 2
914 // call sql_tracer, if set:
915 lua_settop(L, 2);
916 lua_getfield(L, 1, "sql_tracer"); // tracer at stack position 3
917 if (lua_toboolean(L, 3)) {
918 lua_pushvalue(L, 1); // 4
919 lua_pushvalue(L, 2); // 5
920 lua_call(L, 2, 1); // trace callback at stack position 3
921 }
922 // NOTE: If no tracer was found, then nil or false is stored at stack
923 // position 3.
924 // call PQsendQuery function and store result in 'sent_success' variable:
925 sent_success = PQsendQuery(conn->pgconn, lua_tostring(L, 2));
926 // create preliminary result table:
927 lua_newtable(L); // results in table at stack position 4
928 // iterate over results using function PQgetResult to fill result table:
929 for (command_idx = 0; ; command_idx++) {
930 int mode;
931 char binary[MONDELEFANT_MAX_COLUMN_COUNT];
932 ExecStatusType pgstatus;
933 // fetch mode which was given for the command:
934 mode = modes[command_idx];
935 // if PQsendQuery call was successful, then fetch result data:
936 if (sent_success) {
937 // avoid cumulating memory leaks in case of previous out-of-memory errors:
938 if (conn->todo_PQclear) {
939 PQclear(conn->todo_PQclear);
940 conn->todo_PQclear = NULL;
941 }
942 // NOTE: PQgetResult called one extra time. Break only, if all
943 // queries have been processed and PQgetResult returned NULL.
944 res = PQgetResult(conn->pgconn);
945 if (command_idx >= command_count && !res) break;
946 if (res) {
947 pgstatus = PQresultStatus(res);
948 rows = PQntuples(res);
949 cols = PQnfields(res);
950 // ensure call of PQclear in case of repeated Lua errors:
951 conn->todo_PQclear = res;
952 }
953 }
954 // handle errors:
955 if (
956 !sent_success || command_idx >= command_count || !res ||
957 (pgstatus != PGRES_TUPLES_OK && pgstatus != PGRES_COMMAND_OK) ||
958 (rows < 1 && mode == MONDELEFANT_QUERY_MODE_OBJECT) ||
959 (rows > 1 && mode != MONDELEFANT_QUERY_MODE_LIST)
960 ) {
961 const char *command;
962 command = lua_tostring(L, 2);
963 lua_newtable(L); // 5
964 luaL_setmetatable(L, MONDELEFANT_ERROROBJECT_MT_REGKEY);
965 lua_pushvalue(L, 1);
966 lua_setfield(L, 5, "connection");
967 lua_pushvalue(L, 2);
968 lua_setfield(L, 5, "sql_command");
969 if (!sent_success) {
970 lua_pushliteral(L, MONDELEFANT_ERRCODE_CONNECTION);
971 lua_setfield(L, 5, "code");
972 mondelefant_push_first_line(L, PQerrorMessage(conn->pgconn));
973 lua_setfield(L, 5, "message");
974 } else {
975 lua_pushinteger(L, command_idx + 1);
976 lua_setfield(L, 5, "command_number");
977 if (!res) {
978 lua_pushliteral(L, MONDELEFANT_ERRCODE_RESULTCOUNT_LOW);
979 lua_setfield(L, 5, "code");
980 lua_pushliteral(L, "Received too few database result sets.");
981 lua_setfield(L, 5, "message");
982 } else if (command_idx >= command_count) {
983 lua_pushliteral(L, MONDELEFANT_ERRCODE_RESULTCOUNT_HIGH);
984 lua_setfield(L, 5, "code");
985 lua_pushliteral(L, "Received too many database result sets.");
986 lua_setfield(L, 5, "message");
987 } else if (
988 pgstatus != PGRES_TUPLES_OK && pgstatus != PGRES_COMMAND_OK
989 ) {
990 const char *sqlstate;
991 const char *errmsg;
992 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_SEVERITY));
993 lua_setfield(L, 5, "pg_severity");
994 sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
995 if (sqlstate) {
996 lua_pushstring(L, sqlstate);
997 lua_setfield(L, 5, "pg_sqlstate");
998 lua_pushstring(L, mondelefant_translate_errcode(sqlstate));
999 lua_setfield(L, 5, "code");
1000 } else {
1001 lua_pushliteral(L, MONDELEFANT_ERRCODE_UNKNOWN);
1002 lua_setfield(L, 5, "code");
1004 errmsg = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
1005 if (errmsg) {
1006 mondelefant_push_first_line(L, errmsg);
1007 lua_setfield(L, 5, "message");
1008 lua_pushstring(L, errmsg);
1009 lua_setfield(L, 5, "pg_message_primary");
1010 } else {
1011 lua_pushliteral(L,
1012 "Error while fetching result, but no error message given."
1013 );
1014 lua_setfield(L, 5, "message");
1016 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL));
1017 lua_setfield(L, 5, "pg_message_detail");
1018 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_MESSAGE_HINT));
1019 lua_setfield(L, 5, "pg_message_hint");
1020 // NOTE: "position" and "pg_internal_position" are recalculated to
1021 // byte offsets, as Lua 5.2 is not Unicode aware.
1023 char *tmp;
1024 tmp = PQresultErrorField(res, PG_DIAG_STATEMENT_POSITION);
1025 if (tmp) {
1026 int pos;
1027 pos = atoi(tmp) - 1;
1028 if (conn->server_encoding == MONDELEFANT_SERVER_ENCODING_UTF8) {
1029 pos = utf8_position_to_byte(command, pos);
1031 lua_pushinteger(L, pos + 1);
1032 lua_setfield(L, 5, "position");
1036 const char *internal_query;
1037 internal_query = PQresultErrorField(res, PG_DIAG_INTERNAL_QUERY);
1038 lua_pushstring(L, internal_query);
1039 lua_setfield(L, 5, "pg_internal_query");
1040 char *tmp;
1041 tmp = PQresultErrorField(res, PG_DIAG_INTERNAL_POSITION);
1042 if (tmp) {
1043 int pos;
1044 pos = atoi(tmp) - 1;
1045 if (conn->server_encoding == MONDELEFANT_SERVER_ENCODING_UTF8) {
1046 pos = utf8_position_to_byte(internal_query, pos);
1048 lua_pushinteger(L, pos + 1);
1049 lua_setfield(L, 5, "pg_internal_position");
1052 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_CONTEXT));
1053 lua_setfield(L, 5, "pg_context");
1054 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_SOURCE_FILE));
1055 lua_setfield(L, 5, "pg_source_file");
1056 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_SOURCE_LINE));
1057 lua_setfield(L, 5, "pg_source_line");
1058 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_SOURCE_FUNCTION));
1059 lua_setfield(L, 5, "pg_source_function");
1060 } else if (rows < 1 && mode == MONDELEFANT_QUERY_MODE_OBJECT) {
1061 lua_pushliteral(L, MONDELEFANT_ERRCODE_QUERY1_NO_ROWS);
1062 lua_setfield(L, 5, "code");
1063 lua_pushliteral(L, "Expected one row, but got empty set.");
1064 lua_setfield(L, 5, "message");
1065 } else if (rows > 1 && mode != MONDELEFANT_QUERY_MODE_LIST) {
1066 lua_pushliteral(L, MONDELEFANT_ERRCODE_QUERY1_MULTIPLE_ROWS);
1067 lua_setfield(L, 5, "code");
1068 lua_pushliteral(L, "Got more than one result row.");
1069 lua_setfield(L, 5, "message");
1070 } else {
1071 // should not happen
1072 abort();
1074 if (res) {
1075 PQclear(res);
1076 while ((res = PQgetResult(conn->pgconn))) PQclear(res);
1077 // avoid double call of PQclear later:
1078 conn->todo_PQclear = NULL;
1081 if (lua_toboolean(L, 3)) {
1082 lua_pushvalue(L, 3);
1083 lua_pushvalue(L, 5);
1084 lua_call(L, 1, 0);
1086 return 1;
1088 // call "create_list" or "create_object" method of database handle,
1089 // result will be at stack position 5:
1090 if (modes[command_idx] == MONDELEFANT_QUERY_MODE_LIST) {
1091 lua_pushcfunction(L, mondelefant_conn_create_list); // 5
1092 lua_pushvalue(L, 1); // 6
1093 lua_call(L, 1, 1); // 5
1094 } else {
1095 lua_pushcfunction(L, mondelefant_conn_create_object); // 5
1096 lua_pushvalue(L, 1); // 6
1097 lua_call(L, 1, 1); // 5
1099 // set "_column_info":
1100 lua_newtable(L); // 6
1101 for (col = 0; col < cols; col++) {
1102 lua_newtable(L); // 7
1103 lua_pushstring(L, PQfname(res, col)); // 8
1104 lua_pushvalue(L, 8); // 9
1105 lua_pushvalue(L, 7); // 10
1106 lua_rawset(L, 6);
1107 lua_setfield(L, 7, "field_name");
1108 // _column_info entry (for current column) on stack position 7
1110 Oid tmp;
1111 tmp = PQftable(res, col);
1112 if (tmp == InvalidOid) lua_pushnil(L);
1113 else lua_pushinteger(L, tmp);
1114 lua_setfield(L, 7, "table_oid");
1117 int tmp;
1118 tmp = PQftablecol(res, col);
1119 if (tmp == 0) lua_pushnil(L);
1120 else lua_pushinteger(L, tmp);
1121 lua_setfield(L, 7, "table_column_number");
1124 Oid tmp;
1125 tmp = PQftype(res, col);
1126 binary[col] = (tmp == MONDELEFANT_POSTGRESQL_BINARY_OID);
1127 lua_pushinteger(L, tmp);
1128 lua_setfield(L, 7, "type_oid");
1129 lua_pushstring(L, mondelefant_oid_to_typestr(tmp));
1130 lua_setfield(L, 7, "type");
1133 int tmp;
1134 tmp = PQfmod(res, col);
1135 if (tmp == -1) lua_pushnil(L);
1136 else lua_pushinteger(L, tmp);
1137 lua_setfield(L, 7, "type_modifier");
1139 lua_rawseti(L, 6, col+1);
1141 lua_setfield(L, 5, "_column_info");
1142 // set "_rows_affected":
1144 char *tmp;
1145 tmp = PQcmdTuples(res);
1146 if (tmp[0]) {
1147 lua_pushinteger(L, atoi(tmp));
1148 lua_setfield(L, 5, "_rows_affected");
1151 // set "_oid":
1153 Oid tmp;
1154 tmp = PQoidValue(res);
1155 if (tmp != InvalidOid) {
1156 lua_pushinteger(L, tmp);
1157 lua_setfield(L, 5, "_oid");
1160 // copy data as strings or nil, while performing binary unescaping
1161 // automatically:
1162 if (modes[command_idx] == MONDELEFANT_QUERY_MODE_LIST) {
1163 for (row = 0; row < rows; row++) {
1164 lua_pushcfunction(L, mondelefant_conn_create_object); // 6
1165 lua_pushvalue(L, 1); // 7
1166 lua_call(L, 1, 1); // 6
1167 for (col = 0; col < cols; col++) {
1168 if (PQgetisnull(res, row, col)) {
1169 lua_pushnil(L);
1170 } else if (binary[col]) {
1171 size_t binlen;
1172 char *binval;
1173 binval = (char *)PQunescapeBytea(
1174 (unsigned char *)PQgetvalue(res, row, col), &binlen
1175 );
1176 if (!binval) {
1177 return luaL_error(L,
1178 "Could not allocate memory for binary unescaping."
1179 );
1181 lua_pushlstring(L, binval, binlen);
1182 PQfreemem(binval);
1183 } else {
1184 lua_pushstring(L, PQgetvalue(res, row, col));
1186 lua_rawseti(L, 6, col+1);
1188 lua_rawseti(L, 5, row+1);
1190 } else if (rows == 1) {
1191 for (col = 0; col < cols; col++) {
1192 if (PQgetisnull(res, 0, col)) {
1193 lua_pushnil(L);
1194 } else if (binary[col]) {
1195 size_t binlen;
1196 char *binval;
1197 binval = (char *)PQunescapeBytea(
1198 (unsigned char *)PQgetvalue(res, 0, col), &binlen
1199 );
1200 if (!binval) {
1201 return luaL_error(L,
1202 "Could not allocate memory for binary unescaping."
1203 );
1205 lua_pushlstring(L, binval, binlen);
1206 PQfreemem(binval);
1207 } else {
1208 lua_pushstring(L, PQgetvalue(res, 0, col));
1210 lua_rawseti(L, 5, col+1);
1212 } else {
1213 // no row in optrow mode
1214 lua_pop(L, 1);
1215 lua_pushnil(L);
1217 // save result in result list:
1218 lua_rawseti(L, 4, command_idx+1);
1219 // extra assertion:
1220 if (lua_gettop(L) != 4) abort(); // should not happen
1221 // free memory acquired by libpq:
1222 PQclear(res);
1223 // avoid double call of PQclear later:
1224 conn->todo_PQclear = NULL;
1226 // trace callback at stack position 3
1227 // result at stack position 4 (top of stack)
1228 // if a trace callback is existent, then call:
1229 if (lua_toboolean(L, 3)) {
1230 lua_pushvalue(L, 3);
1231 lua_call(L, 0, 0);
1233 // put result at stack position 3:
1234 lua_replace(L, 3);
1235 // get output converter to stack position 4:
1236 lua_getfield(L, 1, "output_converter");
1237 // get mutability state saver to stack position 5:
1238 lua_getfield(L, LUA_REGISTRYINDEX, MONDELEFANT_MODULE_REGKEY);
1239 lua_getfield(L, -1, "save_mutability_state");
1240 lua_replace(L, -2);
1241 // apply output converters and fill "_data" table according to column names:
1242 for (command_idx = 0; command_idx < command_count; command_idx++) {
1243 int mode;
1244 mode = modes[command_idx];
1245 lua_rawgeti(L, 3, command_idx+1); // raw result at stack position 6
1246 if (lua_toboolean(L, 6)) {
1247 lua_getfield(L, 6, "_column_info"); // column_info list at position 7
1248 cols = lua_rawlen(L, 7);
1249 if (mode == MONDELEFANT_QUERY_MODE_LIST) {
1250 rows = lua_rawlen(L, 6);
1251 for (row = 0; row < rows; row++) {
1252 lua_rawgeti(L, 6, row+1); // row at stack position 8
1253 lua_getfield(L, 8, "_data"); // _data table at stack position 9
1254 lua_getfield(L, 8, "_dirty"); // _dirty table at stack position 10
1255 for (col = 0; col < cols; col++) {
1256 lua_rawgeti(L, 7, col+1); // this column info at position 11
1257 lua_getfield(L, 11, "field_name"); // 12
1258 if (lua_toboolean(L, 4)) {
1259 lua_pushvalue(L, 4); // output-converter
1260 lua_pushvalue(L, 1); // connection
1261 lua_rawgeti(L, 8, col+1); // raw-value
1262 lua_pushvalue(L, 11); // this column info
1263 lua_call(L, 3, 1); // converted value at position 13
1264 } else {
1265 lua_rawgeti(L, 8, col+1); // raw-value at position 13
1267 if (lua_toboolean(L, 5)) { // handle mutable values?
1268 lua_pushvalue(L, 12); // copy of field name
1269 lua_pushvalue(L, 5); // mutability state saver function
1270 lua_pushvalue(L, 13); // copy of value
1271 lua_call(L, 1, 1); // calculated mutability state of value
1272 lua_rawset(L, 10); // store mutability state in _dirty table
1274 lua_pushvalue(L, 13); // 14
1275 lua_rawseti(L, 8, col+1);
1276 lua_rawset(L, 9);
1277 lua_settop(L, 10);
1279 lua_settop(L, 7);
1281 } else {
1282 lua_getfield(L, 6, "_data"); // _data table at stack position 8
1283 lua_getfield(L, 6, "_dirty"); // _dirty table at stack position 9
1284 for (col = 0; col < cols; col++) {
1285 lua_rawgeti(L, 7, col+1); // this column info at position 10
1286 lua_getfield(L, 10, "field_name"); // 11
1287 if (lua_toboolean(L, 4)) {
1288 lua_pushvalue(L, 4); // output-converter
1289 lua_pushvalue(L, 1); // connection
1290 lua_rawgeti(L, 6, col+1); // raw-value
1291 lua_pushvalue(L, 10); // this column info
1292 lua_call(L, 3, 1); // converted value at position 12
1293 } else {
1294 lua_rawgeti(L, 6, col+1); // raw-value at position 12
1296 if (lua_toboolean(L, 5)) { // handle mutable values?
1297 lua_pushvalue(L, 11); // copy of field name
1298 lua_pushvalue(L, 5); // mutability state saver function
1299 lua_pushvalue(L, 12); // copy of value
1300 lua_call(L, 1, 1); // calculated mutability state of value
1301 lua_rawset(L, 9); // store mutability state in _dirty table
1303 lua_pushvalue(L, 12); // 13
1304 lua_rawseti(L, 6, col+1);
1305 lua_rawset(L, 8);
1306 lua_settop(L, 9);
1310 lua_settop(L, 5);
1312 // return nil as first result value, followed by result lists/objects:
1313 lua_settop(L, 3);
1314 lua_pushnil(L);
1315 for (command_idx = 0; command_idx < command_count; command_idx++) {
1316 lua_rawgeti(L, 3, command_idx+1);
1318 return command_count+1;
1321 // method "is_kind_of" of error objects:
1322 static int mondelefant_errorobject_is_kind_of(lua_State *L) {
1323 const char *errclass;
1324 luaL_checktype(L, 1, LUA_TTABLE);
1325 errclass = luaL_checkstring(L, 2);
1326 lua_settop(L, 2);
1327 lua_getfield(L, 1, "code"); // 3
1328 luaL_argcheck(L,
1329 lua_type(L, 3) == LUA_TSTRING,
1330 1,
1331 "field 'code' of error object is not a string"
1332 );
1333 lua_pushboolean(L,
1334 mondelefant_check_error_class(lua_tostring(L, 3), errclass)
1335 );
1336 return 1;
1339 // method "wait" of database handles:
1340 static int mondelefant_conn_wait(lua_State *L) {
1341 int argc;
1342 // count number of arguments:
1343 argc = lua_gettop(L);
1344 // insert "try_wait" function/method at stack position 1:
1345 lua_pushcfunction(L, mondelefant_conn_try_wait);
1346 lua_insert(L, 1);
1347 // call "try_wait" method:
1348 lua_call(L, argc, LUA_MULTRET); // results (with error) starting at index 1
1349 // check, if error occurred:
1350 if (lua_toboolean(L, 1)) {
1351 // raise error
1352 lua_settop(L, 1);
1353 return lua_error(L);
1354 } else {
1355 // return everything but nil error object:
1356 return lua_gettop(L) - 1;
1360 // method "query" of database handles:
1361 static int mondelefant_conn_query(lua_State *L) {
1362 int argc;
1363 // count number of arguments:
1364 argc = lua_gettop(L);
1365 // insert "try_query" function/method at stack position 1:
1366 lua_pushcfunction(L, mondelefant_conn_try_query);
1367 lua_insert(L, 1);
1368 // call "try_query" method:
1369 lua_call(L, argc, LUA_MULTRET); // results (with error) starting at index 1
1370 // check, if error occurred:
1371 if (lua_toboolean(L, 1)) {
1372 // raise error
1373 lua_settop(L, 1);
1374 return lua_error(L);
1375 } else {
1376 // return everything but nil error object:
1377 return lua_gettop(L) - 1;
1381 // library function "set_class":
1382 static int mondelefant_set_class(lua_State *L) {
1383 // ensure that first argument is a database result list/object:
1384 lua_settop(L, 2);
1385 lua_getmetatable(L, 1); // 3
1386 lua_getfield(L, LUA_REGISTRYINDEX, MONDELEFANT_RESULT_MT_REGKEY); // 4
1387 luaL_argcheck(L, lua_compare(L, 3, 4, LUA_OPEQ), 1, "not a database result");
1388 // ensure that second argument is a database class (model):
1389 lua_settop(L, 2);
1390 lua_getmetatable(L, 2); // 3
1391 lua_getfield(L, LUA_REGISTRYINDEX, MONDELEFANT_CLASS_MT_REGKEY); // 4
1392 luaL_argcheck(L, lua_compare(L, 3, 4, LUA_OPEQ), 2, "not a database class");
1393 // set attribute "_class" of result list/object to given class:
1394 lua_settop(L, 2);
1395 lua_pushvalue(L, 2); // 3
1396 lua_setfield(L, 1, "_class");
1397 // test, if database result is a list (and not a single object):
1398 lua_getfield(L, 1, "_type"); // 3
1399 lua_pushliteral(L, "list"); // 4
1400 if (lua_rawequal(L, 3, 4)) {
1401 int i;
1402 // set attribute "_class" of all elements to given class:
1403 for (i=0; i < lua_rawlen(L, 1); i++) {
1404 lua_settop(L, 2);
1405 lua_rawgeti(L, 1, i+1); // 3
1406 lua_pushvalue(L, 2); // 4
1407 lua_setfield(L, 3, "_class");
1410 // return first argument:
1411 lua_settop(L, 1);
1412 return 1;
1415 // library function "new_class":
1416 static int mondelefant_new_class(lua_State *L) {
1417 // if no argument is given, use an empty table:
1418 if (lua_isnoneornil(L, 1)) {
1419 lua_settop(L, 0);
1420 lua_newtable(L); // 1
1421 } else {
1422 luaL_checktype(L, 1, LUA_TTABLE);
1423 lua_settop(L, 1);
1425 // set meta-table for database classes (models):
1426 luaL_setmetatable(L, MONDELEFANT_CLASS_MT_REGKEY);
1427 // check, if "prototype" attribute is not set:
1428 lua_pushliteral(L, "prototype"); // 2
1429 lua_rawget(L, 1); // 2
1430 if (!lua_toboolean(L, 2)) {
1431 // set "prototype" attribute to default prototype:
1432 lua_pushliteral(L, "prototype"); // 3
1433 lua_getfield(L,
1434 LUA_REGISTRYINDEX,
1435 MONDELEFANT_CLASS_PROTO_REGKEY
1436 ); // 4
1437 lua_rawset(L, 1);
1439 // set "object" attribute to empty table, unless it is already set:
1440 lua_settop(L, 1);
1441 lua_pushliteral(L, "object"); // 2
1442 lua_rawget(L, 1); // 2
1443 if (!lua_toboolean(L, 2)) {
1444 lua_pushliteral(L, "object"); // 3
1445 lua_newtable(L); // 4
1446 lua_rawset(L, 1);
1448 // set "object_get" attribute to empty table, unless it is already set:
1449 lua_settop(L, 1);
1450 lua_pushliteral(L, "object_get"); // 2
1451 lua_rawget(L, 1); // 2
1452 if (!lua_toboolean(L, 2)) {
1453 lua_pushliteral(L, "object_get"); // 3
1454 lua_newtable(L); // 4
1455 lua_rawset(L, 1);
1457 // set "object_set" attribute to empty table, unless it is already set:
1458 lua_settop(L, 1);
1459 lua_pushliteral(L, "object_set"); // 2
1460 lua_rawget(L, 1); // 2
1461 if (!lua_toboolean(L, 2)) {
1462 lua_pushliteral(L, "object_set"); // 3
1463 lua_newtable(L); // 4
1464 lua_rawset(L, 1);
1466 // set "list" attribute to empty table, unless it is already set:
1467 lua_settop(L, 1);
1468 lua_pushliteral(L, "list"); // 2
1469 lua_rawget(L, 1); // 2
1470 if (!lua_toboolean(L, 2)) {
1471 lua_pushliteral(L, "list"); // 3
1472 lua_newtable(L); // 4
1473 lua_rawset(L, 1);
1475 // set "references" attribute to empty table, unless it is already set:
1476 lua_settop(L, 1);
1477 lua_pushliteral(L, "references"); // 2
1478 lua_rawget(L, 1); // 2
1479 if (!lua_toboolean(L, 2)) {
1480 lua_pushliteral(L, "references"); // 3
1481 lua_newtable(L); // 4
1482 lua_rawset(L, 1);
1484 // set "foreign_keys" attribute to empty table, unless it is already set:
1485 lua_settop(L, 1);
1486 lua_pushliteral(L, "foreign_keys"); // 2
1487 lua_rawget(L, 1); // 2
1488 if (!lua_toboolean(L, 2)) {
1489 lua_pushliteral(L, "foreign_keys"); // 3
1490 lua_newtable(L); // 4
1491 lua_rawset(L, 1);
1493 // return table:
1494 lua_settop(L, 1);
1495 return 1;
1498 // method "get_reference" of classes (models):
1499 static int mondelefant_class_get_reference(lua_State *L) {
1500 lua_settop(L, 2);
1501 while (lua_toboolean(L, 1)) {
1502 // get "references" table:
1503 lua_getfield(L, 1, "references"); // 3
1504 // perform lookup:
1505 lua_pushvalue(L, 2); // 4
1506 lua_gettable(L, 3); // 4
1507 // return result, if lookup was successful:
1508 if (!lua_isnil(L, 4)) return 1;
1509 // replace current table by its prototype:
1510 lua_settop(L, 2);
1511 lua_pushliteral(L, "prototype"); // 3
1512 lua_rawget(L, 1); // 3
1513 lua_replace(L, 1);
1515 // return nothing:
1516 return 0;
1519 // method "iterate_over_references" of classes (models):
1520 static int mondelefant_class_iterate_over_references(lua_State *L) {
1521 return luaL_error(L, "Reference iterator not implemented yet."); // TODO
1524 // method "get_foreign_key_reference_name" of classes (models):
1525 static int mondelefant_class_get_foreign_key_reference_name(lua_State *L) {
1526 lua_settop(L, 2);
1527 while (lua_toboolean(L, 1)) {
1528 // get "foreign_keys" table:
1529 lua_getfield(L, 1, "foreign_keys"); // 3
1530 // perform lookup:
1531 lua_pushvalue(L, 2); // 4
1532 lua_gettable(L, 3); // 4
1533 // return result, if lookup was successful:
1534 if (!lua_isnil(L, 4)) return 1;
1535 // replace current table by its prototype:
1536 lua_settop(L, 2);
1537 lua_pushliteral(L, "prototype"); // 3
1538 lua_rawget(L, 1); // 3
1539 lua_replace(L, 1);
1541 // return nothing:
1542 return 0;
1545 // meta-method "__index" of database result lists and objects:
1546 static int mondelefant_result_index(lua_State *L) {
1547 const char *result_type;
1548 // only lookup, when key is a string not beginning with an underscore:
1549 if (lua_type(L, 2) != LUA_TSTRING || lua_tostring(L, 2)[0] == '_') {
1550 return 0;
1552 // value of "_class" attribute or default class on stack position 3:
1553 lua_settop(L, 2);
1554 lua_getfield(L, 1, "_class"); // 3
1555 if (!lua_toboolean(L, 3)) {
1556 lua_settop(L, 2);
1557 lua_getfield(L,
1558 LUA_REGISTRYINDEX,
1559 MONDELEFANT_CLASS_PROTO_REGKEY
1560 ); // 3
1562 // get value of "_type" attribute:
1563 lua_getfield(L, 1, "_type"); // 4
1564 result_type = lua_tostring(L, 4);
1565 // different lookup for lists and objects:
1566 if (result_type && !strcmp(result_type, "object")) { // object
1567 lua_settop(L, 3);
1568 // try inherited attributes, methods or getter functions:
1569 lua_pushvalue(L, 3); // 4
1570 while (lua_toboolean(L, 4)) {
1571 lua_getfield(L, 4, "object"); // 5
1572 lua_pushvalue(L, 2); // 6
1573 lua_gettable(L, 5); // 6
1574 if (!lua_isnil(L, 6)) return 1;
1575 lua_settop(L, 4);
1576 lua_getfield(L, 4, "object_get"); // 5
1577 lua_pushvalue(L, 2); // 6
1578 lua_gettable(L, 5); // 6
1579 if (lua_toboolean(L, 6)) {
1580 lua_pushvalue(L, 1); // 7
1581 lua_call(L, 1, 1); // 6
1582 return 1;
1584 lua_settop(L, 4);
1585 lua_pushliteral(L, "prototype"); // 5
1586 lua_rawget(L, 4); // 5
1587 lua_replace(L, 4);
1589 lua_settop(L, 3);
1590 // try primary keys of referenced objects:
1591 lua_pushcfunction(L,
1592 mondelefant_class_get_foreign_key_reference_name
1593 ); // 4
1594 lua_pushvalue(L, 3); // 5
1595 lua_pushvalue(L, 2); // 6
1596 lua_call(L, 2, 1); // 4
1597 if (!lua_isnil(L, 4)) {
1598 // reference name at stack position 4
1599 lua_pushcfunction(L, mondelefant_class_get_reference); // 5
1600 lua_pushvalue(L, 3); // 6
1601 lua_pushvalue(L, 4); // 7
1602 lua_call(L, 2, 1); // reference info at stack position 5
1603 lua_getfield(L, 1, "_ref"); // 6
1604 lua_getfield(L, 5, "ref"); // 7
1605 lua_gettable(L, 6); // 7
1606 if (!lua_isnil(L, 7)) {
1607 if (lua_toboolean(L, 7)) {
1608 lua_getfield(L, 5, "that_key"); // 8
1609 if (lua_isnil(L, 8)) {
1610 return luaL_error(L, "Missing 'that_key' entry in model reference.");
1612 lua_gettable(L, 7); // 8
1613 } else {
1614 lua_pushnil(L);
1616 return 1;
1619 lua_settop(L, 3);
1620 lua_getfield(L, 1, "_data"); // _data table on stack position 4
1621 // try normal data field info:
1622 lua_pushvalue(L, 2); // 5
1623 lua_gettable(L, 4); // 5
1624 if (!lua_isnil(L, 5)) return 1;
1625 lua_settop(L, 4); // keep _data table on stack
1626 // try cached referenced object (or cached NULL reference):
1627 lua_getfield(L, 1, "_ref"); // 5
1628 lua_pushvalue(L, 2); // 6
1629 lua_gettable(L, 5); // 6
1630 if (lua_isboolean(L, 6) && !lua_toboolean(L, 6)) {
1631 lua_pushnil(L);
1632 return 1;
1633 } else if (!lua_isnil(L, 6)) {
1634 return 1;
1636 lua_settop(L, 4);
1637 // try to load a referenced object:
1638 lua_pushcfunction(L, mondelefant_class_get_reference); // 5
1639 lua_pushvalue(L, 3); // 6
1640 lua_pushvalue(L, 2); // 7
1641 lua_call(L, 2, 1); // 5
1642 if (!lua_isnil(L, 5)) {
1643 lua_settop(L, 2);
1644 lua_getfield(L, 1, "load"); // 3
1645 lua_pushvalue(L, 1); // 4 (self)
1646 lua_pushvalue(L, 2); // 5
1647 lua_call(L, 2, 0);
1648 lua_settop(L, 2);
1649 lua_getfield(L, 1, "_ref"); // 3
1650 lua_pushvalue(L, 2); // 4
1651 lua_gettable(L, 3); // 4
1652 if (lua_isboolean(L, 4) && !lua_toboolean(L, 4)) lua_pushnil(L); // TODO: use special object instead of false
1653 return 1;
1655 lua_settop(L, 4);
1656 // try proxy access to document in special column:
1657 lua_getfield(L, 3, "document_column"); // 5
1658 if (lua_toboolean(L, 5)) {
1659 lua_gettable(L, 4); // 5
1660 if (!lua_isnil(L, 5)) {
1661 lua_pushvalue(L, 2); // 6
1662 lua_gettable(L, 5); // 6
1663 if (!lua_isnil(L, 6)) return 1;
1666 return 0;
1667 } else if (result_type && !strcmp(result_type, "list")) { // list
1668 lua_settop(L, 3);
1669 // try inherited list attributes or methods:
1670 while (lua_toboolean(L, 3)) {
1671 lua_getfield(L, 3, "list"); // 4
1672 lua_pushvalue(L, 2); // 5
1673 lua_gettable(L, 4); // 5
1674 if (!lua_isnil(L, 5)) return 1;
1675 lua_settop(L, 3);
1676 lua_pushliteral(L, "prototype"); // 4
1677 lua_rawget(L, 3); // 4
1678 lua_replace(L, 3);
1681 // return nothing:
1682 return 0;
1685 // meta-method "__newindex" of database result lists and objects:
1686 static int mondelefant_result_newindex(lua_State *L) {
1687 const char *result_type;
1688 // perform rawset, unless key is a string not starting with underscore:
1689 lua_settop(L, 3);
1690 if (lua_type(L, 2) != LUA_TSTRING || lua_tostring(L, 2)[0] == '_') {
1691 lua_rawset(L, 1);
1692 return 1;
1694 // value of "_class" attribute or default class on stack position 4:
1695 lua_settop(L, 3);
1696 lua_getfield(L, 1, "_class"); // 4
1697 if (!lua_toboolean(L, 4)) {
1698 lua_settop(L, 3);
1699 lua_getfield(L,
1700 LUA_REGISTRYINDEX,
1701 MONDELEFANT_CLASS_PROTO_REGKEY
1702 ); // 4
1704 // get value of "_type" attribute:
1705 lua_getfield(L, 1, "_type"); // 5
1706 result_type = lua_tostring(L, 5);
1707 // distinguish between lists and objects:
1708 if (result_type && !strcmp(result_type, "object")) { // objects
1709 lua_settop(L, 4);
1710 // try object setter functions:
1711 lua_pushvalue(L, 4); // 5
1712 while (lua_toboolean(L, 5)) {
1713 lua_getfield(L, 5, "object_set"); // 6
1714 lua_pushvalue(L, 2); // 7
1715 lua_gettable(L, 6); // 7
1716 if (lua_toboolean(L, 7)) {
1717 lua_pushvalue(L, 1); // 8
1718 lua_pushvalue(L, 3); // 9
1719 lua_call(L, 2, 0);
1720 return 0;
1722 lua_settop(L, 5);
1723 lua_pushliteral(L, "prototype"); // 6
1724 lua_rawget(L, 5); // 6
1725 lua_replace(L, 5);
1727 lua_settop(L, 4);
1728 lua_getfield(L, 1, "_data"); // _data table on stack position 5
1729 // check, if a object reference is changed:
1730 lua_pushcfunction(L, mondelefant_class_get_reference); // 6
1731 lua_pushvalue(L, 4); // 7
1732 lua_pushvalue(L, 2); // 8
1733 lua_call(L, 2, 1); // 6
1734 if (!lua_isnil(L, 6)) {
1735 // store object in _ref table (use false for nil): // TODO: use special object instead of false
1736 lua_getfield(L, 1, "_ref"); // 7
1737 lua_pushvalue(L, 2); // 8
1738 if (lua_isnil(L, 3)) lua_pushboolean(L, 0); // 9
1739 else lua_pushvalue(L, 3); // 9
1740 lua_settable(L, 7);
1741 lua_settop(L, 6);
1742 // delete referencing key from _data table:
1743 lua_getfield(L, 6, "this_key"); // 7
1744 if (lua_isnil(L, 7)) {
1745 return luaL_error(L, "Missing 'this_key' entry in model reference.");
1747 lua_pushvalue(L, 7); // 8
1748 lua_pushnil(L); // 9
1749 lua_settable(L, 5);
1750 lua_getfield(L, 1, "_dirty"); // 8
1751 lua_pushvalue(L, 7); // 9
1752 lua_pushboolean(L, 1); // 10
1753 lua_settable(L, 8);
1754 return 0;
1756 lua_settop(L, 5);
1757 // check proxy access to document in special column:
1758 lua_getfield(L, 4, "document_column"); // 6
1759 if (lua_toboolean(L, 6)) {
1760 lua_getfield(L, 1, "_column_info"); // 7
1761 if (!lua_isnil(L, 7)) { // TODO: quick fix to avoid problems on document creation
1762 lua_pushvalue(L, 2); // 8
1763 lua_gettable(L, 7); // 8
1764 if (!lua_toboolean(L, 8)) {
1765 lua_settop(L, 6);
1766 lua_gettable(L, 5); // 6
1767 if (lua_isnil(L, 6)) {
1768 return luaL_error(L, "Cannot write to document column: document is nil");
1770 lua_pushvalue(L, 2); // 7
1771 lua_pushvalue(L, 3); // 8
1772 lua_settable(L, 6);
1773 return 0;
1775 } // TODO: quick fix to avoid problems on document creation
1777 lua_settop(L, 5);
1778 // store value in data field info:
1779 lua_pushvalue(L, 2); // 6
1780 lua_pushvalue(L, 3); // 7
1781 lua_settable(L, 5);
1782 lua_settop(L, 4);
1783 // mark field as dirty (needs to be UPDATEd on save):
1784 lua_getfield(L, 1, "_dirty"); // 5
1785 lua_pushvalue(L, 2); // 6
1786 lua_pushboolean(L, 1); // 7
1787 lua_settable(L, 5);
1788 lua_settop(L, 4);
1789 // reset reference cache, if neccessary:
1790 lua_pushcfunction(L,
1791 mondelefant_class_get_foreign_key_reference_name
1792 ); // 5
1793 lua_pushvalue(L, 4); // 6
1794 lua_pushvalue(L, 2); // 7
1795 lua_call(L, 2, 1); // 5
1796 if (!lua_isnil(L, 5)) {
1797 lua_getfield(L, 1, "_ref"); // 6
1798 lua_pushvalue(L, 5); // 7
1799 lua_pushnil(L); // 8
1800 lua_settable(L, 6);
1802 return 0;
1803 } else { // non-objects (i.e. lists)
1804 // perform rawset:
1805 lua_settop(L, 3);
1806 lua_rawset(L, 1);
1807 return 0;
1811 // meta-method "__index" of classes (models):
1812 static int mondelefant_class_index(lua_State *L) {
1813 // perform lookup in prototype:
1814 lua_settop(L, 2);
1815 lua_pushliteral(L, "prototype"); // 3
1816 lua_rawget(L, 1); // 3
1817 lua_pushvalue(L, 2); // 4
1818 lua_gettable(L, 3); // 4
1819 return 1;
1822 // registration information for functions of library:
1823 static const struct luaL_Reg mondelefant_module_functions[] = {
1824 {"connect", mondelefant_connect},
1825 {"set_class", mondelefant_set_class},
1826 {"new_class", mondelefant_new_class},
1827 {NULL, NULL}
1828 };
1830 // registration information for meta-methods of database connections:
1831 static const struct luaL_Reg mondelefant_conn_mt_functions[] = {
1832 {"__gc", mondelefant_conn_free},
1833 {"__index", mondelefant_conn_index},
1834 {"__newindex", mondelefant_conn_newindex},
1835 {NULL, NULL}
1836 };
1838 // registration information for methods of database connections:
1839 static const struct luaL_Reg mondelefant_conn_methods[] = {
1840 {"close", mondelefant_conn_close},
1841 {"is_ok", mondelefant_conn_is_ok},
1842 {"get_transaction_status", mondelefant_conn_get_transaction_status},
1843 {"try_wait", mondelefant_conn_try_wait},
1844 {"wait", mondelefant_conn_wait},
1845 {"create_list", mondelefant_conn_create_list},
1846 {"create_object", mondelefant_conn_create_object},
1847 {"quote_string", mondelefant_conn_quote_string},
1848 {"quote_binary", mondelefant_conn_quote_binary},
1849 {"assemble_command", mondelefant_conn_assemble_command},
1850 {"try_query", mondelefant_conn_try_query},
1851 {"query", mondelefant_conn_query},
1852 {NULL, NULL}
1853 };
1855 // registration information for meta-methods of error objects:
1856 static const struct luaL_Reg mondelefant_errorobject_mt_functions[] = {
1857 {NULL, NULL}
1858 };
1860 // registration information for methods of error objects:
1861 static const struct luaL_Reg mondelefant_errorobject_methods[] = {
1862 {"escalate", lua_error},
1863 {"is_kind_of", mondelefant_errorobject_is_kind_of},
1864 {NULL, NULL}
1865 };
1867 // registration information for meta-methods of database result lists/objects:
1868 static const struct luaL_Reg mondelefant_result_mt_functions[] = {
1869 {"__index", mondelefant_result_index},
1870 {"__newindex", mondelefant_result_newindex},
1871 {NULL, NULL}
1872 };
1874 // registration information for methods of database result lists/objects:
1875 static const struct luaL_Reg mondelefant_class_mt_functions[] = {
1876 {"__index", mondelefant_class_index},
1877 {NULL, NULL}
1878 };
1880 // registration information for methods of classes (models):
1881 static const struct luaL_Reg mondelefant_class_methods[] = {
1882 {"get_reference", mondelefant_class_get_reference},
1883 {"iterate_over_references", mondelefant_class_iterate_over_references},
1884 {"get_foreign_key_reference_name",
1885 mondelefant_class_get_foreign_key_reference_name},
1886 {NULL, NULL}
1887 };
1889 // registration information for methods of database result objects (not lists!):
1890 static const struct luaL_Reg mondelefant_object_methods[] = {
1891 {NULL, NULL}
1892 };
1894 // registration information for methods of database result lists (not single objects!):
1895 static const struct luaL_Reg mondelefant_list_methods[] = {
1896 {NULL, NULL}
1897 };
1899 // luaopen function to initialize/register library:
1900 int luaopen_mondelefant_native(lua_State *L) {
1901 lua_settop(L, 0);
1902 lua_newtable(L); // module at stack position 1
1903 luaL_setfuncs(L, mondelefant_module_functions, 0);
1905 lua_pushvalue(L, 1); // 2
1906 lua_setfield(L, LUA_REGISTRYINDEX, MONDELEFANT_MODULE_REGKEY);
1908 lua_newtable(L); // 2
1909 // NOTE: only PostgreSQL is supported yet:
1910 luaL_setfuncs(L, mondelefant_conn_methods, 0);
1911 lua_setfield(L, 1, "postgresql_connection_prototype");
1912 lua_newtable(L); // 2
1913 lua_setfield(L, 1, "connection_prototype");
1915 luaL_newmetatable(L, MONDELEFANT_CONN_MT_REGKEY); // 2
1916 luaL_setfuncs(L, mondelefant_conn_mt_functions, 0);
1917 lua_settop(L, 1);
1918 luaL_newmetatable(L, MONDELEFANT_RESULT_MT_REGKEY); // 2
1919 luaL_setfuncs(L, mondelefant_result_mt_functions, 0);
1920 lua_setfield(L, 1, "result_metatable");
1921 luaL_newmetatable(L, MONDELEFANT_CLASS_MT_REGKEY); // 2
1922 luaL_setfuncs(L, mondelefant_class_mt_functions, 0);
1923 lua_setfield(L, 1, "class_metatable");
1925 lua_newtable(L); // 2
1926 luaL_setfuncs(L, mondelefant_class_methods, 0);
1927 lua_newtable(L); // 3
1928 luaL_setfuncs(L, mondelefant_object_methods, 0);
1929 lua_setfield(L, 2, "object");
1930 lua_newtable(L); // 3
1931 lua_setfield(L, 2, "object_get");
1932 lua_newtable(L); // 3
1933 lua_setfield(L, 2, "object_set");
1934 lua_newtable(L); // 3
1935 luaL_setfuncs(L, mondelefant_list_methods, 0);
1936 lua_setfield(L, 2, "list");
1937 lua_newtable(L); // 3
1938 lua_setfield(L, 2, "references");
1939 lua_newtable(L); // 3
1940 lua_setfield(L, 2, "foreign_keys");
1941 lua_pushvalue(L, 2); // 3
1942 lua_setfield(L, LUA_REGISTRYINDEX, MONDELEFANT_CLASS_PROTO_REGKEY);
1943 lua_setfield(L, 1, "class_prototype");
1945 luaL_newmetatable(L, MONDELEFANT_ERROROBJECT_MT_REGKEY); // 2
1946 luaL_setfuncs(L, mondelefant_errorobject_mt_functions, 0);
1947 lua_newtable(L); // 3
1948 luaL_setfuncs(L, mondelefant_errorobject_methods, 0);
1949 lua_setfield(L, 2, "__index");
1950 lua_setfield(L, 1, "errorobject_metatable");
1952 return 1;

Impressum / About Us