webmcp

view libraries/mondelefant/mondelefant_native.c @ 414:015be25c98dd

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

Impressum / About Us