webmcp

view libraries/mondelefant/mondelefant_native.c @ 400:7b183a70a37d

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

Impressum / About Us