webmcp

view libraries/mondelefant/mondelefant_native.c @ 397:46ba2168693a

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

Impressum / About Us