webmcp

view libraries/mondelefant/mondelefant_native.c @ 406:36f0d1d5ed7d

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

Impressum / About Us