webmcp

view libraries/mondelefant/mondelefant_native.c @ 407:0e641ac76647

Some code-cleanup and fixed comments; Better behavior on out-of-memory errors in certain cases
author jbe
date Wed Jan 06 22:59:39 2016 +0100 (2016-01-06)
parents 36f0d1d5ed7d
children fd5880964d99
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 // throw error in case of (unexpected) error of PQconnectdb call:
259 if (!conn->pgconn) return luaL_error(L,
260 "Error in libpq while creating 'PGconn' structure."
261 );
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 luaL_Buffer buf;
563 char *output;
564 size_t output_len;
565 // get database connection object:
566 conn = mondelefant_get_conn(L, 1);
567 // get second argument, which must be a string:
568 input = luaL_checklstring(L, 2, &input_len);
569 // throw error, if string is too long:
570 if (input_len > (SIZE_MAX / sizeof(char) - 3) / 2) {
571 return luaL_error(L, "String to be escaped is too long.");
572 }
573 // allocate memory for quoted string:
574 output = luaL_buffinitsize(L, &buf, (2 * input_len + 3) * sizeof(char));
575 // do escaping by calling PQescapeStringConn and enclosing result with
576 // single quotes:
577 output[0] = '\'';
578 output_len = PQescapeStringConn(
579 conn->pgconn, output + 1, input, input_len, NULL
580 );
581 output[output_len + 1] = '\'';
582 output[output_len + 2] = 0;
583 // create Lua string:
584 luaL_addsize(&buf, output_len + 2);
585 // return Lua string:
586 return 1;
587 }
589 // method "quote_binary" of database handles:
590 static int mondelefant_conn_quote_binary(lua_State *L) {
591 mondelefant_conn_t *conn;
592 const char *input;
593 size_t input_len;
594 char *output;
595 size_t output_len;
596 luaL_Buffer buf;
597 // get database connection object:
598 conn = mondelefant_get_conn(L, 1);
599 // get second argument, which must be a string:
600 input = luaL_checklstring(L, 2, &input_len);
601 // call PQescapeByteaConn, which allocates memory itself:
602 output = (char *)PQescapeByteaConn(
603 conn->pgconn, (const unsigned char *)input, input_len, &output_len
604 );
605 // if PQescapeByteaConn returned NULL, then throw error:
606 if (!output) {
607 return luaL_error(L, "Could not allocate memory for binary quoting.");
608 }
609 // create Lua string enclosed by single quotes:
610 luaL_buffinit(L, &buf);
611 luaL_addchar(&buf, '\'');
612 luaL_addlstring(&buf, output, output_len - 1);
613 luaL_addchar(&buf, '\'');
614 luaL_pushresult(&buf);
615 // free memory allocated by PQescapeByteaConn:
616 PQfreemem(output);
617 // return Lua string:
618 return 1;
619 }
621 // method "assemble_command" of database handles:
622 static int mondelefant_conn_assemble_command(lua_State *L) {
623 mondelefant_conn_t *conn;
624 int paramidx = 2;
625 const char *template;
626 size_t template_pos = 0;
627 luaL_Buffer buf;
628 // get database connection object:
629 conn = mondelefant_get_conn(L, 1);
630 // if second argument is a string, return this string:
631 if (lua_type(L, 2) == LUA_TSTRING) {
632 lua_settop(L, 2);
633 return 1;
634 }
635 // if second argument has __tostring meta-method,
636 // then use this method and return its result:
637 if (luaL_callmeta(L, 2, "__tostring")) return 1;
638 // otherwise, require that second argument is a table:
639 luaL_checktype(L, 2, LUA_TTABLE);
640 // set stack top:
641 lua_settop(L, 2);
642 // get first element of table, which must be a string:
643 lua_rawgeti(L, 2, 1); // 3
644 luaL_argcheck(L,
645 lua_isstring(L, 3),
646 2,
647 "First entry of SQL command structure is not a string."
648 );
649 template = lua_tostring(L, 3);
650 // get value of "input_converter" attribute of database connection:
651 lua_pushliteral(L, "input_converter"); // 4
652 lua_gettable(L, 1); // input_converter at stack position 4
653 // reserve space on Lua stack:
654 lua_pushnil(L); // free space at stack position 5
655 lua_pushnil(L); // free space at stack position 6
656 // initialize Lua buffer for result string:
657 luaL_buffinit(L, &buf);
658 // fill buffer in loop:
659 while (1) {
660 // variable declaration:
661 char c;
662 // get next character:
663 c = template[template_pos++];
664 // break, when character is NULL byte:
665 if (!c) break;
666 // question-mark and dollar-sign are special characters:
667 if (c == '?' || c == '$') { // special character found
668 // check, if same character follows:
669 if (template[template_pos] == c) { // special character is escaped
670 // consume two characters of input and add one character to buffer:
671 template_pos++;
672 luaL_addchar(&buf, c);
673 } else { // special character is not escaped
674 luaL_Buffer keybuf;
675 int subcmd;
676 // set 'subcmd' = true, if special character was a dollar-sign,
677 // set 'subcmd' = false, if special character was a question-mark:
678 subcmd = (c == '$');
679 // read any number of alpha numeric chars or underscores
680 // and store them on Lua stack:
681 luaL_buffinit(L, &keybuf);
682 while (1) {
683 c = template[template_pos];
684 if (
685 (c < 'A' || c > 'Z') &&
686 (c < 'a' || c > 'z') &&
687 (c < '0' || c > '9') &&
688 (c != '_')
689 ) break;
690 luaL_addchar(&keybuf, c);
691 template_pos++;
692 }
693 luaL_pushresult(&keybuf);
694 // check, if any characters matched:
695 if (lua_rawlen(L, -1)) {
696 // if any alpha numeric chars or underscores were found,
697 // push them on stack as a Lua string and use them to lookup
698 // value from second argument:
699 lua_pushvalue(L, -1); // save key on stack
700 lua_gettable(L, 2); // fetch value (raw-value)
701 } else {
702 // otherwise push nil and use numeric lookup based on 'paramidx':
703 lua_pop(L, 1);
704 lua_pushnil(L); // put nil on key position
705 lua_rawgeti(L, 2, paramidx++); // fetch value (raw-value)
706 }
707 // Lua stack contains: ..., <buffer>, key, raw-value
708 // branch according to type of special character ("?" or "$"):
709 if (subcmd) { // dollar-sign
710 size_t i;
711 size_t count;
712 // store fetched value (which is supposed to be sub-structure)
713 // on Lua stack position 5 and drop key:
714 lua_replace(L, 5);
715 lua_pop(L, 1);
716 // Lua stack contains: ..., <buffer>
717 // check, if fetched value is really a sub-structure:
718 luaL_argcheck(L,
719 !lua_isnil(L, 5),
720 2,
721 "SQL sub-structure not found."
722 );
723 luaL_argcheck(L,
724 lua_type(L, 5) == LUA_TTABLE,
725 2,
726 "SQL sub-structure must be a table."
727 );
728 // Lua stack contains: ..., <buffer>
729 // get value of "sep" attribute of sub-structure,
730 // and place it on Lua stack position 6:
731 lua_getfield(L, 5, "sep");
732 lua_replace(L, 6);
733 // if seperator is nil, then use ", " as default,
734 // if seperator is neither nil nor a string, then throw error:
735 if (lua_isnil(L, 6)) {
736 lua_pushstring(L, ", ");
737 lua_replace(L, 6);
738 } else {
739 luaL_argcheck(L,
740 lua_isstring(L, 6),
741 2,
742 "Seperator of SQL sub-structure has to be a string."
743 );
744 }
745 // iterate over items of sub-structure:
746 count = lua_rawlen(L, 5);
747 for (i = 0; i < count; i++) {
748 // add seperator, unless this is the first run:
749 if (i) {
750 lua_pushvalue(L, 6);
751 luaL_addvalue(&buf);
752 }
753 // recursivly apply assemble function and add results to buffer:
754 lua_pushcfunction(L, mondelefant_conn_assemble_command);
755 lua_pushvalue(L, 1);
756 lua_rawgeti(L, 5, i+1);
757 lua_call(L, 2, 1);
758 luaL_addvalue(&buf);
759 }
760 } else { // question-mark
761 if (lua_toboolean(L, 4)) {
762 // call input_converter with connection handle, raw-value and
763 // an info-table which contains a "field_name" entry with the
764 // used key:
765 lua_pushvalue(L, 4);
766 lua_pushvalue(L, 1);
767 lua_pushvalue(L, -3);
768 lua_newtable(L);
769 lua_pushvalue(L, -6);
770 lua_setfield(L, -2, "field_name");
771 lua_call(L, 3, 1);
772 // Lua stack contains: ..., <buffer>, key, raw-value, final-value
773 // remove key and raw-value:
774 lua_remove(L, -2);
775 lua_remove(L, -2);
776 // Lua stack contains: ..., <buffer>, final-value
777 // throw error, if final-value is not a string:
778 if (!lua_isstring(L, -1)) {
779 return luaL_error(L, "input_converter returned non-string.");
780 }
781 } else {
782 // remove key from stack:
783 lua_remove(L, -2);
784 // Lua stack contains: ..., <buffer>, raw-value
785 // branch according to type of value:
786 if (lua_isnil(L, -1)) { // value is nil
787 // push string "NULL" to stack:
788 lua_pushliteral(L, "NULL");
789 } else if (lua_type(L, -1) == LUA_TBOOLEAN) { // value is boolean
790 // push strings "TRUE" or "FALSE" to stack:
791 lua_pushstring(L, lua_toboolean(L, -1) ? "TRUE" : "FALSE");
792 } else if (lua_isstring(L, -1)) { // value is string or number
793 // NOTE: In this version of lua a number will be converted
794 // push output of "quote_string" method of database
795 // connection to stack:
796 lua_tostring(L, -1);
797 lua_pushcfunction(L, mondelefant_conn_quote_string);
798 lua_pushvalue(L, 1);
799 lua_pushvalue(L, -3);
800 lua_call(L, 2, 1);
801 } else { // value is of other type
802 // throw error:
803 return luaL_error(L,
804 "Unable to convert SQL value due to unknown type "
805 "or missing input_converter."
806 );
807 }
808 // Lua stack contains: ..., <buffer>, raw-value, final-value
809 // remove raw-value:
810 lua_remove(L, -2);
811 // Lua stack contains: ..., <buffer>, final-value
812 }
813 // append final-value to buffer:
814 luaL_addvalue(&buf);
815 }
816 }
817 } else { // character is not special
818 // just copy character:
819 luaL_addchar(&buf, c);
820 }
821 }
822 // return string in buffer:
823 luaL_pushresult(&buf);
824 return 1;
825 }
827 // max number of SQL statements executed by one "query" method call:
828 #define MONDELEFANT_MAX_COMMAND_COUNT 64
829 // max number of columns in a database result:
830 #define MONDELEFANT_MAX_COLUMN_COUNT 1024
831 // enum values for 'modes' array in C-function below:
832 #define MONDELEFANT_QUERY_MODE_LIST 1
833 #define MONDELEFANT_QUERY_MODE_OBJECT 2
834 #define MONDELEFANT_QUERY_MODE_OPT_OBJECT 3
836 // method "try_query" of database handles:
837 static int mondelefant_conn_try_query(lua_State *L) {
838 mondelefant_conn_t *conn;
839 int command_count;
840 int command_idx;
841 int modes[MONDELEFANT_MAX_COMMAND_COUNT];
842 luaL_Buffer buf;
843 int sent_success;
844 PGresult *res;
845 int rows, cols, row, col;
846 // get database connection object:
847 conn = mondelefant_get_conn(L, 1);
848 // calculate number of commands (2 arguments for one command):
849 command_count = lua_gettop(L) / 2;
850 // push nil on stack, which is needed, if last mode was ommitted:
851 lua_pushnil(L);
852 // throw error, if number of commands is too high:
853 if (command_count > MONDELEFANT_MAX_COMMAND_COUNT) {
854 return luaL_error(L, "Exceeded maximum command count in one query.");
855 }
856 // create SQL string, store query modes and push SQL string on stack:
857 luaL_buffinit(L, &buf);
858 for (command_idx = 0; command_idx < command_count; command_idx++) {
859 int mode;
860 int mode_idx; // stack index of mode string
861 if (command_idx) luaL_addchar(&buf, ' ');
862 lua_pushcfunction(L, mondelefant_conn_assemble_command);
863 lua_pushvalue(L, 1);
864 lua_pushvalue(L, 2 + 2 * command_idx);
865 lua_call(L, 2, 1);
866 luaL_addvalue(&buf);
867 luaL_addchar(&buf, ';');
868 mode_idx = 3 + 2 * command_idx;
869 if (lua_isnil(L, mode_idx)) {
870 mode = MONDELEFANT_QUERY_MODE_LIST;
871 } else {
872 const char *modestr;
873 modestr = luaL_checkstring(L, mode_idx);
874 if (!strcmp(modestr, "list")) {
875 mode = MONDELEFANT_QUERY_MODE_LIST;
876 } else if (!strcmp(modestr, "object")) {
877 mode = MONDELEFANT_QUERY_MODE_OBJECT;
878 } else if (!strcmp(modestr, "opt_object")) {
879 mode = MONDELEFANT_QUERY_MODE_OPT_OBJECT;
880 } else {
881 return luaL_argerror(L, mode_idx, "unknown query mode");
882 }
883 }
884 modes[command_idx] = mode;
885 }
886 luaL_pushresult(&buf); // stack position unknown
887 lua_replace(L, 2); // SQL command string to stack position 2
888 // call sql_tracer, if set:
889 lua_settop(L, 2);
890 lua_getfield(L, 1, "sql_tracer"); // tracer at stack position 3
891 if (lua_toboolean(L, 3)) {
892 lua_pushvalue(L, 1); // 4
893 lua_pushvalue(L, 2); // 5
894 lua_call(L, 2, 1); // trace callback at stack position 3
895 }
896 // NOTE: If no tracer was found, then nil or false is stored at stack
897 // position 3.
898 // call PQsendQuery function and store result in 'sent_success' variable:
899 sent_success = PQsendQuery(conn->pgconn, lua_tostring(L, 2));
900 // create preliminary result table:
901 lua_newtable(L); // results in table at stack position 4
902 // iterate over results using function PQgetResult to fill result table:
903 for (command_idx = 0; ; command_idx++) {
904 int mode;
905 char binary[MONDELEFANT_MAX_COLUMN_COUNT];
906 ExecStatusType pgstatus;
907 // fetch mode which was given for the command:
908 mode = modes[command_idx];
909 // if PQsendQuery call was successful, then fetch result data:
910 if (sent_success) {
911 // NOTE: PQgetResult called one extra time. Break only, if all
912 // queries have been processed and PQgetResult returned NULL.
913 res = PQgetResult(conn->pgconn);
914 if (command_idx >= command_count && !res) break;
915 if (res) {
916 pgstatus = PQresultStatus(res);
917 rows = PQntuples(res);
918 cols = PQnfields(res);
919 }
920 }
921 // handle errors:
922 if (
923 !sent_success || command_idx >= command_count || !res ||
924 (pgstatus != PGRES_TUPLES_OK && pgstatus != PGRES_COMMAND_OK) ||
925 (rows < 1 && mode == MONDELEFANT_QUERY_MODE_OBJECT) ||
926 (rows > 1 && mode != MONDELEFANT_QUERY_MODE_LIST)
927 ) {
928 const char *command;
929 command = lua_tostring(L, 2);
930 lua_newtable(L); // 5
931 luaL_setmetatable(L, MONDELEFANT_ERROROBJECT_MT_REGKEY);
932 lua_pushvalue(L, 1);
933 lua_setfield(L, 5, "connection");
934 lua_pushvalue(L, 2);
935 lua_setfield(L, 5, "sql_command");
936 if (!sent_success) {
937 lua_pushliteral(L, MONDELEFANT_ERRCODE_CONNECTION);
938 lua_setfield(L, 5, "code");
939 mondelefant_push_first_line(L, PQerrorMessage(conn->pgconn));
940 lua_setfield(L, 5, "message");
941 } else {
942 lua_pushinteger(L, command_idx + 1);
943 lua_setfield(L, 5, "command_number");
944 if (!res) {
945 lua_pushliteral(L, MONDELEFANT_ERRCODE_RESULTCOUNT_LOW);
946 lua_setfield(L, 5, "code");
947 lua_pushliteral(L, "Received too few database result sets.");
948 lua_setfield(L, 5, "message");
949 } else if (command_idx >= command_count) {
950 lua_pushliteral(L, MONDELEFANT_ERRCODE_RESULTCOUNT_HIGH);
951 lua_setfield(L, 5, "code");
952 lua_pushliteral(L, "Received too many database result sets.");
953 lua_setfield(L, 5, "message");
954 } else if (
955 pgstatus != PGRES_TUPLES_OK && pgstatus != PGRES_COMMAND_OK
956 ) {
957 const char *sqlstate;
958 const char *errmsg;
959 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_SEVERITY));
960 lua_setfield(L, 5, "pg_severity");
961 sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
962 if (sqlstate) {
963 lua_pushstring(L, sqlstate);
964 lua_setfield(L, 5, "pg_sqlstate");
965 lua_pushstring(L, mondelefant_translate_errcode(sqlstate));
966 lua_setfield(L, 5, "code");
967 } else {
968 lua_pushliteral(L, MONDELEFANT_ERRCODE_UNKNOWN);
969 lua_setfield(L, 5, "code");
970 }
971 errmsg = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
972 if (errmsg) {
973 mondelefant_push_first_line(L, errmsg);
974 lua_setfield(L, 5, "message");
975 lua_pushstring(L, errmsg);
976 lua_setfield(L, 5, "pg_message_primary");
977 } else {
978 lua_pushliteral(L,
979 "Error while fetching result, but no error message given."
980 );
981 lua_setfield(L, 5, "message");
982 }
983 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL));
984 lua_setfield(L, 5, "pg_message_detail");
985 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_MESSAGE_HINT));
986 lua_setfield(L, 5, "pg_message_hint");
987 // NOTE: "position" and "pg_internal_position" are recalculated to
988 // byte offsets, as Lua 5.2 is not Unicode aware.
989 {
990 char *tmp;
991 tmp = PQresultErrorField(res, PG_DIAG_STATEMENT_POSITION);
992 if (tmp) {
993 int pos;
994 pos = atoi(tmp) - 1;
995 if (conn->server_encoding == MONDELEFANT_SERVER_ENCODING_UTF8) {
996 pos = utf8_position_to_byte(command, pos);
997 }
998 lua_pushinteger(L, pos + 1);
999 lua_setfield(L, 5, "position");
1003 const char *internal_query;
1004 internal_query = PQresultErrorField(res, PG_DIAG_INTERNAL_QUERY);
1005 lua_pushstring(L, internal_query);
1006 lua_setfield(L, 5, "pg_internal_query");
1007 char *tmp;
1008 tmp = PQresultErrorField(res, PG_DIAG_INTERNAL_POSITION);
1009 if (tmp) {
1010 int pos;
1011 pos = atoi(tmp) - 1;
1012 if (conn->server_encoding == MONDELEFANT_SERVER_ENCODING_UTF8) {
1013 pos = utf8_position_to_byte(internal_query, pos);
1015 lua_pushinteger(L, pos + 1);
1016 lua_setfield(L, 5, "pg_internal_position");
1019 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_CONTEXT));
1020 lua_setfield(L, 5, "pg_context");
1021 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_SOURCE_FILE));
1022 lua_setfield(L, 5, "pg_source_file");
1023 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_SOURCE_LINE));
1024 lua_setfield(L, 5, "pg_source_line");
1025 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_SOURCE_FUNCTION));
1026 lua_setfield(L, 5, "pg_source_function");
1027 } else if (rows < 1 && mode == MONDELEFANT_QUERY_MODE_OBJECT) {
1028 lua_pushliteral(L, MONDELEFANT_ERRCODE_QUERY1_NO_ROWS);
1029 lua_setfield(L, 5, "code");
1030 lua_pushliteral(L, "Expected one row, but got empty set.");
1031 lua_setfield(L, 5, "message");
1032 } else if (rows > 1 && mode != MONDELEFANT_QUERY_MODE_LIST) {
1033 lua_pushliteral(L, MONDELEFANT_ERRCODE_QUERY1_MULTIPLE_ROWS);
1034 lua_setfield(L, 5, "code");
1035 lua_pushliteral(L, "Got more than one result row.");
1036 lua_setfield(L, 5, "message");
1037 } else {
1038 // should not happen
1039 abort();
1041 if (res) {
1042 PQclear(res);
1043 while ((res = PQgetResult(conn->pgconn))) PQclear(res);
1046 if (lua_toboolean(L, 3)) {
1047 lua_pushvalue(L, 3);
1048 lua_pushvalue(L, 5);
1049 lua_call(L, 1, 0);
1051 return 1;
1053 // call "create_list" or "create_object" method of database handle,
1054 // result will be at stack position 5:
1055 if (modes[command_idx] == MONDELEFANT_QUERY_MODE_LIST) {
1056 lua_pushcfunction(L, mondelefant_conn_create_list); // 5
1057 lua_pushvalue(L, 1); // 6
1058 lua_call(L, 1, 1); // 5
1059 } else {
1060 lua_pushcfunction(L, mondelefant_conn_create_object); // 5
1061 lua_pushvalue(L, 1); // 6
1062 lua_call(L, 1, 1); // 5
1064 // set "_column_info":
1065 lua_newtable(L); // 6
1066 for (col = 0; col < cols; col++) {
1067 lua_newtable(L); // 7
1068 lua_pushstring(L, PQfname(res, col)); // 8
1069 lua_pushvalue(L, 8); // 9
1070 lua_pushvalue(L, 7); // 10
1071 lua_rawset(L, 6);
1072 lua_setfield(L, 7, "field_name");
1073 // _column_info entry (for current column) on stack position 7
1075 Oid tmp;
1076 tmp = PQftable(res, col);
1077 if (tmp == InvalidOid) lua_pushnil(L);
1078 else lua_pushinteger(L, tmp);
1079 lua_setfield(L, 7, "table_oid");
1082 int tmp;
1083 tmp = PQftablecol(res, col);
1084 if (tmp == 0) lua_pushnil(L);
1085 else lua_pushinteger(L, tmp);
1086 lua_setfield(L, 7, "table_column_number");
1089 Oid tmp;
1090 tmp = PQftype(res, col);
1091 binary[col] = (tmp == MONDELEFANT_POSTGRESQL_BINARY_OID);
1092 lua_pushinteger(L, tmp);
1093 lua_setfield(L, 7, "type_oid");
1094 lua_pushstring(L, mondelefant_oid_to_typestr(tmp));
1095 lua_setfield(L, 7, "type");
1098 int tmp;
1099 tmp = PQfmod(res, col);
1100 if (tmp == -1) lua_pushnil(L);
1101 else lua_pushinteger(L, tmp);
1102 lua_setfield(L, 7, "type_modifier");
1104 lua_rawseti(L, 6, col+1);
1106 lua_setfield(L, 5, "_column_info");
1107 // set "_rows_affected":
1109 char *tmp;
1110 tmp = PQcmdTuples(res);
1111 if (tmp[0]) {
1112 lua_pushinteger(L, atoi(tmp));
1113 lua_setfield(L, 5, "_rows_affected");
1116 // set "_oid":
1118 Oid tmp;
1119 tmp = PQoidValue(res);
1120 if (tmp != InvalidOid) {
1121 lua_pushinteger(L, tmp);
1122 lua_setfield(L, 5, "_oid");
1125 // copy data as strings or nil, while performing binary unescaping
1126 // automatically:
1127 if (modes[command_idx] == MONDELEFANT_QUERY_MODE_LIST) {
1128 for (row = 0; row < rows; row++) {
1129 lua_pushcfunction(L, mondelefant_conn_create_object); // 6
1130 lua_pushvalue(L, 1); // 7
1131 lua_call(L, 1, 1); // 6
1132 for (col = 0; col < cols; col++) {
1133 if (PQgetisnull(res, row, col)) {
1134 lua_pushnil(L);
1135 } else if (binary[col]) {
1136 size_t binlen;
1137 char *binval;
1138 binval = (char *)PQunescapeBytea(
1139 (unsigned char *)PQgetvalue(res, row, col), &binlen
1140 );
1141 if (!binval) {
1142 return luaL_error(L,
1143 "Could not allocate memory for binary unescaping."
1144 );
1146 lua_pushlstring(L, binval, binlen);
1147 PQfreemem(binval);
1148 } else {
1149 lua_pushstring(L, PQgetvalue(res, row, col));
1151 lua_rawseti(L, 6, col+1);
1153 lua_rawseti(L, 5, row+1);
1155 } else if (rows == 1) {
1156 for (col = 0; col < cols; col++) {
1157 if (PQgetisnull(res, 0, col)) {
1158 lua_pushnil(L);
1159 } else if (binary[col]) {
1160 size_t binlen;
1161 char *binval;
1162 binval = (char *)PQunescapeBytea(
1163 (unsigned char *)PQgetvalue(res, 0, col), &binlen
1164 );
1165 if (!binval) {
1166 return luaL_error(L,
1167 "Could not allocate memory for binary unescaping."
1168 );
1170 lua_pushlstring(L, binval, binlen);
1171 PQfreemem(binval);
1172 } else {
1173 lua_pushstring(L, PQgetvalue(res, 0, col));
1175 lua_rawseti(L, 5, col+1);
1177 } else {
1178 // no row in optrow mode
1179 lua_pop(L, 1);
1180 lua_pushnil(L);
1182 // save result in result list:
1183 lua_rawseti(L, 4, command_idx+1);
1184 // extra assertion:
1185 if (lua_gettop(L) != 4) abort(); // should not happen
1186 // free memory acquired by libpq:
1187 PQclear(res);
1189 // trace callback at stack position 3
1190 // result at stack position 4 (top of stack)
1191 // if a trace callback is existent, then call:
1192 if (lua_toboolean(L, 3)) {
1193 lua_pushvalue(L, 3);
1194 lua_call(L, 0, 0);
1196 // put result at stack position 3:
1197 lua_replace(L, 3);
1198 // get output converter to stack position 4:
1199 lua_getfield(L, 1, "output_converter");
1200 // get mutability state saver to stack position 5:
1201 lua_getfield(L, LUA_REGISTRYINDEX, MONDELEFANT_MODULE_REGKEY);
1202 lua_getfield(L, -1, "save_mutability_state");
1203 lua_replace(L, -2);
1204 // apply output converters and fill "_data" table according to column names:
1205 for (command_idx = 0; command_idx < command_count; command_idx++) {
1206 int mode;
1207 mode = modes[command_idx];
1208 lua_rawgeti(L, 3, command_idx+1); // raw result at stack position 6
1209 if (lua_toboolean(L, 6)) {
1210 lua_getfield(L, 6, "_column_info"); // column_info list at position 7
1211 cols = lua_rawlen(L, 7);
1212 if (mode == MONDELEFANT_QUERY_MODE_LIST) {
1213 rows = lua_rawlen(L, 6);
1214 for (row = 0; row < rows; row++) {
1215 lua_rawgeti(L, 6, row+1); // row at stack position 8
1216 lua_getfield(L, 8, "_data"); // _data table at stack position 9
1217 lua_getfield(L, 8, "_dirty"); // _dirty table at stack position 10
1218 for (col = 0; col < cols; col++) {
1219 lua_rawgeti(L, 7, col+1); // this column info at position 11
1220 lua_getfield(L, 11, "field_name"); // 12
1221 if (lua_toboolean(L, 4)) {
1222 lua_pushvalue(L, 4); // output-converter
1223 lua_pushvalue(L, 1); // connection
1224 lua_rawgeti(L, 8, col+1); // raw-value
1225 lua_pushvalue(L, 11); // this column info
1226 lua_call(L, 3, 1); // converted value at position 13
1227 } else {
1228 lua_rawgeti(L, 8, col+1); // raw-value at position 13
1230 if (lua_toboolean(L, 5)) { // handle mutable values?
1231 lua_pushvalue(L, 12); // copy of field name
1232 lua_pushvalue(L, 5); // mutability state saver function
1233 lua_pushvalue(L, 13); // copy of value
1234 lua_call(L, 1, 1); // calculated mutability state of value
1235 lua_rawset(L, 10); // store mutability state in _dirty table
1237 lua_pushvalue(L, 13); // 14
1238 lua_rawseti(L, 8, col+1);
1239 lua_rawset(L, 9);
1240 lua_settop(L, 10);
1242 lua_settop(L, 7);
1244 } else {
1245 lua_getfield(L, 6, "_data"); // _data table at stack position 8
1246 lua_getfield(L, 6, "_dirty"); // _dirty table at stack position 9
1247 for (col = 0; col < cols; col++) {
1248 lua_rawgeti(L, 7, col+1); // this column info at position 10
1249 lua_getfield(L, 10, "field_name"); // 11
1250 if (lua_toboolean(L, 4)) {
1251 lua_pushvalue(L, 4); // output-converter
1252 lua_pushvalue(L, 1); // connection
1253 lua_rawgeti(L, 6, col+1); // raw-value
1254 lua_pushvalue(L, 10); // this column info
1255 lua_call(L, 3, 1); // converted value at position 12
1256 } else {
1257 lua_rawgeti(L, 6, col+1); // raw-value at position 12
1259 if (lua_toboolean(L, 5)) { // handle mutable values?
1260 lua_pushvalue(L, 11); // copy of field name
1261 lua_pushvalue(L, 5); // mutability state saver function
1262 lua_pushvalue(L, 12); // copy of value
1263 lua_call(L, 1, 1); // calculated mutability state of value
1264 lua_rawset(L, 9); // store mutability state in _dirty table
1266 lua_pushvalue(L, 12); // 13
1267 lua_rawseti(L, 6, col+1);
1268 lua_rawset(L, 8);
1269 lua_settop(L, 9);
1273 lua_settop(L, 5);
1275 // return nil as first result value, followed by result lists/objects:
1276 lua_settop(L, 3);
1277 lua_pushnil(L);
1278 for (command_idx = 0; command_idx < command_count; command_idx++) {
1279 lua_rawgeti(L, 3, command_idx+1);
1281 return command_count+1;
1284 // method "is_kind_of" of error objects:
1285 static int mondelefant_errorobject_is_kind_of(lua_State *L) {
1286 const char *errclass;
1287 luaL_checktype(L, 1, LUA_TTABLE);
1288 errclass = luaL_checkstring(L, 2);
1289 lua_settop(L, 2);
1290 lua_getfield(L, 1, "code"); // 3
1291 luaL_argcheck(L,
1292 lua_type(L, 3) == LUA_TSTRING,
1293 1,
1294 "field 'code' of error object is not a string"
1295 );
1296 lua_pushboolean(L,
1297 mondelefant_check_error_class(lua_tostring(L, 3), errclass)
1298 );
1299 return 1;
1302 // method "wait" of database handles:
1303 static int mondelefant_conn_wait(lua_State *L) {
1304 int argc;
1305 // count number of arguments:
1306 argc = lua_gettop(L);
1307 // insert "try_wait" function/method at stack position 1:
1308 lua_pushcfunction(L, mondelefant_conn_try_wait);
1309 lua_insert(L, 1);
1310 // call "try_wait" method:
1311 lua_call(L, argc, LUA_MULTRET); // results (with error) starting at index 1
1312 // check, if error occurred:
1313 if (lua_toboolean(L, 1)) {
1314 // raise error
1315 lua_settop(L, 1);
1316 return lua_error(L);
1317 } else {
1318 // return everything but nil error object:
1319 return lua_gettop(L) - 1;
1323 // method "query" of database handles:
1324 static int mondelefant_conn_query(lua_State *L) {
1325 int argc;
1326 // count number of arguments:
1327 argc = lua_gettop(L);
1328 // insert "try_query" function/method at stack position 1:
1329 lua_pushcfunction(L, mondelefant_conn_try_query);
1330 lua_insert(L, 1);
1331 // call "try_query" method:
1332 lua_call(L, argc, LUA_MULTRET); // results (with error) starting at index 1
1333 // check, if error occurred:
1334 if (lua_toboolean(L, 1)) {
1335 // raise error
1336 lua_settop(L, 1);
1337 return lua_error(L);
1338 } else {
1339 // return everything but nil error object:
1340 return lua_gettop(L) - 1;
1344 // library function "set_class":
1345 static int mondelefant_set_class(lua_State *L) {
1346 // ensure that first argument is a database result list/object:
1347 lua_settop(L, 2);
1348 lua_getmetatable(L, 1); // 3
1349 lua_getfield(L, LUA_REGISTRYINDEX, MONDELEFANT_RESULT_MT_REGKEY); // 4
1350 luaL_argcheck(L, lua_compare(L, 3, 4, LUA_OPEQ), 1, "not a database result");
1351 // ensure that second argument is a database class (model):
1352 lua_settop(L, 2);
1353 lua_getmetatable(L, 2); // 3
1354 lua_getfield(L, LUA_REGISTRYINDEX, MONDELEFANT_CLASS_MT_REGKEY); // 4
1355 luaL_argcheck(L, lua_compare(L, 3, 4, LUA_OPEQ), 2, "not a database class");
1356 // set attribute "_class" of result list/object to given class:
1357 lua_settop(L, 2);
1358 lua_pushvalue(L, 2); // 3
1359 lua_setfield(L, 1, "_class");
1360 // test, if database result is a list (and not a single object):
1361 lua_getfield(L, 1, "_type"); // 3
1362 lua_pushliteral(L, "list"); // 4
1363 if (lua_rawequal(L, 3, 4)) {
1364 int i;
1365 // set attribute "_class" of all elements to given class:
1366 for (i=0; i < lua_rawlen(L, 1); i++) {
1367 lua_settop(L, 2);
1368 lua_rawgeti(L, 1, i+1); // 3
1369 lua_pushvalue(L, 2); // 4
1370 lua_setfield(L, 3, "_class");
1373 // return first argument:
1374 lua_settop(L, 1);
1375 return 1;
1378 // library function "new_class":
1379 static int mondelefant_new_class(lua_State *L) {
1380 // if no argument is given, use an empty table:
1381 if (lua_isnoneornil(L, 1)) {
1382 lua_settop(L, 0);
1383 lua_newtable(L); // 1
1384 } else {
1385 luaL_checktype(L, 1, LUA_TTABLE);
1386 lua_settop(L, 1);
1388 // set meta-table for database classes (models):
1389 luaL_setmetatable(L, MONDELEFANT_CLASS_MT_REGKEY);
1390 // check, if "prototype" attribute is not set:
1391 lua_pushliteral(L, "prototype"); // 2
1392 lua_rawget(L, 1); // 2
1393 if (!lua_toboolean(L, 2)) {
1394 // set "prototype" attribute to default prototype:
1395 lua_pushliteral(L, "prototype"); // 3
1396 lua_getfield(L,
1397 LUA_REGISTRYINDEX,
1398 MONDELEFANT_CLASS_PROTO_REGKEY
1399 ); // 4
1400 lua_rawset(L, 1);
1402 // set "object" attribute to empty table, unless it is already set:
1403 lua_settop(L, 1);
1404 lua_pushliteral(L, "object"); // 2
1405 lua_rawget(L, 1); // 2
1406 if (!lua_toboolean(L, 2)) {
1407 lua_pushliteral(L, "object"); // 3
1408 lua_newtable(L); // 4
1409 lua_rawset(L, 1);
1411 // set "object_get" attribute to empty table, unless it is already set:
1412 lua_settop(L, 1);
1413 lua_pushliteral(L, "object_get"); // 2
1414 lua_rawget(L, 1); // 2
1415 if (!lua_toboolean(L, 2)) {
1416 lua_pushliteral(L, "object_get"); // 3
1417 lua_newtable(L); // 4
1418 lua_rawset(L, 1);
1420 // set "object_set" attribute to empty table, unless it is already set:
1421 lua_settop(L, 1);
1422 lua_pushliteral(L, "object_set"); // 2
1423 lua_rawget(L, 1); // 2
1424 if (!lua_toboolean(L, 2)) {
1425 lua_pushliteral(L, "object_set"); // 3
1426 lua_newtable(L); // 4
1427 lua_rawset(L, 1);
1429 // set "list" attribute to empty table, unless it is already set:
1430 lua_settop(L, 1);
1431 lua_pushliteral(L, "list"); // 2
1432 lua_rawget(L, 1); // 2
1433 if (!lua_toboolean(L, 2)) {
1434 lua_pushliteral(L, "list"); // 3
1435 lua_newtable(L); // 4
1436 lua_rawset(L, 1);
1438 // set "references" attribute to empty table, unless it is already set:
1439 lua_settop(L, 1);
1440 lua_pushliteral(L, "references"); // 2
1441 lua_rawget(L, 1); // 2
1442 if (!lua_toboolean(L, 2)) {
1443 lua_pushliteral(L, "references"); // 3
1444 lua_newtable(L); // 4
1445 lua_rawset(L, 1);
1447 // set "foreign_keys" attribute to empty table, unless it is already set:
1448 lua_settop(L, 1);
1449 lua_pushliteral(L, "foreign_keys"); // 2
1450 lua_rawget(L, 1); // 2
1451 if (!lua_toboolean(L, 2)) {
1452 lua_pushliteral(L, "foreign_keys"); // 3
1453 lua_newtable(L); // 4
1454 lua_rawset(L, 1);
1456 // return table:
1457 lua_settop(L, 1);
1458 return 1;
1461 // method "get_reference" of classes (models):
1462 static int mondelefant_class_get_reference(lua_State *L) {
1463 lua_settop(L, 2);
1464 while (lua_toboolean(L, 1)) {
1465 // get "references" table:
1466 lua_getfield(L, 1, "references"); // 3
1467 // perform lookup:
1468 lua_pushvalue(L, 2); // 4
1469 lua_gettable(L, 3); // 4
1470 // return result, if lookup was successful:
1471 if (!lua_isnil(L, 4)) return 1;
1472 // replace current table by its prototype:
1473 lua_settop(L, 2);
1474 lua_pushliteral(L, "prototype"); // 3
1475 lua_rawget(L, 1); // 3
1476 lua_replace(L, 1);
1478 // return nothing:
1479 return 0;
1482 // method "iterate_over_references" of classes (models):
1483 static int mondelefant_class_iterate_over_references(lua_State *L) {
1484 return luaL_error(L, "Reference iterator not implemented yet."); // TODO
1487 // method "get_foreign_key_reference_name" of classes (models):
1488 static int mondelefant_class_get_foreign_key_reference_name(lua_State *L) {
1489 lua_settop(L, 2);
1490 while (lua_toboolean(L, 1)) {
1491 // get "foreign_keys" table:
1492 lua_getfield(L, 1, "foreign_keys"); // 3
1493 // perform lookup:
1494 lua_pushvalue(L, 2); // 4
1495 lua_gettable(L, 3); // 4
1496 // return result, if lookup was successful:
1497 if (!lua_isnil(L, 4)) return 1;
1498 // replace current table by its prototype:
1499 lua_settop(L, 2);
1500 lua_pushliteral(L, "prototype"); // 3
1501 lua_rawget(L, 1); // 3
1502 lua_replace(L, 1);
1504 // return nothing:
1505 return 0;
1508 // meta-method "__index" of database result lists and objects:
1509 static int mondelefant_result_index(lua_State *L) {
1510 const char *result_type;
1511 // only lookup, when key is a string not beginning with an underscore:
1512 if (lua_type(L, 2) != LUA_TSTRING || lua_tostring(L, 2)[0] == '_') {
1513 return 0;
1515 // value of "_class" attribute or default class on stack position 3:
1516 lua_settop(L, 2);
1517 lua_getfield(L, 1, "_class"); // 3
1518 if (!lua_toboolean(L, 3)) {
1519 lua_settop(L, 2);
1520 lua_getfield(L,
1521 LUA_REGISTRYINDEX,
1522 MONDELEFANT_CLASS_PROTO_REGKEY
1523 ); // 3
1525 // get value of "_type" attribute:
1526 lua_getfield(L, 1, "_type"); // 4
1527 result_type = lua_tostring(L, 4);
1528 // different lookup for lists and objects:
1529 if (result_type && !strcmp(result_type, "object")) { // object
1530 lua_settop(L, 3);
1531 // try inherited attributes, methods or getter functions:
1532 lua_pushvalue(L, 3); // 4
1533 while (lua_toboolean(L, 4)) {
1534 lua_getfield(L, 4, "object"); // 5
1535 lua_pushvalue(L, 2); // 6
1536 lua_gettable(L, 5); // 6
1537 if (!lua_isnil(L, 6)) return 1;
1538 lua_settop(L, 4);
1539 lua_getfield(L, 4, "object_get"); // 5
1540 lua_pushvalue(L, 2); // 6
1541 lua_gettable(L, 5); // 6
1542 if (lua_toboolean(L, 6)) {
1543 lua_pushvalue(L, 1); // 7
1544 lua_call(L, 1, 1); // 6
1545 return 1;
1547 lua_settop(L, 4);
1548 lua_pushliteral(L, "prototype"); // 5
1549 lua_rawget(L, 4); // 5
1550 lua_replace(L, 4);
1552 lua_settop(L, 3);
1553 // try primary keys of referenced objects:
1554 lua_pushcfunction(L,
1555 mondelefant_class_get_foreign_key_reference_name
1556 ); // 4
1557 lua_pushvalue(L, 3); // 5
1558 lua_pushvalue(L, 2); // 6
1559 lua_call(L, 2, 1); // 4
1560 if (!lua_isnil(L, 4)) {
1561 // reference name at stack position 4
1562 lua_pushcfunction(L, mondelefant_class_get_reference); // 5
1563 lua_pushvalue(L, 3); // 6
1564 lua_pushvalue(L, 4); // 7
1565 lua_call(L, 2, 1); // reference info at stack position 5
1566 lua_getfield(L, 1, "_ref"); // 6
1567 lua_getfield(L, 5, "ref"); // 7
1568 lua_gettable(L, 6); // 7
1569 if (!lua_isnil(L, 7)) {
1570 if (lua_toboolean(L, 7)) {
1571 lua_getfield(L, 5, "that_key"); // 8
1572 if (lua_isnil(L, 8)) {
1573 return luaL_error(L, "Missing 'that_key' entry in model reference.");
1575 lua_gettable(L, 7); // 8
1576 } else {
1577 lua_pushnil(L);
1579 return 1;
1582 lua_settop(L, 3);
1583 lua_getfield(L, 1, "_data"); // _data table on stack position 4
1584 // try normal data field info:
1585 lua_pushvalue(L, 2); // 5
1586 lua_gettable(L, 4); // 5
1587 if (!lua_isnil(L, 5)) return 1;
1588 lua_settop(L, 4); // keep _data table on stack
1589 // try cached referenced object (or cached NULL reference):
1590 lua_getfield(L, 1, "_ref"); // 5
1591 lua_pushvalue(L, 2); // 6
1592 lua_gettable(L, 5); // 6
1593 if (lua_isboolean(L, 6) && !lua_toboolean(L, 6)) {
1594 lua_pushnil(L);
1595 return 1;
1596 } else if (!lua_isnil(L, 6)) {
1597 return 1;
1599 lua_settop(L, 4);
1600 // try to load a referenced object:
1601 lua_pushcfunction(L, mondelefant_class_get_reference); // 5
1602 lua_pushvalue(L, 3); // 6
1603 lua_pushvalue(L, 2); // 7
1604 lua_call(L, 2, 1); // 5
1605 if (!lua_isnil(L, 5)) {
1606 lua_settop(L, 2);
1607 lua_getfield(L, 1, "load"); // 3
1608 lua_pushvalue(L, 1); // 4 (self)
1609 lua_pushvalue(L, 2); // 5
1610 lua_call(L, 2, 0);
1611 lua_settop(L, 2);
1612 lua_getfield(L, 1, "_ref"); // 3
1613 lua_pushvalue(L, 2); // 4
1614 lua_gettable(L, 3); // 4
1615 if (lua_isboolean(L, 4) && !lua_toboolean(L, 4)) lua_pushnil(L); // TODO: use special object instead of false
1616 return 1;
1618 lua_settop(L, 4);
1619 // try proxy access to document in special column:
1620 lua_getfield(L, 3, "document_column"); // 5
1621 if (lua_toboolean(L, 5)) {
1622 lua_gettable(L, 4); // 5
1623 if (!lua_isnil(L, 5)) {
1624 lua_pushvalue(L, 2); // 6
1625 lua_gettable(L, 5); // 6
1626 if (!lua_isnil(L, 6)) return 1;
1629 return 0;
1630 } else if (result_type && !strcmp(result_type, "list")) { // list
1631 lua_settop(L, 3);
1632 // try inherited list attributes or methods:
1633 while (lua_toboolean(L, 3)) {
1634 lua_getfield(L, 3, "list"); // 4
1635 lua_pushvalue(L, 2); // 5
1636 lua_gettable(L, 4); // 5
1637 if (!lua_isnil(L, 5)) return 1;
1638 lua_settop(L, 3);
1639 lua_pushliteral(L, "prototype"); // 4
1640 lua_rawget(L, 3); // 4
1641 lua_replace(L, 3);
1644 // return nothing:
1645 return 0;
1648 // meta-method "__newindex" of database result lists and objects:
1649 static int mondelefant_result_newindex(lua_State *L) {
1650 const char *result_type;
1651 // perform rawset, unless key is a string not starting with underscore:
1652 lua_settop(L, 3);
1653 if (lua_type(L, 2) != LUA_TSTRING || lua_tostring(L, 2)[0] == '_') {
1654 lua_rawset(L, 1);
1655 return 1;
1657 // value of "_class" attribute or default class on stack position 4:
1658 lua_settop(L, 3);
1659 lua_getfield(L, 1, "_class"); // 4
1660 if (!lua_toboolean(L, 4)) {
1661 lua_settop(L, 3);
1662 lua_getfield(L,
1663 LUA_REGISTRYINDEX,
1664 MONDELEFANT_CLASS_PROTO_REGKEY
1665 ); // 4
1667 // get value of "_type" attribute:
1668 lua_getfield(L, 1, "_type"); // 5
1669 result_type = lua_tostring(L, 5);
1670 // distinguish between lists and objects:
1671 if (result_type && !strcmp(result_type, "object")) { // objects
1672 lua_settop(L, 4);
1673 // try object setter functions:
1674 lua_pushvalue(L, 4); // 5
1675 while (lua_toboolean(L, 5)) {
1676 lua_getfield(L, 5, "object_set"); // 6
1677 lua_pushvalue(L, 2); // 7
1678 lua_gettable(L, 6); // 7
1679 if (lua_toboolean(L, 7)) {
1680 lua_pushvalue(L, 1); // 8
1681 lua_pushvalue(L, 3); // 9
1682 lua_call(L, 2, 0);
1683 return 0;
1685 lua_settop(L, 5);
1686 lua_pushliteral(L, "prototype"); // 6
1687 lua_rawget(L, 5); // 6
1688 lua_replace(L, 5);
1690 lua_settop(L, 4);
1691 lua_getfield(L, 1, "_data"); // _data table on stack position 5
1692 // check, if a object reference is changed:
1693 lua_pushcfunction(L, mondelefant_class_get_reference); // 6
1694 lua_pushvalue(L, 4); // 7
1695 lua_pushvalue(L, 2); // 8
1696 lua_call(L, 2, 1); // 6
1697 if (!lua_isnil(L, 6)) {
1698 // store object in _ref table (use false for nil): // TODO: use special object instead of false
1699 lua_getfield(L, 1, "_ref"); // 7
1700 lua_pushvalue(L, 2); // 8
1701 if (lua_isnil(L, 3)) lua_pushboolean(L, 0); // 9
1702 else lua_pushvalue(L, 3); // 9
1703 lua_settable(L, 7);
1704 lua_settop(L, 6);
1705 // delete referencing key from _data table:
1706 lua_getfield(L, 6, "this_key"); // 7
1707 if (lua_isnil(L, 7)) {
1708 return luaL_error(L, "Missing 'this_key' entry in model reference.");
1710 lua_pushvalue(L, 7); // 8
1711 lua_pushnil(L); // 9
1712 lua_settable(L, 5);
1713 lua_getfield(L, 1, "_dirty"); // 8
1714 lua_pushvalue(L, 7); // 9
1715 lua_pushboolean(L, 1); // 10
1716 lua_settable(L, 8);
1717 return 0;
1719 lua_settop(L, 5);
1720 // check proxy access to document in special column:
1721 lua_getfield(L, 4, "document_column"); // 6
1722 if (lua_toboolean(L, 6)) {
1723 lua_getfield(L, 1, "_column_info"); // 7
1724 if (!lua_isnil(L, 7)) { // TODO: quick fix to avoid problems on document creation
1725 lua_pushvalue(L, 2); // 8
1726 lua_gettable(L, 7); // 8
1727 if (!lua_toboolean(L, 8)) {
1728 lua_settop(L, 6);
1729 lua_gettable(L, 5); // 6
1730 if (lua_isnil(L, 6)) {
1731 return luaL_error(L, "Cannot write to document column: document is nil");
1733 lua_pushvalue(L, 2); // 7
1734 lua_pushvalue(L, 3); // 8
1735 lua_settable(L, 6);
1736 return 0;
1738 } // TODO: quick fix to avoid problems on document creation
1740 lua_settop(L, 5);
1741 // store value in data field info:
1742 lua_pushvalue(L, 2); // 6
1743 lua_pushvalue(L, 3); // 7
1744 lua_settable(L, 5);
1745 lua_settop(L, 4);
1746 // mark field as dirty (needs to be UPDATEd on save):
1747 lua_getfield(L, 1, "_dirty"); // 5
1748 lua_pushvalue(L, 2); // 6
1749 lua_pushboolean(L, 1); // 7
1750 lua_settable(L, 5);
1751 lua_settop(L, 4);
1752 // reset reference cache, if neccessary:
1753 lua_pushcfunction(L,
1754 mondelefant_class_get_foreign_key_reference_name
1755 ); // 5
1756 lua_pushvalue(L, 4); // 6
1757 lua_pushvalue(L, 2); // 7
1758 lua_call(L, 2, 1); // 5
1759 if (!lua_isnil(L, 5)) {
1760 lua_getfield(L, 1, "_ref"); // 6
1761 lua_pushvalue(L, 5); // 7
1762 lua_pushnil(L); // 8
1763 lua_settable(L, 6);
1765 return 0;
1766 } else { // non-objects (i.e. lists)
1767 // perform rawset:
1768 lua_settop(L, 3);
1769 lua_rawset(L, 1);
1770 return 0;
1774 // meta-method "__index" of classes (models):
1775 static int mondelefant_class_index(lua_State *L) {
1776 // perform lookup in prototype:
1777 lua_settop(L, 2);
1778 lua_pushliteral(L, "prototype"); // 3
1779 lua_rawget(L, 1); // 3
1780 lua_pushvalue(L, 2); // 4
1781 lua_gettable(L, 3); // 4
1782 return 1;
1785 // registration information for functions of library:
1786 static const struct luaL_Reg mondelefant_module_functions[] = {
1787 {"connect", mondelefant_connect},
1788 {"set_class", mondelefant_set_class},
1789 {"new_class", mondelefant_new_class},
1790 {NULL, NULL}
1791 };
1793 // registration information for meta-methods of database connections:
1794 static const struct luaL_Reg mondelefant_conn_mt_functions[] = {
1795 {"__gc", mondelefant_conn_free},
1796 {"__index", mondelefant_conn_index},
1797 {"__newindex", mondelefant_conn_newindex},
1798 {NULL, NULL}
1799 };
1801 // registration information for methods of database connections:
1802 static const struct luaL_Reg mondelefant_conn_methods[] = {
1803 {"close", mondelefant_conn_close},
1804 {"is_ok", mondelefant_conn_is_ok},
1805 {"get_transaction_status", mondelefant_conn_get_transaction_status},
1806 {"try_wait", mondelefant_conn_try_wait},
1807 {"wait", mondelefant_conn_wait},
1808 {"create_list", mondelefant_conn_create_list},
1809 {"create_object", mondelefant_conn_create_object},
1810 {"quote_string", mondelefant_conn_quote_string},
1811 {"quote_binary", mondelefant_conn_quote_binary},
1812 {"assemble_command", mondelefant_conn_assemble_command},
1813 {"try_query", mondelefant_conn_try_query},
1814 {"query", mondelefant_conn_query},
1815 {NULL, NULL}
1816 };
1818 // registration information for meta-methods of error objects:
1819 static const struct luaL_Reg mondelefant_errorobject_mt_functions[] = {
1820 {NULL, NULL}
1821 };
1823 // registration information for methods of error objects:
1824 static const struct luaL_Reg mondelefant_errorobject_methods[] = {
1825 {"escalate", lua_error},
1826 {"is_kind_of", mondelefant_errorobject_is_kind_of},
1827 {NULL, NULL}
1828 };
1830 // registration information for meta-methods of database result lists/objects:
1831 static const struct luaL_Reg mondelefant_result_mt_functions[] = {
1832 {"__index", mondelefant_result_index},
1833 {"__newindex", mondelefant_result_newindex},
1834 {NULL, NULL}
1835 };
1837 // registration information for methods of database result lists/objects:
1838 static const struct luaL_Reg mondelefant_class_mt_functions[] = {
1839 {"__index", mondelefant_class_index},
1840 {NULL, NULL}
1841 };
1843 // registration information for methods of classes (models):
1844 static const struct luaL_Reg mondelefant_class_methods[] = {
1845 {"get_reference", mondelefant_class_get_reference},
1846 {"iterate_over_references", mondelefant_class_iterate_over_references},
1847 {"get_foreign_key_reference_name",
1848 mondelefant_class_get_foreign_key_reference_name},
1849 {NULL, NULL}
1850 };
1852 // registration information for methods of database result objects (not lists!):
1853 static const struct luaL_Reg mondelefant_object_methods[] = {
1854 {NULL, NULL}
1855 };
1857 // registration information for methods of database result lists (not single objects!):
1858 static const struct luaL_Reg mondelefant_list_methods[] = {
1859 {NULL, NULL}
1860 };
1862 // luaopen function to initialize/register library:
1863 int luaopen_mondelefant_native(lua_State *L) {
1864 lua_settop(L, 0);
1865 lua_newtable(L); // module at stack position 1
1866 luaL_setfuncs(L, mondelefant_module_functions, 0);
1868 lua_pushvalue(L, 1); // 2
1869 lua_setfield(L, LUA_REGISTRYINDEX, MONDELEFANT_MODULE_REGKEY);
1871 lua_newtable(L); // 2
1872 // NOTE: only PostgreSQL is supported yet:
1873 luaL_setfuncs(L, mondelefant_conn_methods, 0);
1874 lua_setfield(L, 1, "postgresql_connection_prototype");
1875 lua_newtable(L); // 2
1876 lua_setfield(L, 1, "connection_prototype");
1878 luaL_newmetatable(L, MONDELEFANT_CONN_MT_REGKEY); // 2
1879 luaL_setfuncs(L, mondelefant_conn_mt_functions, 0);
1880 lua_settop(L, 1);
1881 luaL_newmetatable(L, MONDELEFANT_RESULT_MT_REGKEY); // 2
1882 luaL_setfuncs(L, mondelefant_result_mt_functions, 0);
1883 lua_setfield(L, 1, "result_metatable");
1884 luaL_newmetatable(L, MONDELEFANT_CLASS_MT_REGKEY); // 2
1885 luaL_setfuncs(L, mondelefant_class_mt_functions, 0);
1886 lua_setfield(L, 1, "class_metatable");
1888 lua_newtable(L); // 2
1889 luaL_setfuncs(L, mondelefant_class_methods, 0);
1890 lua_newtable(L); // 3
1891 luaL_setfuncs(L, mondelefant_object_methods, 0);
1892 lua_setfield(L, 2, "object");
1893 lua_newtable(L); // 3
1894 lua_setfield(L, 2, "object_get");
1895 lua_newtable(L); // 3
1896 lua_setfield(L, 2, "object_set");
1897 lua_newtable(L); // 3
1898 luaL_setfuncs(L, mondelefant_list_methods, 0);
1899 lua_setfield(L, 2, "list");
1900 lua_newtable(L); // 3
1901 lua_setfield(L, 2, "references");
1902 lua_newtable(L); // 3
1903 lua_setfield(L, 2, "foreign_keys");
1904 lua_pushvalue(L, 2); // 3
1905 lua_setfield(L, LUA_REGISTRYINDEX, MONDELEFANT_CLASS_PROTO_REGKEY);
1906 lua_setfield(L, 1, "class_prototype");
1908 luaL_newmetatable(L, MONDELEFANT_ERROROBJECT_MT_REGKEY); // 2
1909 luaL_setfuncs(L, mondelefant_errorobject_mt_functions, 0);
1910 lua_newtable(L); // 3
1911 luaL_setfuncs(L, mondelefant_errorobject_methods, 0);
1912 lua_setfield(L, 2, "__index");
1913 lua_setfield(L, 1, "errorobject_metatable");
1915 return 1;

Impressum / About Us