webmcp

view libraries/mondelefant/mondelefant_native.c @ 421:c343ce9092ee

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

Impressum / About Us