webmcp

view libraries/mondelefant/mondelefant_native.c @ 60:f2fe38a54504

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

Impressum / About Us