webmcp

view libraries/mondelefant/mondelefant_native.c @ 408:fd5880964d99

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

Impressum / About Us