webmcp

view libraries/mondelefant/mondelefant_native.c @ 393:b2d2ff6e4385

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

Impressum / About Us