webmcp

view libraries/mondelefant/mondelefant_native.c @ 402:04172238d79b

Do not require "engine" field to be set for mondelefant.connect{...}; Fixed bugs in mondelefant.connect{...} that could have crashed Lua; Shortened Lua registry key for mondelefant library
author jbe
date Wed Jan 06 02:39:50 2016 +0100 (2016-01-06)
parents ad437022be90
children 36f0d1d5ed7d
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 PGconn *pgconn; // PGconn object as returned by PQconnectdb function
199 mondelefant_conn_t *conn; // C-structure for userdata
200 // check if string is given as first argument:
201 if (lua_type(L, 1) != LUA_TSTRING) {
202 // expect a table as first argument if no string is given:
203 luaL_checktype(L, 1, LUA_TTABLE);
204 // copy conninfo string for PQconnectdb function from argument table to
205 // stack position 2:
206 lua_settop(L, 1);
207 lua_getfield(L, 1, "conninfo"); // 2
208 // check if conninfo is set:
209 if (!lua_isnil(L, 2)) {
210 // if yes, use that value but check its type:
211 luaL_argcheck(L, lua_type(L, 2) == LUA_TSTRING, 2, "\"conninfo\" value is not a string");
212 } else {
213 // otherwise assemble conninfo string from the named options:
214 luaL_Buffer buf;
215 int need_seperator = 0;
216 const char *value;
217 size_t value_len;
218 size_t value_pos = 0;
219 lua_settop(L, 1);
220 lua_pushnil(L); // slot for key at stack position 2
221 lua_pushnil(L); // slot for value at stack position 3
222 luaL_buffinit(L, &buf);
223 while (lua_pushvalue(L, 2), lua_next(L, 1)) {
224 luaL_argcheck(L, lua_isstring(L, -2), 1, "key in table is not a string");
225 luaL_argcheck(L, lua_isstring(L, -1), 1, "value in table is not a string");
226 value = lua_tolstring(L, -1, &value_len);
227 lua_replace(L, 3);
228 lua_pop(L, 1);
229 lua_replace(L, 2);
230 if (need_seperator) luaL_addchar(&buf, ' ');
231 // NOTE: numbers will be converted to strings automatically here,
232 // but perhaps this will change in future versions of lua
233 lua_pushvalue(L, 2);
234 luaL_addvalue(&buf);
235 luaL_addchar(&buf, '=');
236 luaL_addchar(&buf, '\'');
237 do {
238 char c;
239 c = value[value_pos++];
240 if (c == '\'') luaL_addchar(&buf, '\\');
241 luaL_addchar(&buf, c);
242 } while (value_pos < value_len);
243 luaL_addchar(&buf, '\'');
244 need_seperator = 1;
245 }
246 luaL_pushresult(&buf);
247 }
248 // ensure that string is on stack position 1 which is the top of stack:
249 lua_replace(L, 1);
250 lua_settop(L, 1);
251 }
252 // use conninfo string on stack position 1:
253 conninfo = lua_tostring(L, 1);
254 // call PQconnectdb function of libpq:
255 pgconn = PQconnectdb(conninfo);
256 // throw or return errors, if neccessary:
257 if (!pgconn) {
258 return luaL_error(L,
259 "Error in libpq while creating 'PGconn' structure."
260 );
261 }
262 if (PQstatus(pgconn) != CONNECTION_OK) {
263 lua_pushnil(L); // 2
264 mondelefant_push_first_line(L, PQerrorMessage(pgconn)); // 3
265 lua_newtable(L); // 4
266 lua_getfield(L,
267 LUA_REGISTRYINDEX,
268 MONDELEFANT_ERROROBJECT_MT_REGKEY
269 );
270 lua_setmetatable(L, 4);
271 lua_pushliteral(L, MONDELEFANT_ERRCODE_CONNECTION);
272 lua_setfield(L, 4, "code");
273 lua_pushvalue(L, 3);
274 lua_setfield(L, 4, "message");
275 PQfinish(pgconn);
276 return 3;
277 }
278 // create userdata:
279 lua_settop(L, 0);
280 conn = lua_newuserdata(L, sizeof(*conn)); // 1
281 // set 'pgconn' in C-struct of userdata:
282 conn->pgconn = pgconn;
283 // set 'server_encoding' in C-struct of userdata:
284 {
285 const char *charset;
286 charset = PQparameterStatus(pgconn, "server_encoding");
287 if (charset && !strcmp(charset, "UTF8")) {
288 conn->server_encoding = MONDELEFANT_SERVER_ENCODING_UTF8;
289 } else {
290 conn->server_encoding = MONDELEFANT_SERVER_ENCODING_ASCII;
291 }
292 }
293 // set meta-table of userdata:
294 luaL_getmetatable(L, MONDELEFANT_CONN_MT_REGKEY); // 2
295 lua_setmetatable(L, 1);
296 // create and associate userdata table:
297 lua_newtable(L);
298 lua_setuservalue(L, 1);
299 // store key "fd" with file descriptor of connection:
300 lua_pushinteger(L, PQsocket(pgconn));
301 lua_setfield(L, 1, "fd");
302 // store key "engine" with value "postgresql" as connection specific data:
303 lua_pushliteral(L, "postgresql");
304 lua_setfield(L, 1, "engine");
305 // return userdata:
306 return 1;
307 }
309 // returns pointer to libpq handle 'pgconn' of userdata at given index
310 // (or throws error, if database connection has been closed):
311 static mondelefant_conn_t *mondelefant_get_conn(lua_State *L, int index) {
312 mondelefant_conn_t *conn;
313 conn = luaL_checkudata(L, index, MONDELEFANT_CONN_MT_REGKEY);
314 if (!conn->pgconn) {
315 luaL_error(L, "PostgreSQL connection has been closed.");
316 return NULL;
317 }
318 return conn;
319 }
321 // meta-method "__index" of database handles (userdata):
322 static int mondelefant_conn_index(lua_State *L) {
323 // try table for connection specific data:
324 lua_settop(L, 2);
325 lua_getuservalue(L, 1); // 3
326 lua_pushvalue(L, 2); // 4
327 lua_gettable(L, 3); // 4
328 if (!lua_isnil(L, 4)) return 1;
329 // try to use prototype stored in connection specific data:
330 lua_settop(L, 3);
331 lua_getfield(L, 3, "prototype"); // 4
332 if (lua_toboolean(L, 4)) {
333 lua_pushvalue(L, 2); // 5
334 lua_gettable(L, 4); // 5
335 if (!lua_isnil(L, 5)) return 1;
336 }
337 // try to use "postgresql_connection_prototype" of library:
338 lua_settop(L, 2);
339 lua_getfield(L, LUA_REGISTRYINDEX, MONDELEFANT_MODULE_REGKEY); // 3
340 lua_getfield(L, 3, "postgresql_connection_prototype"); // 4
341 if (lua_toboolean(L, 4)) {
342 lua_pushvalue(L, 2); // 5
343 lua_gettable(L, 4); // 5
344 if (!lua_isnil(L, 5)) return 1;
345 }
346 // try to use "connection_prototype" of library:
347 lua_settop(L, 3);
348 lua_getfield(L, 3, "connection_prototype"); // 4
349 if (lua_toboolean(L, 4)) {
350 lua_pushvalue(L, 2); // 5
351 lua_gettable(L, 4); // 5
352 if (!lua_isnil(L, 5)) return 1;
353 }
354 // give up and return nothing:
355 return 0;
356 }
358 // meta-method "__newindex" of database handles (userdata):
359 static int mondelefant_conn_newindex(lua_State *L) {
360 // store key-value pair in table for connection specific data:
361 lua_settop(L, 3);
362 lua_getuservalue(L, 1); // 4
363 lua_pushvalue(L, 2);
364 lua_pushvalue(L, 3);
365 lua_settable(L, 4);
366 // return nothing:
367 return 0;
368 }
370 // meta-method "__gc" of database handles:
371 static int mondelefant_conn_free(lua_State *L) {
372 mondelefant_conn_t *conn;
373 conn = luaL_checkudata(L, 1, MONDELEFANT_CONN_MT_REGKEY);
374 if (conn->pgconn) PQfinish(conn->pgconn);
375 conn->pgconn = NULL;
376 return 0;
377 }
379 // method "close" of database handles:
380 static int mondelefant_conn_close(lua_State *L) {
381 mondelefant_conn_t *conn;
382 conn = mondelefant_get_conn(L, 1);
383 PQfinish(conn->pgconn);
384 conn->pgconn = NULL;
385 lua_pushnil(L);
386 lua_setfield(L, 1, "fd"); // set "fd" attribute to nil
387 return 0;
388 }
390 // method "is_okay" of database handles:
391 static int mondelefant_conn_is_ok(lua_State *L) {
392 mondelefant_conn_t *conn;
393 conn = mondelefant_get_conn(L, 1);
394 lua_pushboolean(L, PQstatus(conn->pgconn) == CONNECTION_OK);
395 return 1;
396 }
398 // method "get_transaction_status" of database handles:
399 static int mondelefant_conn_get_transaction_status(lua_State *L) {
400 mondelefant_conn_t *conn;
401 conn = mondelefant_get_conn(L, 1);
402 switch (PQtransactionStatus(conn->pgconn)) {
403 case PQTRANS_IDLE:
404 lua_pushliteral(L, "idle");
405 break;
406 case PQTRANS_ACTIVE:
407 lua_pushliteral(L, "active");
408 break;
409 case PQTRANS_INTRANS:
410 lua_pushliteral(L, "intrans");
411 break;
412 case PQTRANS_INERROR:
413 lua_pushliteral(L, "inerror");
414 break;
415 default:
416 lua_pushliteral(L, "unknown");
417 }
418 return 1;
419 }
421 // method "try_wait" of database handles:
422 static int mondelefant_conn_try_wait(lua_State *L) {
423 mondelefant_conn_t *conn;
424 int infinite, nonblock = 0;
425 struct timespec wakeup;
426 int fd;
427 fd_set fds;
428 conn = mondelefant_get_conn(L, 1);
429 infinite = lua_isnoneornil(L, 2);
430 if (!infinite) {
431 lua_Number n;
432 int isnum;
433 n = lua_tonumberx(L, 2, &isnum);
434 if (isnum && n>0 && n<=86400*366) {
435 if (clock_gettime(CLOCK_MONOTONIC, &wakeup)) {
436 return luaL_error(L, "Could not access CLOCK_MONOTONIC");
437 }
438 wakeup.tv_sec += n;
439 wakeup.tv_nsec += 1000000000 * (n - (time_t)n);
440 if (wakeup.tv_nsec >= 1000000000) {
441 wakeup.tv_sec += 1;
442 wakeup.tv_nsec -= 1000000000;
443 }
444 } else if (isnum && n==0) {
445 nonblock = 1;
446 } else {
447 luaL_argcheck(L, 0, 2, "not a valid timeout");
448 }
449 }
450 lua_settop(L, 1);
451 if (!nonblock) {
452 fd = PQsocket(conn->pgconn);
453 FD_ZERO(&fds);
454 FD_SET(fd, &fds);
455 }
456 while (true) {
457 {
458 PGnotify *notify;
459 if (!PQconsumeInput(conn->pgconn)) {
460 lua_newtable(L); // 2
461 lua_getfield(L,
462 LUA_REGISTRYINDEX,
463 MONDELEFANT_ERROROBJECT_MT_REGKEY
464 );
465 lua_setmetatable(L, 2);
466 lua_pushliteral(L, MONDELEFANT_ERRCODE_CONNECTION);
467 lua_setfield(L, 2, "code");
468 mondelefant_push_first_line(L, PQerrorMessage(conn->pgconn)); // 3
469 lua_setfield(L, 2, "message");
470 return 1;
471 }
472 notify = PQnotifies(conn->pgconn);
473 if (notify) {
474 lua_pushnil(L);
475 lua_pushstring(L, notify->relname);
476 lua_pushstring(L, notify->extra);
477 lua_pushinteger(L, notify->be_pid);
478 PQfreemem(notify);
479 return 4;
480 }
481 }
482 if (infinite) {
483 select(fd+1, &fds, NULL, NULL, NULL);
484 } else if (nonblock) {
485 break;
486 } else {
487 struct timespec tp;
488 struct timeval timeout = { 0, };
489 if (clock_gettime(CLOCK_MONOTONIC, &tp)) {
490 return luaL_error(L, "Could not access CLOCK_MONOTONIC");
491 }
492 tp.tv_sec = wakeup.tv_sec - tp.tv_sec;
493 tp.tv_nsec = wakeup.tv_nsec - tp.tv_nsec;
494 if (tp.tv_nsec < 0) {
495 tp.tv_sec -= 1;
496 tp.tv_nsec += 1000000000;
497 }
498 timeout.tv_sec = tp.tv_sec;
499 timeout.tv_usec = (tp.tv_nsec + 500) / 1000;
500 if (
501 timeout.tv_sec < 0 ||
502 (timeout.tv_sec == 0 && timeout.tv_usec == 0)
503 ) break;
504 select(fd+1, &fds, NULL, NULL, &timeout);
505 }
506 }
507 lua_pushnil(L);
508 lua_pushnil(L);
509 return 2;
510 }
512 // method "create_list" of database handles:
513 static int mondelefant_conn_create_list(lua_State *L) {
514 // ensure that first argument is a database connection:
515 luaL_checkudata(L, 1, MONDELEFANT_CONN_MT_REGKEY);
516 // if no second argument is given, use an empty table:
517 if (lua_isnoneornil(L, 2)) {
518 lua_settop(L, 1);
519 lua_newtable(L); // 2
520 } else {
521 luaL_checktype(L, 2, LUA_TTABLE);
522 lua_settop(L, 2);
523 }
524 // set meta-table for database result lists/objects:
525 lua_getfield(L, LUA_REGISTRYINDEX, MONDELEFANT_RESULT_MT_REGKEY); // 3
526 lua_setmetatable(L, 2);
527 // set "_connection" attribute to self:
528 lua_pushvalue(L, 1); // 3
529 lua_setfield(L, 2, "_connection");
530 // set "_type" attribute to string "list":
531 lua_pushliteral(L, "list"); // 3
532 lua_setfield(L, 2, "_type");
533 // return created database result list:
534 return 1;
535 }
537 // method "create_object" of database handles:
538 static int mondelefant_conn_create_object(lua_State *L) {
539 // ensure that first argument is a database connection:
540 luaL_checkudata(L, 1, MONDELEFANT_CONN_MT_REGKEY);
541 // if no second argument is given, use an empty table:
542 if (lua_isnoneornil(L, 2)) {
543 lua_settop(L, 1);
544 lua_newtable(L); // 2
545 } else {
546 luaL_checktype(L, 2, LUA_TTABLE);
547 lua_settop(L, 2);
548 }
549 // set meta-table for database result lists/objects:
550 lua_getfield(L, LUA_REGISTRYINDEX, MONDELEFANT_RESULT_MT_REGKEY); // 3
551 lua_setmetatable(L, 2);
552 // set "_connection" attribute to self:
553 lua_pushvalue(L, 1); // 3
554 lua_setfield(L, 2, "_connection");
555 // set "_type" attribute to string "object":
556 lua_pushliteral(L, "object"); // 3
557 lua_setfield(L, 2, "_type"); // "object" or "list"
558 // create empty tables for "_data", "_dirty" and "_ref" attributes:
559 lua_newtable(L); // 3
560 lua_setfield(L, 2, "_data");
561 lua_newtable(L); // 3
562 lua_setfield(L, 2, "_dirty");
563 lua_newtable(L); // 3
564 lua_setfield(L, 2, "_ref"); // nil=no info, false=nil, else table
565 // return created database result object:
566 return 1;
567 }
569 // method "quote_string" of database handles:
570 static int mondelefant_conn_quote_string(lua_State *L) {
571 mondelefant_conn_t *conn;
572 const char *input;
573 size_t input_len;
574 char *output;
575 size_t output_len;
576 // get 'conn' attribute of C-struct of database connection:
577 conn = mondelefant_get_conn(L, 1);
578 // get second argument, which must be a string:
579 input = luaL_checklstring(L, 2, &input_len);
580 // throw error, if string is too long:
581 if (input_len > (SIZE_MAX / sizeof(char) - 3) / 2) {
582 return luaL_error(L, "String to be escaped is too long.");
583 }
584 // allocate memory for quoted string:
585 output = malloc((2 * input_len + 3) * sizeof(char));
586 if (!output) {
587 return luaL_error(L, "Could not allocate memory for string quoting.");
588 }
589 // do escaping by calling PQescapeStringConn and enclosing result with
590 // single quotes:
591 output[0] = '\'';
592 output_len = PQescapeStringConn(
593 conn->pgconn, output + 1, input, input_len, NULL
594 );
595 output[output_len + 1] = '\'';
596 output[output_len + 2] = 0;
597 // create Lua string:
598 lua_pushlstring(L, output, output_len + 2);
599 // free allocated memory:
600 free(output);
601 // return Lua string:
602 return 1;
603 }
605 // method "quote_binary" of database handles:
606 static int mondelefant_conn_quote_binary(lua_State *L) {
607 mondelefant_conn_t *conn;
608 const char *input;
609 size_t input_len;
610 char *output;
611 size_t output_len;
612 luaL_Buffer buf;
613 // get 'conn' attribute of C-struct of database connection:
614 conn = mondelefant_get_conn(L, 1);
615 // get second argument, which must be a string:
616 input = luaL_checklstring(L, 2, &input_len);
617 // call PQescapeByteaConn, which allocates memory itself:
618 output = (char *)PQescapeByteaConn(
619 conn->pgconn, (const unsigned char *)input, input_len, &output_len
620 );
621 // if PQescapeByteaConn returned NULL, then throw error:
622 if (!output) {
623 return luaL_error(L, "Could not allocate memory for binary quoting.");
624 }
625 // create Lua string enclosed by single quotes:
626 luaL_buffinit(L, &buf);
627 luaL_addchar(&buf, '\'');
628 luaL_addlstring(&buf, output, output_len - 1);
629 luaL_addchar(&buf, '\'');
630 luaL_pushresult(&buf);
631 // free memory allocated by PQescapeByteaConn:
632 PQfreemem(output);
633 // return Lua string:
634 return 1;
635 }
637 // method "assemble_command" of database handles:
638 static int mondelefant_conn_assemble_command(lua_State *L) {
639 mondelefant_conn_t *conn;
640 int paramidx = 2;
641 const char *template;
642 size_t template_pos = 0;
643 luaL_Buffer buf;
644 // get 'conn' attribute of C-struct of database connection:
645 conn = mondelefant_get_conn(L, 1);
646 // if second argument is a string, return this string:
647 if (lua_type(L, 2) == LUA_TSTRING) {
648 lua_settop(L, 2);
649 return 1;
650 }
651 // if second argument has __tostring meta-method,
652 // then use this method and return its result:
653 if (luaL_callmeta(L, 2, "__tostring")) return 1;
654 // otherwise, require that second argument is a table:
655 luaL_checktype(L, 2, LUA_TTABLE);
656 // set stack top:
657 lua_settop(L, 2);
658 // get first element of table, which must be a string:
659 lua_rawgeti(L, 2, 1); // 3
660 luaL_argcheck(L,
661 lua_isstring(L, 3),
662 2,
663 "First entry of SQL command structure is not a string."
664 );
665 template = lua_tostring(L, 3);
666 // get value of "input_converter" attribute of database connection:
667 lua_pushliteral(L, "input_converter"); // 4
668 lua_gettable(L, 1); // input_converter at stack position 4
669 // reserve space on Lua stack:
670 lua_pushnil(L); // free space at stack position 5
671 lua_pushnil(L); // free space at stack position 6
672 // initialize Lua buffer for result string:
673 luaL_buffinit(L, &buf);
674 // fill buffer in loop:
675 while (1) {
676 // variable declaration:
677 char c;
678 // get next character:
679 c = template[template_pos++];
680 // break, when character is NULL byte:
681 if (!c) break;
682 // question-mark and dollar-sign are special characters:
683 if (c == '?' || c == '$') { // special character found
684 // check, if same character follows:
685 if (template[template_pos] == c) { // special character is escaped
686 // consume two characters of input and add one character to buffer:
687 template_pos++;
688 luaL_addchar(&buf, c);
689 } else { // special character is not escaped
690 luaL_Buffer keybuf;
691 int subcmd;
692 // set 'subcmd' = true, if special character was a dollar-sign,
693 // set 'subcmd' = false, if special character was a question-mark:
694 subcmd = (c == '$');
695 // read any number of alpha numeric chars or underscores
696 // and store them on Lua stack:
697 luaL_buffinit(L, &keybuf);
698 while (1) {
699 c = template[template_pos];
700 if (
701 (c < 'A' || c > 'Z') &&
702 (c < 'a' || c > 'z') &&
703 (c < '0' || c > '9') &&
704 (c != '_')
705 ) break;
706 luaL_addchar(&keybuf, c);
707 template_pos++;
708 }
709 luaL_pushresult(&keybuf);
710 // check, if any characters matched:
711 if (lua_rawlen(L, -1)) {
712 // if any alpha numeric chars or underscores were found,
713 // push them on stack as a Lua string and use them to lookup
714 // value from second argument:
715 lua_pushvalue(L, -1); // save key on stack
716 lua_gettable(L, 2); // fetch value (raw-value)
717 } else {
718 // otherwise push nil and use numeric lookup based on 'paramidx':
719 lua_pop(L, 1);
720 lua_pushnil(L); // put nil on key position
721 lua_rawgeti(L, 2, paramidx++); // fetch value (raw-value)
722 }
723 // Lua stack contains: ..., <buffer>, key, raw-value
724 // branch according to type of special character ("?" or "$"):
725 if (subcmd) { // dollar-sign
726 size_t i;
727 size_t count;
728 // store fetched value (which is supposed to be sub-structure)
729 // on Lua stack position 5 and drop key:
730 lua_replace(L, 5);
731 lua_pop(L, 1);
732 // Lua stack contains: ..., <buffer>
733 // check, if fetched value is really a sub-structure:
734 luaL_argcheck(L,
735 !lua_isnil(L, 5),
736 2,
737 "SQL sub-structure not found."
738 );
739 luaL_argcheck(L,
740 lua_type(L, 5) == LUA_TTABLE,
741 2,
742 "SQL sub-structure must be a table."
743 );
744 // Lua stack contains: ..., <buffer>
745 // get value of "sep" attribute of sub-structure,
746 // and place it on Lua stack position 6:
747 lua_getfield(L, 5, "sep");
748 lua_replace(L, 6);
749 // if seperator is nil, then use ", " as default,
750 // if seperator is neither nil nor a string, then throw error:
751 if (lua_isnil(L, 6)) {
752 lua_pushstring(L, ", ");
753 lua_replace(L, 6);
754 } else {
755 luaL_argcheck(L,
756 lua_isstring(L, 6),
757 2,
758 "Seperator of SQL sub-structure has to be a string."
759 );
760 }
761 // iterate over items of sub-structure:
762 count = lua_rawlen(L, 5);
763 for (i = 0; i < count; i++) {
764 // add seperator, unless this is the first run:
765 if (i) {
766 lua_pushvalue(L, 6);
767 luaL_addvalue(&buf);
768 }
769 // recursivly apply assemble function and add results to buffer:
770 lua_pushcfunction(L, mondelefant_conn_assemble_command);
771 lua_pushvalue(L, 1);
772 lua_rawgeti(L, 5, i+1);
773 lua_call(L, 2, 1);
774 luaL_addvalue(&buf);
775 }
776 } else { // question-mark
777 if (lua_toboolean(L, 4)) {
778 // call input_converter with connection handle, raw-value and
779 // an info-table which contains a "field_name" entry with the
780 // used key:
781 lua_pushvalue(L, 4);
782 lua_pushvalue(L, 1);
783 lua_pushvalue(L, -3);
784 lua_newtable(L);
785 lua_pushvalue(L, -6);
786 lua_setfield(L, -2, "field_name");
787 lua_call(L, 3, 1);
788 // Lua stack contains: ..., <buffer>, key, raw-value, final-value
789 // remove key and raw-value:
790 lua_remove(L, -2);
791 lua_remove(L, -2);
792 // Lua stack contains: ..., <buffer>, final-value
793 // throw error, if final-value is not a string:
794 if (!lua_isstring(L, -1)) {
795 return luaL_error(L, "input_converter returned non-string.");
796 }
797 } else {
798 // remove key from stack:
799 lua_remove(L, -2);
800 // Lua stack contains: ..., <buffer>, raw-value
801 // branch according to type of value:
802 if (lua_isnil(L, -1)) { // value is nil
803 // push string "NULL" to stack:
804 lua_pushliteral(L, "NULL");
805 } else if (lua_type(L, -1) == LUA_TBOOLEAN) { // value is boolean
806 // push strings "TRUE" or "FALSE" to stack:
807 lua_pushstring(L, lua_toboolean(L, -1) ? "TRUE" : "FALSE");
808 } else if (lua_isstring(L, -1)) { // value is string or number
809 // NOTE: In this version of lua a number will be converted
810 // push output of "quote_string" method of database
811 // connection to stack:
812 lua_tostring(L, -1);
813 lua_pushcfunction(L, mondelefant_conn_quote_string);
814 lua_pushvalue(L, 1);
815 lua_pushvalue(L, -3);
816 lua_call(L, 2, 1);
817 } else { // value is of other type
818 // throw error:
819 return luaL_error(L,
820 "Unable to convert SQL value due to unknown type "
821 "or missing input_converter."
822 );
823 }
824 // Lua stack contains: ..., <buffer>, raw-value, final-value
825 // remove raw-value:
826 lua_remove(L, -2);
827 // Lua stack contains: ..., <buffer>, final-value
828 }
829 // append final-value to buffer:
830 luaL_addvalue(&buf);
831 }
832 }
833 } else { // character is not special
834 // just copy character:
835 luaL_addchar(&buf, c);
836 }
837 }
838 // return string in buffer:
839 luaL_pushresult(&buf);
840 return 1;
841 }
843 // max number of SQL statements executed by one "query" method call:
844 #define MONDELEFANT_MAX_COMMAND_COUNT 64
845 // max number of columns in a database result:
846 #define MONDELEFANT_MAX_COLUMN_COUNT 1024
847 // enum values for 'modes' array in C-function below:
848 #define MONDELEFANT_QUERY_MODE_LIST 1
849 #define MONDELEFANT_QUERY_MODE_OBJECT 2
850 #define MONDELEFANT_QUERY_MODE_OPT_OBJECT 3
852 // method "try_query" of database handles:
853 static int mondelefant_conn_try_query(lua_State *L) {
854 mondelefant_conn_t *conn;
855 int command_count;
856 int command_idx;
857 int modes[MONDELEFANT_MAX_COMMAND_COUNT];
858 luaL_Buffer buf;
859 int sent_success;
860 PGresult *res;
861 int rows, cols, row, col;
862 // get 'conn' attribute of C-struct of database connection:
863 conn = mondelefant_get_conn(L, 1);
864 // calculate number of commands (2 arguments for one command):
865 command_count = lua_gettop(L) / 2;
866 // push nil on stack, which is needed, if last mode was ommitted:
867 lua_pushnil(L);
868 // throw error, if number of commands is too high:
869 if (command_count > MONDELEFANT_MAX_COMMAND_COUNT) {
870 return luaL_error(L, "Exceeded maximum command count in one query.");
871 }
872 // create SQL string, store query modes and push SQL string on stack:
873 luaL_buffinit(L, &buf);
874 for (command_idx = 0; command_idx < command_count; command_idx++) {
875 int mode;
876 int mode_idx; // stack index of mode string
877 if (command_idx) luaL_addchar(&buf, ' ');
878 lua_pushcfunction(L, mondelefant_conn_assemble_command);
879 lua_pushvalue(L, 1);
880 lua_pushvalue(L, 2 + 2 * command_idx);
881 lua_call(L, 2, 1);
882 luaL_addvalue(&buf);
883 luaL_addchar(&buf, ';');
884 mode_idx = 3 + 2 * command_idx;
885 if (lua_isnil(L, mode_idx)) {
886 mode = MONDELEFANT_QUERY_MODE_LIST;
887 } else {
888 const char *modestr;
889 modestr = luaL_checkstring(L, mode_idx);
890 if (!strcmp(modestr, "list")) {
891 mode = MONDELEFANT_QUERY_MODE_LIST;
892 } else if (!strcmp(modestr, "object")) {
893 mode = MONDELEFANT_QUERY_MODE_OBJECT;
894 } else if (!strcmp(modestr, "opt_object")) {
895 mode = MONDELEFANT_QUERY_MODE_OPT_OBJECT;
896 } else {
897 return luaL_argerror(L, mode_idx, "unknown query mode");
898 }
899 }
900 modes[command_idx] = mode;
901 }
902 luaL_pushresult(&buf); // stack position unknown
903 lua_replace(L, 2); // SQL command string to stack position 2
904 // call sql_tracer, if set:
905 lua_settop(L, 2);
906 lua_getfield(L, 1, "sql_tracer"); // tracer at stack position 3
907 if (lua_toboolean(L, 3)) {
908 lua_pushvalue(L, 1); // 4
909 lua_pushvalue(L, 2); // 5
910 lua_call(L, 2, 1); // trace callback at stack position 3
911 }
912 // NOTE: If no tracer was found, then nil or false is stored at stack
913 // position 3.
914 // call PQsendQuery function and store result in 'sent_success' variable:
915 sent_success = PQsendQuery(conn->pgconn, lua_tostring(L, 2));
916 // create preliminary result table:
917 lua_newtable(L); // results in table at stack position 4
918 // iterate over results using function PQgetResult to fill result table:
919 for (command_idx = 0; ; command_idx++) {
920 int mode;
921 char binary[MONDELEFANT_MAX_COLUMN_COUNT];
922 ExecStatusType pgstatus;
923 // fetch mode which was given for the command:
924 mode = modes[command_idx];
925 // if PQsendQuery call was successful, then fetch result data:
926 if (sent_success) {
927 // NOTE: PQgetResult called one extra time. Break only, if all
928 // queries have been processed and PQgetResult returned NULL.
929 res = PQgetResult(conn->pgconn);
930 if (command_idx >= command_count && !res) break;
931 if (res) {
932 pgstatus = PQresultStatus(res);
933 rows = PQntuples(res);
934 cols = PQnfields(res);
935 }
936 }
937 // handle errors:
938 if (
939 !sent_success || command_idx >= command_count || !res ||
940 (pgstatus != PGRES_TUPLES_OK && pgstatus != PGRES_COMMAND_OK) ||
941 (rows < 1 && mode == MONDELEFANT_QUERY_MODE_OBJECT) ||
942 (rows > 1 && mode != MONDELEFANT_QUERY_MODE_LIST)
943 ) {
944 const char *command;
945 command = lua_tostring(L, 2);
946 lua_newtable(L); // 5
947 lua_getfield(L,
948 LUA_REGISTRYINDEX,
949 MONDELEFANT_ERROROBJECT_MT_REGKEY
950 );
951 lua_setmetatable(L, 5);
952 lua_pushvalue(L, 1);
953 lua_setfield(L, 5, "connection");
954 lua_pushvalue(L, 2);
955 lua_setfield(L, 5, "sql_command");
956 if (!sent_success) {
957 lua_pushliteral(L, MONDELEFANT_ERRCODE_CONNECTION);
958 lua_setfield(L, 5, "code");
959 mondelefant_push_first_line(L, PQerrorMessage(conn->pgconn));
960 lua_setfield(L, 5, "message");
961 } else {
962 lua_pushinteger(L, command_idx + 1);
963 lua_setfield(L, 5, "command_number");
964 if (!res) {
965 lua_pushliteral(L, MONDELEFANT_ERRCODE_RESULTCOUNT_LOW);
966 lua_setfield(L, 5, "code");
967 lua_pushliteral(L, "Received too few database result sets.");
968 lua_setfield(L, 5, "message");
969 } else if (command_idx >= command_count) {
970 lua_pushliteral(L, MONDELEFANT_ERRCODE_RESULTCOUNT_HIGH);
971 lua_setfield(L, 5, "code");
972 lua_pushliteral(L, "Received too many database result sets.");
973 lua_setfield(L, 5, "message");
974 } else if (
975 pgstatus != PGRES_TUPLES_OK && pgstatus != PGRES_COMMAND_OK
976 ) {
977 const char *sqlstate;
978 const char *errmsg;
979 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_SEVERITY));
980 lua_setfield(L, 5, "pg_severity");
981 sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
982 if (sqlstate) {
983 lua_pushstring(L, sqlstate);
984 lua_setfield(L, 5, "pg_sqlstate");
985 lua_pushstring(L, mondelefant_translate_errcode(sqlstate));
986 lua_setfield(L, 5, "code");
987 } else {
988 lua_pushliteral(L, MONDELEFANT_ERRCODE_UNKNOWN);
989 lua_setfield(L, 5, "code");
990 }
991 errmsg = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
992 if (errmsg) {
993 mondelefant_push_first_line(L, errmsg);
994 lua_setfield(L, 5, "message");
995 lua_pushstring(L, errmsg);
996 lua_setfield(L, 5, "pg_message_primary");
997 } else {
998 lua_pushliteral(L,
999 "Error while fetching result, but no error message given."
1000 );
1001 lua_setfield(L, 5, "message");
1003 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL));
1004 lua_setfield(L, 5, "pg_message_detail");
1005 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_MESSAGE_HINT));
1006 lua_setfield(L, 5, "pg_message_hint");
1007 // NOTE: "position" and "pg_internal_position" are recalculated to
1008 // byte offsets, as Lua 5.2 is not Unicode aware.
1010 char *tmp;
1011 tmp = PQresultErrorField(res, PG_DIAG_STATEMENT_POSITION);
1012 if (tmp) {
1013 int pos;
1014 pos = atoi(tmp) - 1;
1015 if (conn->server_encoding == MONDELEFANT_SERVER_ENCODING_UTF8) {
1016 pos = utf8_position_to_byte(command, pos);
1018 lua_pushinteger(L, pos + 1);
1019 lua_setfield(L, 5, "position");
1023 const char *internal_query;
1024 internal_query = PQresultErrorField(res, PG_DIAG_INTERNAL_QUERY);
1025 lua_pushstring(L, internal_query);
1026 lua_setfield(L, 5, "pg_internal_query");
1027 char *tmp;
1028 tmp = PQresultErrorField(res, PG_DIAG_INTERNAL_POSITION);
1029 if (tmp) {
1030 int pos;
1031 pos = atoi(tmp) - 1;
1032 if (conn->server_encoding == MONDELEFANT_SERVER_ENCODING_UTF8) {
1033 pos = utf8_position_to_byte(internal_query, pos);
1035 lua_pushinteger(L, pos + 1);
1036 lua_setfield(L, 5, "pg_internal_position");
1039 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_CONTEXT));
1040 lua_setfield(L, 5, "pg_context");
1041 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_SOURCE_FILE));
1042 lua_setfield(L, 5, "pg_source_file");
1043 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_SOURCE_LINE));
1044 lua_setfield(L, 5, "pg_source_line");
1045 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_SOURCE_FUNCTION));
1046 lua_setfield(L, 5, "pg_source_function");
1047 } else if (rows < 1 && mode == MONDELEFANT_QUERY_MODE_OBJECT) {
1048 lua_pushliteral(L, MONDELEFANT_ERRCODE_QUERY1_NO_ROWS);
1049 lua_setfield(L, 5, "code");
1050 lua_pushliteral(L, "Expected one row, but got empty set.");
1051 lua_setfield(L, 5, "message");
1052 } else if (rows > 1 && mode != MONDELEFANT_QUERY_MODE_LIST) {
1053 lua_pushliteral(L, MONDELEFANT_ERRCODE_QUERY1_MULTIPLE_ROWS);
1054 lua_setfield(L, 5, "code");
1055 lua_pushliteral(L, "Got more than one result row.");
1056 lua_setfield(L, 5, "message");
1057 } else {
1058 // should not happen
1059 abort();
1061 if (res) {
1062 PQclear(res);
1063 while ((res = PQgetResult(conn->pgconn))) PQclear(res);
1066 if (lua_toboolean(L, 3)) {
1067 lua_pushvalue(L, 3);
1068 lua_pushvalue(L, 5);
1069 lua_call(L, 1, 0);
1071 return 1;
1073 // call "create_list" or "create_object" method of database handle,
1074 // result will be at stack position 5:
1075 if (modes[command_idx] == MONDELEFANT_QUERY_MODE_LIST) {
1076 lua_pushcfunction(L, mondelefant_conn_create_list); // 5
1077 lua_pushvalue(L, 1); // 6
1078 lua_call(L, 1, 1); // 5
1079 } else {
1080 lua_pushcfunction(L, mondelefant_conn_create_object); // 5
1081 lua_pushvalue(L, 1); // 6
1082 lua_call(L, 1, 1); // 5
1084 // set "_column_info":
1085 lua_newtable(L); // 6
1086 for (col = 0; col < cols; col++) {
1087 lua_newtable(L); // 7
1088 lua_pushstring(L, PQfname(res, col)); // 8
1089 lua_pushvalue(L, 8); // 9
1090 lua_pushvalue(L, 7); // 10
1091 lua_rawset(L, 6);
1092 lua_setfield(L, 7, "field_name");
1093 // _column_info entry (for current column) on stack position 7
1095 Oid tmp;
1096 tmp = PQftable(res, col);
1097 if (tmp == InvalidOid) lua_pushnil(L);
1098 else lua_pushinteger(L, tmp);
1099 lua_setfield(L, 7, "table_oid");
1102 int tmp;
1103 tmp = PQftablecol(res, col);
1104 if (tmp == 0) lua_pushnil(L);
1105 else lua_pushinteger(L, tmp);
1106 lua_setfield(L, 7, "table_column_number");
1109 Oid tmp;
1110 tmp = PQftype(res, col);
1111 binary[col] = (tmp == MONDELEFANT_POSTGRESQL_BINARY_OID);
1112 lua_pushinteger(L, tmp);
1113 lua_setfield(L, 7, "type_oid");
1114 lua_pushstring(L, mondelefant_oid_to_typestr(tmp));
1115 lua_setfield(L, 7, "type");
1118 int tmp;
1119 tmp = PQfmod(res, col);
1120 if (tmp == -1) lua_pushnil(L);
1121 else lua_pushinteger(L, tmp);
1122 lua_setfield(L, 7, "type_modifier");
1124 lua_rawseti(L, 6, col+1);
1126 lua_setfield(L, 5, "_column_info");
1127 // set "_rows_affected":
1129 char *tmp;
1130 tmp = PQcmdTuples(res);
1131 if (tmp[0]) {
1132 lua_pushinteger(L, atoi(tmp));
1133 lua_setfield(L, 5, "_rows_affected");
1136 // set "_oid":
1138 Oid tmp;
1139 tmp = PQoidValue(res);
1140 if (tmp != InvalidOid) {
1141 lua_pushinteger(L, tmp);
1142 lua_setfield(L, 5, "_oid");
1145 // copy data as strings or nil, while performing binary unescaping
1146 // automatically:
1147 if (modes[command_idx] == MONDELEFANT_QUERY_MODE_LIST) {
1148 for (row = 0; row < rows; row++) {
1149 lua_pushcfunction(L, mondelefant_conn_create_object); // 6
1150 lua_pushvalue(L, 1); // 7
1151 lua_call(L, 1, 1); // 6
1152 for (col = 0; col < cols; col++) {
1153 if (PQgetisnull(res, row, col)) {
1154 lua_pushnil(L);
1155 } else if (binary[col]) {
1156 size_t binlen;
1157 char *binval;
1158 binval = (char *)PQunescapeBytea(
1159 (unsigned char *)PQgetvalue(res, row, col), &binlen
1160 );
1161 if (!binval) {
1162 return luaL_error(L,
1163 "Could not allocate memory for binary unescaping."
1164 );
1166 lua_pushlstring(L, binval, binlen);
1167 PQfreemem(binval);
1168 } else {
1169 lua_pushstring(L, PQgetvalue(res, row, col));
1171 lua_rawseti(L, 6, col+1);
1173 lua_rawseti(L, 5, row+1);
1175 } else if (rows == 1) {
1176 for (col = 0; col < cols; col++) {
1177 if (PQgetisnull(res, 0, col)) {
1178 lua_pushnil(L);
1179 } else if (binary[col]) {
1180 size_t binlen;
1181 char *binval;
1182 binval = (char *)PQunescapeBytea(
1183 (unsigned char *)PQgetvalue(res, 0, col), &binlen
1184 );
1185 if (!binval) {
1186 return luaL_error(L,
1187 "Could not allocate memory for binary unescaping."
1188 );
1190 lua_pushlstring(L, binval, binlen);
1191 PQfreemem(binval);
1192 } else {
1193 lua_pushstring(L, PQgetvalue(res, 0, col));
1195 lua_rawseti(L, 5, col+1);
1197 } else {
1198 // no row in optrow mode
1199 lua_pop(L, 1);
1200 lua_pushnil(L);
1202 // save result in result list:
1203 lua_rawseti(L, 4, command_idx+1);
1204 // extra assertion:
1205 if (lua_gettop(L) != 4) abort(); // should not happen
1206 // free memory acquired by libpq:
1207 PQclear(res);
1209 // trace callback at stack position 3
1210 // result at stack position 4 (top of stack)
1211 // if a trace callback is existent, then call:
1212 if (lua_toboolean(L, 3)) {
1213 lua_pushvalue(L, 3);
1214 lua_call(L, 0, 0);
1216 // put result at stack position 3:
1217 lua_replace(L, 3);
1218 // get output converter to stack position 4:
1219 lua_getfield(L, 1, "output_converter");
1220 // get mutability state saver to stack position 5:
1221 lua_getfield(L, LUA_REGISTRYINDEX, MONDELEFANT_MODULE_REGKEY);
1222 lua_getfield(L, -1, "save_mutability_state");
1223 lua_replace(L, -2);
1224 // apply output converters and fill "_data" table according to column names:
1225 for (command_idx = 0; command_idx < command_count; command_idx++) {
1226 int mode;
1227 mode = modes[command_idx];
1228 lua_rawgeti(L, 3, command_idx+1); // raw result at stack position 6
1229 if (lua_toboolean(L, 6)) {
1230 lua_getfield(L, 6, "_column_info"); // column_info list at position 7
1231 cols = lua_rawlen(L, 7);
1232 if (mode == MONDELEFANT_QUERY_MODE_LIST) {
1233 rows = lua_rawlen(L, 6);
1234 for (row = 0; row < rows; row++) {
1235 lua_rawgeti(L, 6, row+1); // row at stack position 8
1236 lua_getfield(L, 8, "_data"); // _data table at stack position 9
1237 lua_getfield(L, 8, "_dirty"); // _dirty table at stack position 10
1238 for (col = 0; col < cols; col++) {
1239 lua_rawgeti(L, 7, col+1); // this column info at position 11
1240 lua_getfield(L, 11, "field_name"); // 12
1241 if (lua_toboolean(L, 4)) {
1242 lua_pushvalue(L, 4); // output-converter
1243 lua_pushvalue(L, 1); // connection
1244 lua_rawgeti(L, 8, col+1); // raw-value
1245 lua_pushvalue(L, 11); // this column info
1246 lua_call(L, 3, 1); // converted value at position 13
1247 } else {
1248 lua_rawgeti(L, 8, col+1); // raw-value at position 13
1250 if (lua_toboolean(L, 5)) { // handle mutable values?
1251 lua_pushvalue(L, 12); // copy of field name
1252 lua_pushvalue(L, 5); // mutability state saver function
1253 lua_pushvalue(L, 13); // copy of value
1254 lua_call(L, 1, 1); // calculated mutability state of value
1255 lua_rawset(L, 10); // store mutability state in _dirty table
1257 lua_pushvalue(L, 13); // 14
1258 lua_rawseti(L, 8, col+1);
1259 lua_rawset(L, 9);
1260 lua_settop(L, 10);
1262 lua_settop(L, 7);
1264 } else {
1265 lua_getfield(L, 6, "_data"); // _data table at stack position 8
1266 lua_getfield(L, 6, "_dirty"); // _dirty table at stack position 9
1267 for (col = 0; col < cols; col++) {
1268 lua_rawgeti(L, 7, col+1); // this column info at position 10
1269 lua_getfield(L, 10, "field_name"); // 11
1270 if (lua_toboolean(L, 4)) {
1271 lua_pushvalue(L, 4); // output-converter
1272 lua_pushvalue(L, 1); // connection
1273 lua_rawgeti(L, 6, col+1); // raw-value
1274 lua_pushvalue(L, 10); // this column info
1275 lua_call(L, 3, 1); // converted value at position 12
1276 } else {
1277 lua_rawgeti(L, 6, col+1); // raw-value at position 12
1279 if (lua_toboolean(L, 5)) { // handle mutable values?
1280 lua_pushvalue(L, 11); // copy of field name
1281 lua_pushvalue(L, 5); // mutability state saver function
1282 lua_pushvalue(L, 12); // copy of value
1283 lua_call(L, 1, 1); // calculated mutability state of value
1284 lua_rawset(L, 9); // store mutability state in _dirty table
1286 lua_pushvalue(L, 12); // 13
1287 lua_rawseti(L, 6, col+1);
1288 lua_rawset(L, 8);
1289 lua_settop(L, 9);
1293 lua_settop(L, 5);
1295 // return nil as first result value, followed by result lists/objects:
1296 lua_settop(L, 3);
1297 lua_pushnil(L);
1298 for (command_idx = 0; command_idx < command_count; command_idx++) {
1299 lua_rawgeti(L, 3, command_idx+1);
1301 return command_count+1;
1304 // method "is_kind_of" of error objects:
1305 static int mondelefant_errorobject_is_kind_of(lua_State *L) {
1306 const char *errclass;
1307 luaL_checktype(L, 1, LUA_TTABLE);
1308 errclass = luaL_checkstring(L, 2);
1309 lua_settop(L, 2);
1310 lua_getfield(L, 1, "code"); // 3
1311 luaL_argcheck(L,
1312 lua_type(L, 3) == LUA_TSTRING,
1313 1,
1314 "field 'code' of error object is not a string"
1315 );
1316 lua_pushboolean(L,
1317 mondelefant_check_error_class(lua_tostring(L, 3), errclass)
1318 );
1319 return 1;
1322 // method "wait" of database handles:
1323 static int mondelefant_conn_wait(lua_State *L) {
1324 int argc;
1325 // count number of arguments:
1326 argc = lua_gettop(L);
1327 // insert "try_wait" function/method at stack position 1:
1328 lua_pushcfunction(L, mondelefant_conn_try_wait);
1329 lua_insert(L, 1);
1330 // call "try_wait" method:
1331 lua_call(L, argc, LUA_MULTRET); // results (with error) starting at index 1
1332 // check, if error occurred:
1333 if (lua_toboolean(L, 1)) {
1334 // raise error
1335 lua_settop(L, 1);
1336 return lua_error(L);
1337 } else {
1338 // return everything but nil error object:
1339 return lua_gettop(L) - 1;
1343 // method "query" of database handles:
1344 static int mondelefant_conn_query(lua_State *L) {
1345 int argc;
1346 // count number of arguments:
1347 argc = lua_gettop(L);
1348 // insert "try_query" function/method at stack position 1:
1349 lua_pushcfunction(L, mondelefant_conn_try_query);
1350 lua_insert(L, 1);
1351 // call "try_query" method:
1352 lua_call(L, argc, LUA_MULTRET); // results (with error) starting at index 1
1353 // check, if error occurred:
1354 if (lua_toboolean(L, 1)) {
1355 // raise error
1356 lua_settop(L, 1);
1357 return lua_error(L);
1358 } else {
1359 // return everything but nil error object:
1360 return lua_gettop(L) - 1;
1364 // library function "set_class":
1365 static int mondelefant_set_class(lua_State *L) {
1366 // ensure that first argument is a database result list/object:
1367 lua_settop(L, 2);
1368 lua_getmetatable(L, 1); // 3
1369 lua_getfield(L, LUA_REGISTRYINDEX, MONDELEFANT_RESULT_MT_REGKEY); // 4
1370 luaL_argcheck(L, lua_compare(L, 3, 4, LUA_OPEQ), 1, "not a database result");
1371 // ensure that second argument is a database class (model):
1372 lua_settop(L, 2);
1373 lua_getmetatable(L, 2); // 3
1374 lua_getfield(L, LUA_REGISTRYINDEX, MONDELEFANT_CLASS_MT_REGKEY); // 4
1375 luaL_argcheck(L, lua_compare(L, 3, 4, LUA_OPEQ), 2, "not a database class");
1376 // set attribute "_class" of result list/object to given class:
1377 lua_settop(L, 2);
1378 lua_pushvalue(L, 2); // 3
1379 lua_setfield(L, 1, "_class");
1380 // test, if database result is a list (and not a single object):
1381 lua_getfield(L, 1, "_type"); // 3
1382 lua_pushliteral(L, "list"); // 4
1383 if (lua_rawequal(L, 3, 4)) {
1384 int i;
1385 // set attribute "_class" of all elements to given class:
1386 for (i=0; i < lua_rawlen(L, 1); i++) {
1387 lua_settop(L, 2);
1388 lua_rawgeti(L, 1, i+1); // 3
1389 lua_pushvalue(L, 2); // 4
1390 lua_setfield(L, 3, "_class");
1393 // return first argument:
1394 lua_settop(L, 1);
1395 return 1;
1398 // library function "new_class":
1399 static int mondelefant_new_class(lua_State *L) {
1400 // if no argument is given, use an empty table:
1401 if (lua_isnoneornil(L, 1)) {
1402 lua_settop(L, 0);
1403 lua_newtable(L); // 1
1404 } else {
1405 luaL_checktype(L, 1, LUA_TTABLE);
1406 lua_settop(L, 1);
1408 // set meta-table for database classes (models):
1409 lua_getfield(L, LUA_REGISTRYINDEX, MONDELEFANT_CLASS_MT_REGKEY); // 2
1410 lua_setmetatable(L, 1);
1411 // check, if "prototype" attribute is not set:
1412 lua_pushliteral(L, "prototype"); // 2
1413 lua_rawget(L, 1); // 2
1414 if (!lua_toboolean(L, 2)) {
1415 // set "prototype" attribute to default prototype:
1416 lua_pushliteral(L, "prototype"); // 3
1417 lua_getfield(L,
1418 LUA_REGISTRYINDEX,
1419 MONDELEFANT_CLASS_PROTO_REGKEY
1420 ); // 4
1421 lua_rawset(L, 1);
1423 // set "object" attribute to empty table, unless it is already set:
1424 lua_settop(L, 1);
1425 lua_pushliteral(L, "object"); // 2
1426 lua_rawget(L, 1); // 2
1427 if (!lua_toboolean(L, 2)) {
1428 lua_pushliteral(L, "object"); // 3
1429 lua_newtable(L); // 4
1430 lua_rawset(L, 1);
1432 // set "object_get" attribute to empty table, unless it is already set:
1433 lua_settop(L, 1);
1434 lua_pushliteral(L, "object_get"); // 2
1435 lua_rawget(L, 1); // 2
1436 if (!lua_toboolean(L, 2)) {
1437 lua_pushliteral(L, "object_get"); // 3
1438 lua_newtable(L); // 4
1439 lua_rawset(L, 1);
1441 // set "object_set" attribute to empty table, unless it is already set:
1442 lua_settop(L, 1);
1443 lua_pushliteral(L, "object_set"); // 2
1444 lua_rawget(L, 1); // 2
1445 if (!lua_toboolean(L, 2)) {
1446 lua_pushliteral(L, "object_set"); // 3
1447 lua_newtable(L); // 4
1448 lua_rawset(L, 1);
1450 // set "list" attribute to empty table, unless it is already set:
1451 lua_settop(L, 1);
1452 lua_pushliteral(L, "list"); // 2
1453 lua_rawget(L, 1); // 2
1454 if (!lua_toboolean(L, 2)) {
1455 lua_pushliteral(L, "list"); // 3
1456 lua_newtable(L); // 4
1457 lua_rawset(L, 1);
1459 // set "references" attribute to empty table, unless it is already set:
1460 lua_settop(L, 1);
1461 lua_pushliteral(L, "references"); // 2
1462 lua_rawget(L, 1); // 2
1463 if (!lua_toboolean(L, 2)) {
1464 lua_pushliteral(L, "references"); // 3
1465 lua_newtable(L); // 4
1466 lua_rawset(L, 1);
1468 // set "foreign_keys" attribute to empty table, unless it is already set:
1469 lua_settop(L, 1);
1470 lua_pushliteral(L, "foreign_keys"); // 2
1471 lua_rawget(L, 1); // 2
1472 if (!lua_toboolean(L, 2)) {
1473 lua_pushliteral(L, "foreign_keys"); // 3
1474 lua_newtable(L); // 4
1475 lua_rawset(L, 1);
1477 // return table:
1478 lua_settop(L, 1);
1479 return 1;
1482 // method "get_reference" of classes (models):
1483 static int mondelefant_class_get_reference(lua_State *L) {
1484 lua_settop(L, 2);
1485 while (lua_toboolean(L, 1)) {
1486 // get "references" table:
1487 lua_getfield(L, 1, "references"); // 3
1488 // perform lookup:
1489 lua_pushvalue(L, 2); // 4
1490 lua_gettable(L, 3); // 4
1491 // return result, if lookup was successful:
1492 if (!lua_isnil(L, 4)) return 1;
1493 // replace current table by its prototype:
1494 lua_settop(L, 2);
1495 lua_pushliteral(L, "prototype"); // 3
1496 lua_rawget(L, 1); // 3
1497 lua_replace(L, 1);
1499 // return nothing:
1500 return 0;
1503 // method "iterate_over_references" of classes (models):
1504 static int mondelefant_class_iterate_over_references(lua_State *L) {
1505 return luaL_error(L, "Reference iterator not implemented yet."); // TODO
1508 // method "get_foreign_key_reference_name" of classes (models):
1509 static int mondelefant_class_get_foreign_key_reference_name(lua_State *L) {
1510 lua_settop(L, 2);
1511 while (lua_toboolean(L, 1)) {
1512 // get "foreign_keys" table:
1513 lua_getfield(L, 1, "foreign_keys"); // 3
1514 // perform lookup:
1515 lua_pushvalue(L, 2); // 4
1516 lua_gettable(L, 3); // 4
1517 // return result, if lookup was successful:
1518 if (!lua_isnil(L, 4)) return 1;
1519 // replace current table by its prototype:
1520 lua_settop(L, 2);
1521 lua_pushliteral(L, "prototype"); // 3
1522 lua_rawget(L, 1); // 3
1523 lua_replace(L, 1);
1525 // return nothing:
1526 return 0;
1529 // meta-method "__index" of database result lists and objects:
1530 static int mondelefant_result_index(lua_State *L) {
1531 const char *result_type;
1532 // only lookup, when key is a string not beginning with an underscore:
1533 if (lua_type(L, 2) != LUA_TSTRING || lua_tostring(L, 2)[0] == '_') {
1534 return 0;
1536 // value of "_class" attribute or default class on stack position 3:
1537 lua_settop(L, 2);
1538 lua_getfield(L, 1, "_class"); // 3
1539 if (!lua_toboolean(L, 3)) {
1540 lua_settop(L, 2);
1541 lua_getfield(L,
1542 LUA_REGISTRYINDEX,
1543 MONDELEFANT_CLASS_PROTO_REGKEY
1544 ); // 3
1546 // get value of "_type" attribute:
1547 lua_getfield(L, 1, "_type"); // 4
1548 result_type = lua_tostring(L, 4);
1549 // different lookup for lists and objects:
1550 if (result_type && !strcmp(result_type, "object")) { // object
1551 lua_settop(L, 3);
1552 // try inherited attributes, methods or getter functions:
1553 lua_pushvalue(L, 3); // 4
1554 while (lua_toboolean(L, 4)) {
1555 lua_getfield(L, 4, "object"); // 5
1556 lua_pushvalue(L, 2); // 6
1557 lua_gettable(L, 5); // 6
1558 if (!lua_isnil(L, 6)) return 1;
1559 lua_settop(L, 4);
1560 lua_getfield(L, 4, "object_get"); // 5
1561 lua_pushvalue(L, 2); // 6
1562 lua_gettable(L, 5); // 6
1563 if (lua_toboolean(L, 6)) {
1564 lua_pushvalue(L, 1); // 7
1565 lua_call(L, 1, 1); // 6
1566 return 1;
1568 lua_settop(L, 4);
1569 lua_pushliteral(L, "prototype"); // 5
1570 lua_rawget(L, 4); // 5
1571 lua_replace(L, 4);
1573 lua_settop(L, 3);
1574 // try primary keys of referenced objects:
1575 lua_pushcfunction(L,
1576 mondelefant_class_get_foreign_key_reference_name
1577 ); // 4
1578 lua_pushvalue(L, 3); // 5
1579 lua_pushvalue(L, 2); // 6
1580 lua_call(L, 2, 1); // 4
1581 if (!lua_isnil(L, 4)) {
1582 // reference name at stack position 4
1583 lua_pushcfunction(L, mondelefant_class_get_reference); // 5
1584 lua_pushvalue(L, 3); // 6
1585 lua_pushvalue(L, 4); // 7
1586 lua_call(L, 2, 1); // reference info at stack position 5
1587 lua_getfield(L, 1, "_ref"); // 6
1588 lua_getfield(L, 5, "ref"); // 7
1589 lua_gettable(L, 6); // 7
1590 if (!lua_isnil(L, 7)) {
1591 if (lua_toboolean(L, 7)) {
1592 lua_getfield(L, 5, "that_key"); // 8
1593 if (lua_isnil(L, 8)) {
1594 return luaL_error(L, "Missing 'that_key' entry in model reference.");
1596 lua_gettable(L, 7); // 8
1597 } else {
1598 lua_pushnil(L);
1600 return 1;
1603 lua_settop(L, 3);
1604 lua_getfield(L, 1, "_data"); // _data table on stack position 4
1605 // try normal data field info:
1606 lua_pushvalue(L, 2); // 5
1607 lua_gettable(L, 4); // 5
1608 if (!lua_isnil(L, 5)) return 1;
1609 lua_settop(L, 4); // keep _data table on stack
1610 // try cached referenced object (or cached NULL reference):
1611 lua_getfield(L, 1, "_ref"); // 5
1612 lua_pushvalue(L, 2); // 6
1613 lua_gettable(L, 5); // 6
1614 if (lua_isboolean(L, 6) && !lua_toboolean(L, 6)) {
1615 lua_pushnil(L);
1616 return 1;
1617 } else if (!lua_isnil(L, 6)) {
1618 return 1;
1620 lua_settop(L, 4);
1621 // try to load a referenced object:
1622 lua_pushcfunction(L, mondelefant_class_get_reference); // 5
1623 lua_pushvalue(L, 3); // 6
1624 lua_pushvalue(L, 2); // 7
1625 lua_call(L, 2, 1); // 5
1626 if (!lua_isnil(L, 5)) {
1627 lua_settop(L, 2);
1628 lua_getfield(L, 1, "load"); // 3
1629 lua_pushvalue(L, 1); // 4 (self)
1630 lua_pushvalue(L, 2); // 5
1631 lua_call(L, 2, 0);
1632 lua_settop(L, 2);
1633 lua_getfield(L, 1, "_ref"); // 3
1634 lua_pushvalue(L, 2); // 4
1635 lua_gettable(L, 3); // 4
1636 if (lua_isboolean(L, 4) && !lua_toboolean(L, 4)) lua_pushnil(L); // TODO: use special object instead of false
1637 return 1;
1639 lua_settop(L, 4);
1640 // try proxy access to document in special column:
1641 lua_getfield(L, 3, "document_column"); // 5
1642 if (lua_toboolean(L, 5)) {
1643 lua_gettable(L, 4); // 5
1644 if (!lua_isnil(L, 5)) {
1645 lua_pushvalue(L, 2); // 6
1646 lua_gettable(L, 5); // 6
1647 if (!lua_isnil(L, 6)) return 1;
1650 return 0;
1651 } else if (result_type && !strcmp(result_type, "list")) { // list
1652 lua_settop(L, 3);
1653 // try inherited list attributes or methods:
1654 while (lua_toboolean(L, 3)) {
1655 lua_getfield(L, 3, "list"); // 4
1656 lua_pushvalue(L, 2); // 5
1657 lua_gettable(L, 4); // 5
1658 if (!lua_isnil(L, 5)) return 1;
1659 lua_settop(L, 3);
1660 lua_pushliteral(L, "prototype"); // 4
1661 lua_rawget(L, 3); // 4
1662 lua_replace(L, 3);
1665 // return nothing:
1666 return 0;
1669 // meta-method "__newindex" of database result lists and objects:
1670 static int mondelefant_result_newindex(lua_State *L) {
1671 const char *result_type;
1672 // perform rawset, unless key is a string not starting with underscore:
1673 lua_settop(L, 3);
1674 if (lua_type(L, 2) != LUA_TSTRING || lua_tostring(L, 2)[0] == '_') {
1675 lua_rawset(L, 1);
1676 return 1;
1678 // value of "_class" attribute or default class on stack position 4:
1679 lua_settop(L, 3);
1680 lua_getfield(L, 1, "_class"); // 4
1681 if (!lua_toboolean(L, 4)) {
1682 lua_settop(L, 3);
1683 lua_getfield(L,
1684 LUA_REGISTRYINDEX,
1685 MONDELEFANT_CLASS_PROTO_REGKEY
1686 ); // 4
1688 // get value of "_type" attribute:
1689 lua_getfield(L, 1, "_type"); // 5
1690 result_type = lua_tostring(L, 5);
1691 // distinguish between lists and objects:
1692 if (result_type && !strcmp(result_type, "object")) { // objects
1693 lua_settop(L, 4);
1694 // try object setter functions:
1695 lua_pushvalue(L, 4); // 5
1696 while (lua_toboolean(L, 5)) {
1697 lua_getfield(L, 5, "object_set"); // 6
1698 lua_pushvalue(L, 2); // 7
1699 lua_gettable(L, 6); // 7
1700 if (lua_toboolean(L, 7)) {
1701 lua_pushvalue(L, 1); // 8
1702 lua_pushvalue(L, 3); // 9
1703 lua_call(L, 2, 0);
1704 return 0;
1706 lua_settop(L, 5);
1707 lua_pushliteral(L, "prototype"); // 6
1708 lua_rawget(L, 5); // 6
1709 lua_replace(L, 5);
1711 lua_settop(L, 4);
1712 lua_getfield(L, 1, "_data"); // _data table on stack position 5
1713 // check, if a object reference is changed:
1714 lua_pushcfunction(L, mondelefant_class_get_reference); // 6
1715 lua_pushvalue(L, 4); // 7
1716 lua_pushvalue(L, 2); // 8
1717 lua_call(L, 2, 1); // 6
1718 if (!lua_isnil(L, 6)) {
1719 // store object in _ref table (use false for nil): // TODO: use special object instead of false
1720 lua_getfield(L, 1, "_ref"); // 7
1721 lua_pushvalue(L, 2); // 8
1722 if (lua_isnil(L, 3)) lua_pushboolean(L, 0); // 9
1723 else lua_pushvalue(L, 3); // 9
1724 lua_settable(L, 7);
1725 lua_settop(L, 6);
1726 // delete referencing key from _data table:
1727 lua_getfield(L, 6, "this_key"); // 7
1728 if (lua_isnil(L, 7)) {
1729 return luaL_error(L, "Missing 'this_key' entry in model reference.");
1731 lua_pushvalue(L, 7); // 8
1732 lua_pushnil(L); // 9
1733 lua_settable(L, 5);
1734 lua_getfield(L, 1, "_dirty"); // 8
1735 lua_pushvalue(L, 7); // 9
1736 lua_pushboolean(L, 1); // 10
1737 lua_settable(L, 8);
1738 return 0;
1740 lua_settop(L, 5);
1741 // check proxy access to document in special column:
1742 lua_getfield(L, 4, "document_column"); // 6
1743 if (lua_toboolean(L, 6)) {
1744 lua_getfield(L, 1, "_column_info"); // 7
1745 if (!lua_isnil(L, 7)) { // TODO: quick fix to avoid problems on document creation
1746 lua_pushvalue(L, 2); // 8
1747 lua_gettable(L, 7); // 8
1748 if (!lua_toboolean(L, 8)) {
1749 lua_settop(L, 6);
1750 lua_gettable(L, 5); // 6
1751 if (lua_isnil(L, 6)) {
1752 return luaL_error(L, "Cannot write to document column: document is nil");
1754 lua_pushvalue(L, 2); // 7
1755 lua_pushvalue(L, 3); // 8
1756 lua_settable(L, 6);
1757 return 0;
1759 } // TODO: quick fix to avoid problems on document creation
1761 lua_settop(L, 5);
1762 // store value in data field info:
1763 lua_pushvalue(L, 2); // 6
1764 lua_pushvalue(L, 3); // 7
1765 lua_settable(L, 5);
1766 lua_settop(L, 4);
1767 // mark field as dirty (needs to be UPDATEd on save):
1768 lua_getfield(L, 1, "_dirty"); // 5
1769 lua_pushvalue(L, 2); // 6
1770 lua_pushboolean(L, 1); // 7
1771 lua_settable(L, 5);
1772 lua_settop(L, 4);
1773 // reset reference cache, if neccessary:
1774 lua_pushcfunction(L,
1775 mondelefant_class_get_foreign_key_reference_name
1776 ); // 5
1777 lua_pushvalue(L, 4); // 6
1778 lua_pushvalue(L, 2); // 7
1779 lua_call(L, 2, 1); // 5
1780 if (!lua_isnil(L, 5)) {
1781 lua_getfield(L, 1, "_ref"); // 6
1782 lua_pushvalue(L, 5); // 7
1783 lua_pushnil(L); // 8
1784 lua_settable(L, 6);
1786 return 0;
1787 } else { // non-objects (i.e. lists)
1788 // perform rawset:
1789 lua_settop(L, 3);
1790 lua_rawset(L, 1);
1791 return 0;
1795 // meta-method "__index" of classes (models):
1796 static int mondelefant_class_index(lua_State *L) {
1797 // perform lookup in prototype:
1798 lua_settop(L, 2);
1799 lua_pushliteral(L, "prototype"); // 3
1800 lua_rawget(L, 1); // 3
1801 lua_pushvalue(L, 2); // 4
1802 lua_gettable(L, 3); // 4
1803 return 1;
1806 // registration information for functions of library:
1807 static const struct luaL_Reg mondelefant_module_functions[] = {
1808 {"connect", mondelefant_connect},
1809 {"set_class", mondelefant_set_class},
1810 {"new_class", mondelefant_new_class},
1811 {NULL, NULL}
1812 };
1814 // registration information for meta-methods of database connections:
1815 static const struct luaL_Reg mondelefant_conn_mt_functions[] = {
1816 {"__gc", mondelefant_conn_free},
1817 {"__index", mondelefant_conn_index},
1818 {"__newindex", mondelefant_conn_newindex},
1819 {NULL, NULL}
1820 };
1822 // registration information for methods of database connections:
1823 static const struct luaL_Reg mondelefant_conn_methods[] = {
1824 {"close", mondelefant_conn_close},
1825 {"is_ok", mondelefant_conn_is_ok},
1826 {"get_transaction_status", mondelefant_conn_get_transaction_status},
1827 {"try_wait", mondelefant_conn_try_wait},
1828 {"wait", mondelefant_conn_wait},
1829 {"create_list", mondelefant_conn_create_list},
1830 {"create_object", mondelefant_conn_create_object},
1831 {"quote_string", mondelefant_conn_quote_string},
1832 {"quote_binary", mondelefant_conn_quote_binary},
1833 {"assemble_command", mondelefant_conn_assemble_command},
1834 {"try_query", mondelefant_conn_try_query},
1835 {"query", mondelefant_conn_query},
1836 {NULL, NULL}
1837 };
1839 // registration information for meta-methods of error objects:
1840 static const struct luaL_Reg mondelefant_errorobject_mt_functions[] = {
1841 {NULL, NULL}
1842 };
1844 // registration information for methods of error objects:
1845 static const struct luaL_Reg mondelefant_errorobject_methods[] = {
1846 {"escalate", lua_error},
1847 {"is_kind_of", mondelefant_errorobject_is_kind_of},
1848 {NULL, NULL}
1849 };
1851 // registration information for meta-methods of database result lists/objects:
1852 static const struct luaL_Reg mondelefant_result_mt_functions[] = {
1853 {"__index", mondelefant_result_index},
1854 {"__newindex", mondelefant_result_newindex},
1855 {NULL, NULL}
1856 };
1858 // registration information for methods of database result lists/objects:
1859 static const struct luaL_Reg mondelefant_class_mt_functions[] = {
1860 {"__index", mondelefant_class_index},
1861 {NULL, NULL}
1862 };
1864 // registration information for methods of classes (models):
1865 static const struct luaL_Reg mondelefant_class_methods[] = {
1866 {"get_reference", mondelefant_class_get_reference},
1867 {"iterate_over_references", mondelefant_class_iterate_over_references},
1868 {"get_foreign_key_reference_name",
1869 mondelefant_class_get_foreign_key_reference_name},
1870 {NULL, NULL}
1871 };
1873 // registration information for methods of database result objects (not lists!):
1874 static const struct luaL_Reg mondelefant_object_methods[] = {
1875 {NULL, NULL}
1876 };
1878 // registration information for methods of database result lists (not single objects!):
1879 static const struct luaL_Reg mondelefant_list_methods[] = {
1880 {NULL, NULL}
1881 };
1883 // luaopen function to initialize/register library:
1884 int luaopen_mondelefant_native(lua_State *L) {
1885 lua_settop(L, 0);
1886 lua_newtable(L); // module at stack position 1
1887 luaL_setfuncs(L, mondelefant_module_functions, 0);
1889 lua_pushvalue(L, 1); // 2
1890 lua_setfield(L, LUA_REGISTRYINDEX, MONDELEFANT_MODULE_REGKEY);
1892 lua_newtable(L); // 2
1893 // NOTE: only PostgreSQL is supported yet:
1894 luaL_setfuncs(L, mondelefant_conn_methods, 0);
1895 lua_setfield(L, 1, "postgresql_connection_prototype");
1896 lua_newtable(L); // 2
1897 lua_setfield(L, 1, "connection_prototype");
1899 luaL_newmetatable(L, MONDELEFANT_CONN_MT_REGKEY); // 2
1900 luaL_setfuncs(L, mondelefant_conn_mt_functions, 0);
1901 lua_settop(L, 1);
1902 luaL_newmetatable(L, MONDELEFANT_RESULT_MT_REGKEY); // 2
1903 luaL_setfuncs(L, mondelefant_result_mt_functions, 0);
1904 lua_setfield(L, 1, "result_metatable");
1905 luaL_newmetatable(L, MONDELEFANT_CLASS_MT_REGKEY); // 2
1906 luaL_setfuncs(L, mondelefant_class_mt_functions, 0);
1907 lua_setfield(L, 1, "class_metatable");
1909 lua_newtable(L); // 2
1910 luaL_setfuncs(L, mondelefant_class_methods, 0);
1911 lua_newtable(L); // 3
1912 luaL_setfuncs(L, mondelefant_object_methods, 0);
1913 lua_setfield(L, 2, "object");
1914 lua_newtable(L); // 3
1915 lua_setfield(L, 2, "object_get");
1916 lua_newtable(L); // 3
1917 lua_setfield(L, 2, "object_set");
1918 lua_newtable(L); // 3
1919 luaL_setfuncs(L, mondelefant_list_methods, 0);
1920 lua_setfield(L, 2, "list");
1921 lua_newtable(L); // 3
1922 lua_setfield(L, 2, "references");
1923 lua_newtable(L); // 3
1924 lua_setfield(L, 2, "foreign_keys");
1925 lua_pushvalue(L, 2); // 3
1926 lua_setfield(L, LUA_REGISTRYINDEX, MONDELEFANT_CLASS_PROTO_REGKEY);
1927 lua_setfield(L, 1, "class_prototype");
1929 luaL_newmetatable(L, MONDELEFANT_ERROROBJECT_MT_REGKEY); // 2
1930 luaL_setfuncs(L, mondelefant_errorobject_mt_functions, 0);
1931 lua_newtable(L); // 3
1932 luaL_setfuncs(L, mondelefant_errorobject_methods, 0);
1933 lua_setfield(L, 2, "__index");
1934 lua_setfield(L, 1, "errorobject_metatable");
1936 return 1;

Impressum / About Us