webmcp

view libraries/mondelefant/mondelefant_native.c @ 555:16197a40c7a9

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

Impressum / About Us