webmcp

view libraries/mondelefant/mondelefant_native.c @ 396:762ab1e87702

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

Impressum / About Us