webmcp

view libraries/mondelefant/mondelefant_native.c @ 409:ebe9416db4e0

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

Impressum / About Us