webmcp

view libraries/mondelefant/mondelefant_native.c @ 374:11ef7ab67e43

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

Impressum / About Us