webmcp

view libraries/mondelefant/mondelefant_native.c @ 0:9fdfb27f8e67

Version 1.0.0
author jbe/bsw
date Sun Oct 25 12:00:00 2009 +0100 (2009-10-25)
parents
children 3a6fe8663b26
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 #define MONDELEFANT_REGKEY "e449ba8d9a53d353_mondelefant"
10 #define MONDELEFANT_MODULE_REGKEY (MONDELEFANT_REGKEY "_module")
11 #define MONDELEFANT_CONN_MT_REGKEY (MONDELEFANT_REGKEY "_connection")
12 #define MONDELEFANT_CONN_DATA_REGKEY (MONDELEFANT_REGKEY "_connection_data")
13 #define MONDELEFANT_RESULT_MT_REGKEY (MONDELEFANT_REGKEY "_result")
14 #define MONDELEFANT_ERROROBJECT_MT_REGKEY (MONDELEFANT_REGKEY "_errorobject")
15 #define MONDELEFANT_CLASS_MT_REGKEY (MONDELEFANT_REGKEY "_class")
16 #define MONDELEFANT_CLASS_PROTO_REGKEY (MONDELEFANT_REGKEY "_class_proto")
18 #define MONDELEFANT_SERVER_ENCODING_ASCII 0
19 #define MONDELEFANT_SERVER_ENCODING_UTF8 1
21 typedef struct {
22 PGconn *pgconn;
23 int server_encoding;
24 } mondelefant_conn_t;
26 static size_t utf8_position_to_byte(const char *str, size_t utf8pos) {
27 size_t bytepos;
28 for (bytepos = 0; utf8pos > 0; bytepos++) {
29 uint8_t c;
30 c = ((const uint8_t *)str)[bytepos];
31 if (!c) break;
32 if (c <= 0x7f || c >= 0xc0) utf8pos--;
33 }
34 return bytepos;
35 }
37 #define MONDELEFANT_POSTGRESQL_BINARY_OID ((Oid)17)
39 static const char *mondelefant_oid_to_typestr(Oid oid) {
40 switch (oid) {
41 case 16: return "bool";
42 case 17: return "bytea";
43 case 18: return "char";
44 case 19: return "name";
45 case 20: return "int8";
46 case 21: return "int2";
47 case 23: return "int4";
48 case 25: return "text";
49 case 26: return "oid";
50 case 27: return "tid";
51 case 28: return "xid";
52 case 29: return "cid";
53 case 600: return "point";
54 case 601: return "lseg";
55 case 602: return "path";
56 case 603: return "box";
57 case 604: return "polygon";
58 case 628: return "line";
59 case 700: return "float4";
60 case 701: return "float8";
61 case 705: return "unknown";
62 case 718: return "circle";
63 case 790: return "money";
64 case 829: return "macaddr";
65 case 869: return "inet";
66 case 650: return "cidr";
67 case 1042: return "bpchar";
68 case 1043: return "varchar";
69 case 1082: return "date";
70 case 1083: return "time";
71 case 1114: return "timestamp";
72 case 1184: return "timestamptz";
73 case 1186: return "interval";
74 case 1266: return "timetz";
75 case 1560: return "bit";
76 case 1562: return "varbit";
77 case 1700: return "numeric";
78 default: return NULL;
79 }
80 }
82 #define mondelefant_errcode_item(incode, outcode) \
83 if (!strncmp(pgcode, (incode), strlen(incode))) return outcode; else
85 #define MONDELEFANT_ERRCODE_UNKNOWN "unknown"
86 #define MONDELEFANT_ERRCODE_CONNECTION "ConnectionException"
87 #define MONDELEFANT_ERRCODE_RESULTCOUNT_LOW "WrongResultSetCount.ResultSetMissing"
88 #define MONDELEFANT_ERRCODE_RESULTCOUNT_HIGH "WrongResultSetCount.TooManyResults"
89 #define MONDELEFANT_ERRCODE_QUERY1_NO_ROWS "NoData.OneRowExpected"
90 #define MONDELEFANT_ERRCODE_QUERY1_MULTIPLE_ROWS "CardinalityViolation.OneRowExpected"
92 static const char *mondelefant_translate_errcode(const char *pgcode) {
93 if (!pgcode) abort(); // should not happen
94 mondelefant_errcode_item("02", "NoData")
95 mondelefant_errcode_item("03", "SqlStatementNotYetComplete")
96 mondelefant_errcode_item("08", "ConnectionException")
97 mondelefant_errcode_item("09", "TriggeredActionException")
98 mondelefant_errcode_item("0A", "FeatureNotSupported")
99 mondelefant_errcode_item("0B", "InvalidTransactionInitiation")
100 mondelefant_errcode_item("0F", "LocatorException")
101 mondelefant_errcode_item("0L", "InvalidGrantor")
102 mondelefant_errcode_item("0P", "InvalidRoleSpecification")
103 mondelefant_errcode_item("21", "CardinalityViolation")
104 mondelefant_errcode_item("22", "DataException")
105 mondelefant_errcode_item("23001", "IntegrityConstraintViolation.RestrictViolation")
106 mondelefant_errcode_item("23502", "IntegrityConstraintViolation.NotNullViolation")
107 mondelefant_errcode_item("23503", "IntegrityConstraintViolation.ForeignKeyViolation")
108 mondelefant_errcode_item("23505", "IntegrityConstraintViolation.UniqueViolation")
109 mondelefant_errcode_item("23514", "IntegrityConstraintViolation.CheckViolation")
110 mondelefant_errcode_item("23", "IntegrityConstraintViolation")
111 mondelefant_errcode_item("24", "InvalidCursorState")
112 mondelefant_errcode_item("25", "InvalidTransactionState")
113 mondelefant_errcode_item("26", "InvalidSqlStatementName")
114 mondelefant_errcode_item("27", "TriggeredDataChangeViolation")
115 mondelefant_errcode_item("28", "InvalidAuthorizationSpecification")
116 mondelefant_errcode_item("2B", "DependentPrivilegeDescriptorsStillExist")
117 mondelefant_errcode_item("2D", "InvalidTransactionTermination")
118 mondelefant_errcode_item("2F", "SqlRoutineException")
119 mondelefant_errcode_item("34", "InvalidCursorName")
120 mondelefant_errcode_item("38", "ExternalRoutineException")
121 mondelefant_errcode_item("39", "ExternalRoutineInvocationException")
122 mondelefant_errcode_item("3B", "SavepointException")
123 mondelefant_errcode_item("3D", "InvalidCatalogName")
124 mondelefant_errcode_item("3F", "InvalidSchemaName")
125 mondelefant_errcode_item("40", "TransactionRollback")
126 mondelefant_errcode_item("42", "SyntaxErrorOrAccessRuleViolation")
127 mondelefant_errcode_item("44", "WithCheckOptionViolation")
128 mondelefant_errcode_item("53", "InsufficientResources")
129 mondelefant_errcode_item("54", "ProgramLimitExceeded")
130 mondelefant_errcode_item("55", "ObjectNotInPrerequisiteState")
131 mondelefant_errcode_item("57", "OperatorIntervention")
132 mondelefant_errcode_item("58", "SystemError")
133 mondelefant_errcode_item("F0", "ConfigurationFileError")
134 mondelefant_errcode_item("P0", "PlpgsqlError")
135 mondelefant_errcode_item("XX", "InternalError")
136 return "unknown";
137 }
139 static int mondelefant_check_error_class(
140 const char *errcode, const char *errclass
141 ) {
142 size_t i = 0;
143 while (1) {
144 if (errclass[i] == 0) {
145 if (errcode[i] == 0 || errcode[i] == '.') return 1;
146 else return 0;
147 }
148 if (errcode[i] != errclass[i]) return 0;
149 i++;
150 }
151 }
153 static void mondelefant_push_first_line(lua_State *L, const char *str) {
154 char *str2;
155 size_t i = 0;
156 if (!str) abort(); // should not happen
157 str2 = strdup(str);
158 while (1) {
159 char c = str2[i];
160 if (c == '\n' || c == '\r' || c == 0) { str2[i] = 0; break; }
161 i++;
162 };
163 lua_pushstring(L, str2);
164 free(str2);
165 }
167 static int mondelefant_connect(lua_State *L) {
168 luaL_Buffer buf;
169 const char *conninfo;
170 PGconn *pgconn;
171 mondelefant_conn_t *conn;
172 lua_settop(L, 1);
173 lua_getfield(L, 1, "engine"); // 2
174 if (!lua_toboolean(L, 2)) {
175 return luaL_error(L, "No database engine selected.");
176 }
177 lua_pushliteral(L, "postgresql"); // 3
178 if (!lua_rawequal(L, 2, 3)) {
179 return luaL_error(L,
180 "Only database engine 'postgresql' is supported."
181 );
182 }
183 lua_settop(L, 1);
184 lua_pushnil(L); // slot for key at stack position 2
185 lua_pushnil(L); // slot for value at stack position 3
186 luaL_buffinit(L, &buf);
187 {
188 int need_seperator = 0;
189 while (lua_pushvalue(L, 2), lua_next(L, 1)) {
190 lua_replace(L, 3);
191 lua_replace(L, 2);
192 // NOTE: numbers will be converted to strings automatically here,
193 // but perhaps this will change in future versions of lua
194 luaL_argcheck(L,
195 lua_isstring(L, 2) && lua_isstring(L, 3), 1, "non-string contained"
196 );
197 lua_pushvalue(L, 2);
198 lua_pushliteral(L, "engine");
199 if (!lua_rawequal(L, -2, -1)) {
200 const char *value;
201 size_t value_len;
202 size_t value_pos = 0;
203 lua_pop(L, 1);
204 if (need_seperator) luaL_addchar(&buf, ' ');
205 luaL_addvalue(&buf);
206 luaL_addchar(&buf, '=');
207 luaL_addchar(&buf, '\'');
208 value = lua_tolstring(L, 3, &value_len);
209 do {
210 char c;
211 c = value[value_pos++];
212 if (c == '\'') luaL_addchar(&buf, '\\');
213 luaL_addchar(&buf, c);
214 } while (value_pos < value_len);
215 luaL_addchar(&buf, '\'');
216 need_seperator = 1;
217 } else {
218 lua_pop(L, 1);
219 }
220 }
221 }
222 luaL_pushresult(&buf);
223 lua_replace(L, 2);
224 lua_settop(L, 2);
225 conninfo = lua_tostring(L, 2);
226 pgconn = PQconnectdb(conninfo);
227 if (!pgconn) {
228 return luaL_error(L,
229 "Error in libpq while creating 'PGconn' structure."
230 );
231 }
232 if (PQstatus(pgconn) != CONNECTION_OK) {
233 const char *errmsg;
234 lua_pushnil(L);
235 errmsg = PQerrorMessage(pgconn);
236 if (errmsg) {
237 mondelefant_push_first_line(L, errmsg);
238 } else {
239 lua_pushliteral(L,
240 "Error while connecting to database, but no error message given."
241 );
242 }
243 lua_pushliteral(L, MONDELEFANT_ERRCODE_CONNECTION);
244 PQfinish(pgconn);
245 return 3;
246 }
247 lua_settop(L, 0);
248 conn = lua_newuserdata(L, sizeof(*conn)); // 1
249 conn->pgconn = pgconn;
250 {
251 const char *charset;
252 charset = PQparameterStatus(pgconn, "server_encoding");
253 if (charset && !strcmp(charset, "UTF8")) {
254 conn->server_encoding = MONDELEFANT_SERVER_ENCODING_UTF8;
255 } else {
256 conn->server_encoding = MONDELEFANT_SERVER_ENCODING_ASCII;
257 }
258 }
260 luaL_getmetatable(L, MONDELEFANT_CONN_MT_REGKEY); // 2
261 lua_setmetatable(L, 1);
263 lua_getfield(L, LUA_REGISTRYINDEX, MONDELEFANT_CONN_DATA_REGKEY); // 2
264 lua_pushvalue(L, 1); // 3
265 lua_newtable(L); // 4
266 lua_settable(L, 2);
267 lua_settop(L, 1);
269 lua_pushliteral(L, "postgresql");
270 lua_setfield(L, 1, "engine");
271 return 1;
272 }
274 static mondelefant_conn_t *mondelefant_get_conn(lua_State *L, int index) {
275 mondelefant_conn_t *conn;
276 conn = luaL_checkudata(L, index, MONDELEFANT_CONN_MT_REGKEY);
277 if (!conn->pgconn) {
278 luaL_error(L, "PostgreSQL connection has been closed.");
279 return NULL;
280 }
281 return conn;
282 }
284 static int mondelefant_conn_index(lua_State *L) {
285 lua_settop(L, 2);
286 lua_getfield(L, LUA_REGISTRYINDEX, MONDELEFANT_CONN_DATA_REGKEY); // 3
287 lua_pushvalue(L, 1); // 4
288 lua_gettable(L, 3); // 4
289 lua_remove(L, 3); // connection specific data-table at stack position 3
290 lua_pushvalue(L, 2); // 4
291 lua_gettable(L, 3); // 4
292 if (!lua_isnil(L, 4)) return 1;
293 lua_settop(L, 3);
294 lua_getfield(L, 3, "prototype"); // 4
295 if (lua_toboolean(L, 4)) {
296 lua_pushvalue(L, 2); // 5
297 lua_gettable(L, 4); // 5
298 if (!lua_isnil(L, 5)) return 1;
299 }
300 lua_settop(L, 2);
301 lua_getfield(L, LUA_REGISTRYINDEX, MONDELEFANT_MODULE_REGKEY); // 3
302 lua_getfield(L, 3, "postgresql_connection_prototype"); // 4
303 if (lua_toboolean(L, 4)) {
304 lua_pushvalue(L, 2); // 5
305 lua_gettable(L, 4); // 5
306 if (!lua_isnil(L, 5)) return 1;
307 }
308 lua_settop(L, 3);
309 lua_getfield(L, 3, "connection_prototype"); // 4
310 if (lua_toboolean(L, 4)) {
311 lua_pushvalue(L, 2); // 5
312 lua_gettable(L, 4); // 5
313 if (!lua_isnil(L, 5)) return 1;
314 }
315 return 0;
316 }
318 static int mondelefant_conn_newindex(lua_State *L) {
319 lua_settop(L, 3);
320 lua_getfield(L, LUA_REGISTRYINDEX, MONDELEFANT_CONN_DATA_REGKEY); // 4
321 lua_pushvalue(L, 1); // 5
322 lua_gettable(L, 4); // 5
323 lua_remove(L, 4); // connection specific data-table at stack position 4
324 lua_pushvalue(L, 2);
325 lua_pushvalue(L, 3);
326 lua_settable(L, 4);
327 return 0;
328 }
330 static int mondelefant_conn_free(lua_State *L) {
331 mondelefant_conn_t *conn;
332 conn = luaL_checkudata(L, 1, MONDELEFANT_CONN_MT_REGKEY);
333 if (conn->pgconn) PQfinish(conn->pgconn);
334 conn->pgconn = NULL;
335 return 0;
336 }
338 static int mondelefant_conn_close(lua_State *L) {
339 mondelefant_conn_t *conn;
340 lua_settop(L, 1);
341 conn = mondelefant_get_conn(L, 1);
342 PQfinish(conn->pgconn);
343 conn->pgconn = NULL;
344 return 0;
345 }
347 static int mondelefant_conn_is_ok(lua_State *L) {
348 mondelefant_conn_t *conn;
349 lua_settop(L, 1);
350 conn = mondelefant_get_conn(L, 1);
351 lua_pushboolean(L, PQstatus(conn->pgconn) == CONNECTION_OK);
352 return 1;
353 }
355 static int mondelefant_conn_get_transaction_status(lua_State *L) {
356 mondelefant_conn_t *conn;
357 lua_settop(L, 1);
358 conn = mondelefant_get_conn(L, 1);
359 switch (PQtransactionStatus(conn->pgconn)) {
360 case PQTRANS_IDLE:
361 lua_pushliteral(L, "idle");
362 break;
363 case PQTRANS_ACTIVE:
364 lua_pushliteral(L, "active");
365 break;
366 case PQTRANS_INTRANS:
367 lua_pushliteral(L, "intrans");
368 break;
369 case PQTRANS_INERROR:
370 lua_pushliteral(L, "inerror");
371 break;
372 default:
373 lua_pushliteral(L, "unknown");
374 }
375 return 1;
376 }
378 static int mondelefant_conn_create_list(lua_State *L) {
379 lua_settop(L, 2);
380 luaL_checkudata(L, 1, MONDELEFANT_CONN_MT_REGKEY);
381 if (!lua_toboolean(L, 2)) {
382 lua_newtable(L);
383 lua_replace(L, 2); // new result at stack position 2
384 }
385 lua_getfield(L, LUA_REGISTRYINDEX, MONDELEFANT_RESULT_MT_REGKEY); // 3
386 lua_setmetatable(L, 2);
387 lua_pushvalue(L, 1); // 3
388 lua_setfield(L, 2, "_connection");
389 lua_pushliteral(L, "list"); // 3
390 lua_setfield(L, 2, "_type");
391 return 1;
392 }
394 static int mondelefant_conn_create_object(lua_State *L) {
395 lua_settop(L, 2);
396 luaL_checkudata(L, 1, MONDELEFANT_CONN_MT_REGKEY);
397 if (!lua_toboolean(L, 2)) {
398 lua_newtable(L);
399 lua_replace(L, 2); // new result at stack position 2
400 }
401 lua_getfield(L, LUA_REGISTRYINDEX, MONDELEFANT_RESULT_MT_REGKEY); // 3
402 lua_setmetatable(L, 2);
403 lua_pushvalue(L, 1); // 3
404 lua_setfield(L, 2, "_connection");
405 lua_pushliteral(L, "object"); // 3
406 lua_setfield(L, 2, "_type"); // "object" or "list"
407 lua_newtable(L); // 3
408 lua_setfield(L, 2, "_data");
409 lua_newtable(L); // 3
410 lua_setfield(L, 2, "_dirty");
411 lua_newtable(L); // 3
412 lua_setfield(L, 2, "_ref"); // nil=no info, false=nil, else table
413 return 1;
414 }
416 static int mondelefant_conn_quote_string(lua_State *L) {
417 mondelefant_conn_t *conn;
418 const char *input;
419 size_t input_len;
420 char *output;
421 size_t output_len;
422 lua_settop(L, 2);
423 conn = mondelefant_get_conn(L, 1);
424 input = luaL_checklstring(L, 2, &input_len);
425 if (input_len > (SIZE_MAX / sizeof(char) - 3) / 2) {
426 return luaL_error(L, "String to be escaped is too long.");
427 }
428 output = malloc((2 * input_len + 3) * sizeof(char));
429 if (!output) {
430 return luaL_error(L, "Could not allocate memory for string quoting.");
431 }
432 output[0] = '\'';
433 output_len = PQescapeStringConn(
434 conn->pgconn, output + 1, input, input_len, NULL
435 );
436 output[output_len + 1] = '\'';
437 output[output_len + 2] = 0;
438 lua_pushlstring(L, output, output_len + 2);
439 free(output);
440 return 1;
441 }
443 static int mondelefant_conn_quote_binary(lua_State *L) {
444 mondelefant_conn_t *conn;
445 const char *input;
446 size_t input_len;
447 char *output;
448 size_t output_len;
449 luaL_Buffer buf;
450 lua_settop(L, 2);
451 conn = mondelefant_get_conn(L, 1);
452 input = luaL_checklstring(L, 2, &input_len);
453 output = (char *)PQescapeByteaConn(
454 conn->pgconn, (const unsigned char *)input, input_len, &output_len
455 );
456 if (!output) {
457 return luaL_error(L, "Could not allocate memory for binary quoting.");
458 }
459 luaL_buffinit(L, &buf);
460 luaL_addchar(&buf, '\'');
461 luaL_addlstring(&buf, output, output_len - 1);
462 luaL_addchar(&buf, '\'');
463 luaL_pushresult(&buf);
464 PQfreemem(output);
465 return 1;
466 }
468 static int mondelefant_conn_assemble_command(lua_State *L) {
469 mondelefant_conn_t *conn;
470 int paramidx = 2;
471 const char *template;
472 size_t template_pos = 0;
473 luaL_Buffer buf;
474 lua_settop(L, 2);
475 conn = mondelefant_get_conn(L, 1);
476 if (lua_isstring(L, 2)) {
477 lua_tostring(L, 2);
478 return 1;
479 }
480 // extra feature for objects with __tostring meta-method:
481 if (luaL_callmeta(L, 2, "__tostring")) return 1;
482 luaL_checktype(L, 2, LUA_TTABLE);
483 lua_rawgeti(L, 2, 1); // 3
484 luaL_argcheck(L,
485 lua_isstring(L, 3),
486 2,
487 "First entry of SQL command structure is not a string."
488 );
489 template = lua_tostring(L, 3);
490 lua_pushliteral(L, "input_converter"); // 4
491 lua_gettable(L, 1); // input_converter at stack position 4
492 lua_pushnil(L); // free space at stack position 5
493 lua_pushnil(L); // free space at stack position 6
494 luaL_buffinit(L, &buf);
495 while (1) {
496 char c;
497 c = template[template_pos++];
498 if (!c) break;
499 if (c == '?' || c == '$') {
500 if (template[template_pos] == c) {
501 template_pos++;
502 luaL_addchar(&buf, c);
503 } else {
504 luaL_Buffer keybuf;
505 int subcmd;
506 subcmd = (c == '$');
507 luaL_buffinit(L, &keybuf);
508 while (1) {
509 c = template[template_pos];
510 if (
511 (c < 'A' || c > 'Z') &&
512 (c < 'a' || c > 'z') &&
513 (c < '0' || c > '9') &&
514 (c != '_')
515 ) break;
516 luaL_addchar(&keybuf, c);
517 template_pos++;
518 }
519 luaL_pushresult(&keybuf);
520 if (lua_objlen(L, -1)) {
521 lua_pushvalue(L, -1); // save key on stack
522 lua_gettable(L, 2); // fetch value
523 } else {
524 lua_pop(L, 1);
525 lua_pushnil(L); // put nil on key position
526 lua_rawgeti(L, 2, paramidx++); // fetch value
527 }
528 // stack: ..., <buffer>, key, pre-value
529 if (subcmd) {
530 size_t i;
531 size_t count;
532 lua_replace(L, 5); // sub-structure at stack position 5
533 lua_pop(L, 1); // drop stored key
534 // stack: ..., <buffer>
535 luaL_argcheck(L,
536 !lua_isnil(L, 5),
537 2,
538 "SQL sub-structure not found."
539 );
540 luaL_argcheck(L,
541 lua_type(L, 5) == LUA_TTABLE,
542 2,
543 "SQL sub-structure must be a table."
544 );
545 // stack: ..., <buffer>
546 lua_getfield(L, 5, "sep");
547 lua_replace(L, 6); // seperator at stack position 6
548 if (lua_isnil(L, 6)) {
549 lua_pushstring(L, ", ");
550 lua_replace(L, 6);
551 } else {
552 luaL_argcheck(L,
553 lua_isstring(L, 6),
554 2,
555 "Seperator of SQL sub-structure has to be a string."
556 );
557 }
558 count = lua_objlen(L, 5);
559 for (i = 0; i < count; i++) {
560 if (i) {
561 lua_pushvalue(L, 6);
562 luaL_addvalue(&buf);
563 }
564 lua_pushcfunction(L, mondelefant_conn_assemble_command);
565 lua_pushvalue(L, 1);
566 lua_rawgeti(L, 5, i+1);
567 lua_call(L, 2, 1);
568 luaL_addvalue(&buf);
569 }
570 } else {
571 if (lua_toboolean(L, 4)) {
572 // call input_converter with connection handle, value and info
573 lua_pushvalue(L, 4);
574 lua_pushvalue(L, 1);
575 lua_pushvalue(L, -3);
576 lua_newtable(L);
577 lua_pushvalue(L, -6);
578 lua_setfield(L, -2, "field_name");
579 lua_call(L, 3, 1);
580 // stack: ..., <buffer>, key, pre-value, final-value
581 lua_remove(L, -2);
582 lua_remove(L, -2);
583 // stack: ..., <buffer>, final-value
584 if (!lua_isstring(L, -1)) {
585 return luaL_error(L, "input_converter returned non-string.");
586 }
587 } else {
588 lua_remove(L, -2);
589 // stack: ..., <buffer>, pre-value
590 if (lua_isnil(L, -1)) {
591 lua_pushliteral(L, "NULL");
592 } else if (lua_type(L, -1) == LUA_TBOOLEAN) {
593 lua_pushstring(L, lua_toboolean(L, -1) ? "TRUE" : "FALSE");
594 } else if (lua_isstring(L, -1)) {
595 // NOTE: In this version of lua a number will be converted
596 lua_tostring(L, -1);
597 lua_pushcfunction(L, mondelefant_conn_quote_string);
598 lua_pushvalue(L, 1);
599 lua_pushvalue(L, -3);
600 lua_call(L, 2, 1);
601 } else {
602 return luaL_error(L,
603 "Unable to convert SQL value due to unknown type "
604 "or missing input_converter."
605 );
606 }
607 // stack: ..., <buffer>, pre-value, final-value
608 lua_remove(L, -2);
609 // stack: ..., <buffer>, final-value
610 }
611 luaL_addvalue(&buf);
612 }
613 }
614 } else {
615 luaL_addchar(&buf, c);
616 }
617 }
618 luaL_pushresult(&buf);
619 return 1;
620 }
622 #define MONDELEFANT_MAX_COMMAND_COUNT 64
623 #define MONDELEFANT_MAX_COLUMN_COUNT 1024
624 #define MONDELEFANT_QUERY_MODE_LIST 1
625 #define MONDELEFANT_QUERY_MODE_OBJECT 2
626 #define MONDELEFANT_QUERY_MODE_OPT_OBJECT 3
628 static int mondelefant_conn_try_query(lua_State *L) {
629 mondelefant_conn_t *conn;
630 int command_count;
631 int command_idx;
632 int modes[MONDELEFANT_MAX_COMMAND_COUNT];
633 luaL_Buffer buf;
634 int sent_success;
635 PGresult *res;
636 int rows, cols, row, col;
637 conn = mondelefant_get_conn(L, 1);
638 command_count = lua_gettop(L) / 2;
639 lua_pushnil(L); // needed, if last mode was omitted
640 if (command_count > MONDELEFANT_MAX_COMMAND_COUNT) {
641 return luaL_error(L, "Exceeded maximum command count in one query.");
642 }
643 luaL_buffinit(L, &buf);
644 for (command_idx = 0; command_idx < command_count; command_idx++) {
645 int mode;
646 int mode_idx; // stack index of mode string
647 if (command_idx) luaL_addchar(&buf, ' ');
648 lua_pushcfunction(L, mondelefant_conn_assemble_command);
649 lua_pushvalue(L, 1);
650 lua_pushvalue(L, 2 + 2 * command_idx);
651 lua_call(L, 2, 1);
652 luaL_addvalue(&buf);
653 luaL_addchar(&buf, ';');
654 mode_idx = 3 + 2 * command_idx;
655 if (lua_isnil(L, mode_idx)) {
656 mode = MONDELEFANT_QUERY_MODE_LIST;
657 } else {
658 const char *modestr;
659 modestr = luaL_checkstring(L, mode_idx);
660 if (!strcmp(modestr, "list")) {
661 mode = MONDELEFANT_QUERY_MODE_LIST;
662 } else if (!strcmp(modestr, "object")) {
663 mode = MONDELEFANT_QUERY_MODE_OBJECT;
664 } else if (!strcmp(modestr, "opt_object")) {
665 mode = MONDELEFANT_QUERY_MODE_OPT_OBJECT;
666 } else {
667 return luaL_error(L, "Unknown query mode specified.");
668 }
669 }
670 modes[command_idx] = mode;
671 }
672 luaL_pushresult(&buf); // stack position unknown
673 lua_replace(L, 2); // SQL command string to stack position 2
674 lua_settop(L, 2);
675 lua_getfield(L, 1, "sql_tracer"); // tracer at stack position 3
676 if (lua_toboolean(L, 3)) {
677 lua_pushvalue(L, 1); // 4
678 lua_pushvalue(L, 2); // 5
679 lua_call(L, 2, 1); // trace callback at stack position 3
680 }
681 sent_success = PQsendQuery(conn->pgconn, lua_tostring(L, 2));
682 lua_newtable(L); // results in table at stack position 4
683 for (command_idx = 0; ; command_idx++) {
684 int mode;
685 char binary[MONDELEFANT_MAX_COLUMN_COUNT];
686 ExecStatusType pgstatus;
687 mode = modes[command_idx];
688 if (sent_success) {
689 res = PQgetResult(conn->pgconn);
690 if (command_idx >= command_count && !res) break;
691 if (res) {
692 pgstatus = PQresultStatus(res);
693 rows = PQntuples(res);
694 cols = PQnfields(res);
695 }
696 }
697 if (
698 !sent_success || command_idx >= command_count || !res ||
699 (pgstatus != PGRES_TUPLES_OK && pgstatus != PGRES_COMMAND_OK) ||
700 (rows < 1 && mode == MONDELEFANT_QUERY_MODE_OBJECT) ||
701 (rows > 1 && mode != MONDELEFANT_QUERY_MODE_LIST)
702 ) {
703 const char *command;
704 command = lua_tostring(L, 2);
705 lua_newtable(L); // 5
706 lua_getfield(L,
707 LUA_REGISTRYINDEX,
708 MONDELEFANT_ERROROBJECT_MT_REGKEY
709 );
710 lua_setmetatable(L, 5);
711 lua_pushvalue(L, 1);
712 lua_setfield(L, 5, "connection");
713 lua_pushinteger(L, command_idx + 1);
714 lua_setfield(L, 5, "command_number");
715 lua_pushvalue(L, 2);
716 lua_setfield(L, 5, "sql_command");
717 if (!res) {
718 lua_pushliteral(L, MONDELEFANT_ERRCODE_RESULTCOUNT_LOW);
719 lua_setfield(L, 5, "code");
720 lua_pushliteral(L, "Received too few database result sets.");
721 lua_setfield(L, 5, "message");
722 } else if (command_idx >= command_count) {
723 lua_pushliteral(L, MONDELEFANT_ERRCODE_RESULTCOUNT_HIGH);
724 lua_setfield(L, 5, "code");
725 lua_pushliteral(L, "Received too many database result sets.");
726 lua_setfield(L, 5, "message");
727 } else if (
728 pgstatus != PGRES_TUPLES_OK && pgstatus != PGRES_COMMAND_OK
729 ) {
730 const char *sqlstate;
731 const char *errmsg;
732 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_SEVERITY));
733 lua_setfield(L, 5, "pg_severity");
734 sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
735 if (sqlstate) {
736 lua_pushstring(L, sqlstate);
737 lua_setfield(L, 5, "pg_sqlstate");
738 lua_pushstring(L, mondelefant_translate_errcode(sqlstate));
739 lua_setfield(L, 5, "code");
740 } else {
741 lua_pushliteral(L, MONDELEFANT_ERRCODE_UNKNOWN);
742 lua_setfield(L, 5, "code");
743 }
744 errmsg = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
745 if (errmsg) {
746 mondelefant_push_first_line(L, errmsg);
747 lua_setfield(L, 5, "message");
748 lua_pushstring(L, errmsg);
749 lua_setfield(L, 5, "pg_message_primary");
750 } else {
751 lua_pushliteral(L,
752 "Error while fetching result, but no error message given."
753 );
754 lua_setfield(L, 5, "message");
755 }
756 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL));
757 lua_setfield(L, 5, "pg_message_detail");
758 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_MESSAGE_HINT));
759 lua_setfield(L, 5, "pg_message_hint");
760 // NOTE: "position" and "pg_internal_position" are recalculated to
761 // byte offsets, as Lua 5.1 is not Unicode aware.
762 {
763 char *tmp;
764 tmp = PQresultErrorField(res, PG_DIAG_STATEMENT_POSITION);
765 if (tmp) {
766 int pos;
767 pos = atoi(tmp) - 1;
768 if (conn->server_encoding == MONDELEFANT_SERVER_ENCODING_UTF8) {
769 pos = utf8_position_to_byte(command, pos);
770 }
771 lua_pushinteger(L, pos + 1);
772 lua_setfield(L, 5, "position");
773 }
774 }
775 {
776 const char *internal_query;
777 internal_query = PQresultErrorField(res, PG_DIAG_INTERNAL_QUERY);
778 lua_pushstring(L, internal_query);
779 lua_setfield(L, 5, "pg_internal_query");
780 char *tmp;
781 tmp = PQresultErrorField(res, PG_DIAG_INTERNAL_POSITION);
782 if (tmp) {
783 int pos;
784 pos = atoi(tmp) - 1;
785 if (conn->server_encoding == MONDELEFANT_SERVER_ENCODING_UTF8) {
786 pos = utf8_position_to_byte(internal_query, pos);
787 }
788 lua_pushinteger(L, pos + 1);
789 lua_setfield(L, 5, "pg_internal_position");
790 }
791 }
792 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_CONTEXT));
793 lua_setfield(L, 5, "pg_context");
794 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_SOURCE_FILE));
795 lua_setfield(L, 5, "pg_source_file");
796 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_SOURCE_LINE));
797 lua_setfield(L, 5, "pg_source_line");
798 lua_pushstring(L, PQresultErrorField(res, PG_DIAG_SOURCE_FUNCTION));
799 lua_setfield(L, 5, "pg_source_function");
800 } else if (rows < 1 && mode == MONDELEFANT_QUERY_MODE_OBJECT) {
801 lua_pushliteral(L, MONDELEFANT_ERRCODE_QUERY1_NO_ROWS);
802 lua_setfield(L, 5, "code");
803 lua_pushliteral(L, "Expected one row, but got empty set.");
804 lua_setfield(L, 5, "message");
805 } else if (rows > 1 && mode != MONDELEFANT_QUERY_MODE_LIST) {
806 lua_pushliteral(L, MONDELEFANT_ERRCODE_QUERY1_MULTIPLE_ROWS);
807 lua_setfield(L, 5, "code");
808 lua_pushliteral(L, "Got more than one result row.");
809 lua_setfield(L, 5, "message");
810 } else {
811 // should not happen
812 abort();
813 }
814 if (res) {
815 PQclear(res);
816 while ((res = PQgetResult(conn->pgconn))) PQclear(res);
817 }
818 if (lua_toboolean(L, 3)) {
819 lua_pushvalue(L, 3);
820 lua_pushvalue(L, 5);
821 lua_call(L, 1, 0);
822 }
823 return 1;
824 }
825 rows = PQntuples(res);
826 cols = PQnfields(res);
827 if (modes[command_idx] == MONDELEFANT_QUERY_MODE_LIST) {
828 lua_pushcfunction(L, mondelefant_conn_create_list); // 5
829 lua_pushvalue(L, 1); // 6
830 lua_call(L, 1, 1); // 5
831 } else {
832 lua_pushcfunction(L, mondelefant_conn_create_object); // 5
833 lua_pushvalue(L, 1); // 6
834 lua_call(L, 1, 1); // 5
835 }
836 lua_newtable(L); // column_info at atack position 6
837 for (col = 0; col < cols; col++) {
838 lua_newtable(L); // 7
839 lua_pushstring(L, PQfname(res, col));
840 lua_setfield(L, 7, "field_name");
841 {
842 Oid tmp;
843 tmp = PQftable(res, col);
844 if (tmp == InvalidOid) lua_pushnil(L);
845 else lua_pushinteger(L, tmp);
846 lua_setfield(L, 7, "table_oid");
847 }
848 {
849 int tmp;
850 tmp = PQftablecol(res, col);
851 if (tmp == 0) lua_pushnil(L);
852 else lua_pushinteger(L, tmp);
853 lua_setfield(L, 7, "table_column_number");
854 }
855 {
856 Oid tmp;
857 tmp = PQftype(res, col);
858 binary[col] = (tmp == MONDELEFANT_POSTGRESQL_BINARY_OID);
859 lua_pushinteger(L, tmp);
860 lua_setfield(L, 7, "type_oid");
861 lua_pushstring(L, mondelefant_oid_to_typestr(tmp));
862 lua_setfield(L, 7, "type");
863 }
864 {
865 int tmp;
866 tmp = PQfmod(res, col);
867 if (tmp == -1) lua_pushnil(L);
868 else lua_pushinteger(L, tmp);
869 lua_setfield(L, 7, "type_modifier");
870 }
871 lua_rawseti(L, 6, col+1);
872 }
873 lua_setfield(L, 5, "_column_info"); // stack at position 5 with result
874 {
875 char *tmp;
876 tmp = PQcmdTuples(res);
877 if (tmp[0]) {
878 lua_pushinteger(L, atoi(tmp));
879 lua_setfield(L, 5, "_rows_affected");
880 }
881 }
882 {
883 Oid tmp;
884 tmp = PQoidValue(res);
885 if (tmp != InvalidOid) {
886 lua_pushinteger(L, tmp);
887 lua_setfield(L, 5, "_oid");
888 }
889 }
890 if (modes[command_idx] == MONDELEFANT_QUERY_MODE_LIST) {
891 for (row = 0; row < rows; row++) {
892 lua_pushcfunction(L, mondelefant_conn_create_object); // 6
893 lua_pushvalue(L, 1); // 7
894 lua_call(L, 1, 1); // 6
895 for (col = 0; col < cols; col++) {
896 if (PQgetisnull(res, row, col)) {
897 lua_pushnil(L);
898 } else if (binary[col]) {
899 size_t binlen;
900 char *binval;
901 binval = (char *)PQunescapeBytea(
902 (unsigned char *)PQgetvalue(res, row, col), &binlen
903 );
904 if (!binval) {
905 return luaL_error(L,
906 "Could not allocate memory for binary unescaping."
907 );
908 }
909 lua_pushlstring(L, binval, binlen);
910 PQfreemem(binval);
911 } else {
912 lua_pushstring(L, PQgetvalue(res, row, col));
913 }
914 lua_rawseti(L, 6, col+1);
915 }
916 lua_rawseti(L, 5, row+1);
917 }
918 } else if (rows == 1) {
919 for (col = 0; col < cols; col++) {
920 if (PQgetisnull(res, 0, col)) {
921 lua_pushnil(L);
922 } else if (binary[col]) {
923 size_t binlen;
924 char *binval;
925 binval = (char *)PQunescapeBytea(
926 (unsigned char *)PQgetvalue(res, 0, col), &binlen
927 );
928 if (!binval) {
929 return luaL_error(L,
930 "Could not allocate memory for binary unescaping."
931 );
932 }
933 lua_pushlstring(L, binval, binlen);
934 PQfreemem(binval);
935 } else {
936 lua_pushstring(L, PQgetvalue(res, 0, col));
937 }
938 lua_rawseti(L, 5, col+1);
939 }
940 } else {
941 // no row in optrow mode
942 lua_pop(L, 1);
943 lua_pushnil(L);
944 }
945 lua_rawseti(L, 4, command_idx+1);
946 if (lua_gettop(L) != 4) abort(); // should not happen
947 PQclear(res);
948 }
949 // trace callback at stack position 3
950 // result at stack position 4 (top of stack)
951 if (lua_toboolean(L, 3)) {
952 lua_pushvalue(L, 3);
953 lua_call(L, 0, 0);
954 }
955 lua_replace(L, 3); // result at stack position 3
956 lua_getfield(L, 1, "output_converter"); // output converter at stack position 4
957 for (command_idx = 0; command_idx < command_count; command_idx++) {
958 int mode;
959 mode = modes[command_idx];
960 lua_rawgeti(L, 3, command_idx+1); // raw result at stack position 5
961 if (lua_toboolean(L, 5)) {
962 lua_getfield(L, 5, "_column_info"); // column_info list at position 6
963 cols = lua_objlen(L, 6);
964 if (mode == MONDELEFANT_QUERY_MODE_LIST) {
965 rows = lua_objlen(L, 5);
966 for (row = 0; row < rows; row++) {
967 lua_rawgeti(L, 5, row+1); // row at stack position 7
968 lua_getfield(L, 7, "_data"); // _data table at stack position 8
969 for (col = 0; col < cols; col++) {
970 lua_rawgeti(L, 6, col+1); // this column info at position 9
971 lua_getfield(L, 9, "field_name"); // 10
972 if (lua_toboolean(L, 4)) {
973 lua_pushvalue(L, 4); // output-converter
974 lua_pushvalue(L, 1); // connection
975 lua_rawgeti(L, 7, col+1); // raw-value
976 lua_pushvalue(L, 9); // this column info
977 lua_call(L, 3, 1); // converted value at position 11
978 } else {
979 lua_rawgeti(L, 7, col+1); // raw-value at position 11
980 }
981 lua_pushvalue(L, 11); // 12
982 lua_rawseti(L, 7, col+1);
983 lua_rawset(L, 8);
984 lua_settop(L, 8);
985 }
986 lua_settop(L, 6);
987 }
988 } else {
989 lua_getfield(L, 5, "_data"); // _data table at stack position 7
990 for (col = 0; col < cols; col++) {
991 lua_rawgeti(L, 6, col+1); // this column info at position 8
992 lua_getfield(L, 8, "field_name"); // 9
993 if (lua_toboolean(L, 4)) {
994 lua_pushvalue(L, 4); // output-converter
995 lua_pushvalue(L, 1); // connection
996 lua_rawgeti(L, 5, col+1); // raw-value
997 lua_pushvalue(L, 8); // this column info
998 lua_call(L, 3, 1); // converted value at position 10
999 } else {
1000 lua_rawgeti(L, 5, col+1); // raw-value at position 10
1002 lua_pushvalue(L, 10); // 11
1003 lua_rawseti(L, 5, col+1);
1004 lua_rawset(L, 7);
1005 lua_settop(L, 7);
1009 lua_settop(L, 4);
1011 lua_settop(L, 3);
1012 lua_pushnil(L);
1013 for (command_idx = 0; command_idx < command_count; command_idx++) {
1014 lua_rawgeti(L, 3, command_idx+1);
1016 return command_count+1;
1019 static int mondelefant_errorobject_escalate(lua_State *L) {
1020 lua_settop(L, 1);
1021 lua_getfield(L, 1, "connection"); // 2
1022 lua_getfield(L, 2, "error_objects"); // 3
1023 if (lua_toboolean(L, 3)) {
1024 lua_settop(L, 1);
1025 return lua_error(L);
1026 } else {
1027 lua_getfield(L, 1, "message"); // 4
1028 if (lua_isnil(L, 4)) {
1029 return luaL_error(L, "No error message given for escalation.");
1031 return lua_error(L);
1035 static int mondelefant_errorobject_is_kind_of(lua_State *L) {
1036 lua_settop(L, 2);
1037 lua_getfield(L, 1, "code"); // 3
1038 if (lua_isstring(L, 3)) {
1039 lua_pushboolean(L,
1040 mondelefant_check_error_class(
1041 lua_tostring(L, 3), luaL_checkstring(L, 2)
1043 );
1044 } else {
1045 // only happens for errors where code is not set
1046 lua_pushboolean(L, 0);
1048 return 1;
1051 static int mondelefant_conn_query(lua_State *L) {
1052 int argc;
1053 argc = lua_gettop(L);
1054 lua_pushvalue(L, 1);
1055 lua_insert(L, 1);
1056 lua_pushcfunction(L, mondelefant_conn_try_query);
1057 lua_insert(L, 2);
1058 lua_call(L, argc, LUA_MULTRET); // results (with error) starting at index 2
1059 if (lua_toboolean(L, 2)) {
1060 lua_pushcfunction(L, mondelefant_errorobject_escalate);
1061 lua_pushvalue(L, 2);
1062 lua_call(L, 1, 0); // will raise an error
1063 return 0; // should not be executed
1064 } else {
1065 return lua_gettop(L) - 2;
1069 static int mondelefant_set_class(lua_State *L) {
1070 lua_settop(L, 2);
1071 lua_getmetatable(L, 1); // 3
1072 lua_getfield(L, LUA_REGISTRYINDEX, MONDELEFANT_RESULT_MT_REGKEY); // 4
1073 luaL_argcheck(L, lua_equal(L, 3, 4), 1, "not a database result");
1074 lua_settop(L, 2);
1075 lua_getmetatable(L, 2); // 3
1076 lua_getfield(L, LUA_REGISTRYINDEX, MONDELEFANT_CLASS_MT_REGKEY); // 4
1077 luaL_argcheck(L, lua_equal(L, 3, 4), 2, "not a database class");
1078 lua_settop(L, 2);
1079 lua_pushvalue(L, 2); // 3
1080 lua_setfield(L, 1, "_class");
1081 lua_getfield(L, 1, "_type"); // 3
1082 lua_pushliteral(L, "list"); // 4
1083 if (lua_rawequal(L, 3, 4)) {
1084 int i;
1085 for (i=0; i < lua_objlen(L, 1); i++) {
1086 lua_settop(L, 2);
1087 lua_rawgeti(L, 1, i+1); // 3
1088 lua_pushvalue(L, 2); // 4
1089 lua_setfield(L, 3, "_class");
1092 lua_settop(L, 1);
1093 return 1;
1096 static int mondelefant_new_class(lua_State *L) {
1097 lua_settop(L, 1);
1098 if (!lua_toboolean(L, 1)) {
1099 lua_settop(L, 0);
1100 lua_newtable(L); // 1
1102 lua_getfield(L, LUA_REGISTRYINDEX, MONDELEFANT_CLASS_MT_REGKEY); // 2
1103 lua_setmetatable(L, 1);
1104 lua_pushliteral(L, "prototype"); // 2
1105 lua_rawget(L, 1); // 2
1106 if (!lua_toboolean(L, 2)) {
1107 lua_pushliteral(L, "prototype"); // 3
1108 lua_getfield(L,
1109 LUA_REGISTRYINDEX,
1110 MONDELEFANT_CLASS_PROTO_REGKEY
1111 ); // 4
1112 lua_rawset(L, 1);
1114 lua_settop(L, 1);
1115 lua_pushliteral(L, "object"); // 2
1116 lua_rawget(L, 1); // 2
1117 if (!lua_toboolean(L, 2)) {
1118 lua_pushliteral(L, "object"); // 3
1119 lua_newtable(L); // 4
1120 lua_rawset(L, 1);
1122 lua_settop(L, 1);
1123 lua_pushliteral(L, "object_get"); // 2
1124 lua_rawget(L, 1); // 2
1125 if (!lua_toboolean(L, 2)) {
1126 lua_pushliteral(L, "object_get"); // 3
1127 lua_newtable(L); // 4
1128 lua_rawset(L, 1);
1130 lua_settop(L, 1);
1131 lua_pushliteral(L, "object_set"); // 2
1132 lua_rawget(L, 1); // 2
1133 if (!lua_toboolean(L, 2)) {
1134 lua_pushliteral(L, "object_set"); // 3
1135 lua_newtable(L); // 4
1136 lua_rawset(L, 1);
1138 lua_settop(L, 1);
1139 lua_pushliteral(L, "list"); // 2
1140 lua_rawget(L, 1); // 2
1141 if (!lua_toboolean(L, 2)) {
1142 lua_pushliteral(L, "list"); // 3
1143 lua_newtable(L); // 4
1144 lua_rawset(L, 1);
1146 lua_settop(L, 1);
1147 lua_pushliteral(L, "references"); // 2
1148 lua_rawget(L, 1); // 2
1149 if (!lua_toboolean(L, 2)) {
1150 lua_pushliteral(L, "references"); // 3
1151 lua_newtable(L); // 4
1152 lua_rawset(L, 1);
1154 lua_settop(L, 1);
1155 lua_pushliteral(L, "foreign_keys"); // 2
1156 lua_rawget(L, 1); // 2
1157 if (!lua_toboolean(L, 2)) {
1158 lua_pushliteral(L, "foreign_keys"); // 3
1159 lua_newtable(L); // 4
1160 lua_rawset(L, 1);
1162 lua_settop(L, 1);
1163 return 1;
1166 static int mondelefant_class_get_reference(lua_State *L) {
1167 lua_settop(L, 2);
1168 while (lua_toboolean(L, 1)) {
1169 lua_getfield(L, 1, "references"); // 3
1170 lua_pushvalue(L, 2); // 4
1171 lua_gettable(L, 3); // 4
1172 if (!lua_isnil(L, 4)) return 1;
1173 lua_settop(L, 2);
1174 lua_pushliteral(L, "prototype"); // 3
1175 lua_rawget(L, 1); // 3
1176 lua_replace(L, 1);
1178 return 0;
1181 static int mondelefant_class_iterate_over_references(lua_State *L) {
1182 return luaL_error(L, "Reference iterator not implemented yet."); // TODO
1185 static int mondelefant_class_get_foreign_key_reference_name(lua_State *L) {
1186 lua_settop(L, 2);
1187 while (lua_toboolean(L, 1)) {
1188 lua_getfield(L, 1, "foreign_keys"); // 3
1189 lua_pushvalue(L, 2); // 4
1190 lua_gettable(L, 3); // 4
1191 if (!lua_isnil(L, 4)) return 1;
1192 lua_settop(L, 2);
1193 lua_pushliteral(L, "prototype"); // 3
1194 lua_rawget(L, 1); // 3
1195 lua_replace(L, 1);
1197 return 0;
1200 static int mondelefant_result_index(lua_State *L) {
1201 const char *result_type;
1202 lua_settop(L, 2);
1203 if (lua_type(L, 2) != LUA_TSTRING || lua_tostring(L, 2)[0] == '_') {
1204 lua_rawget(L, 1);
1205 return 1;
1207 lua_getfield(L, 1, "_class"); // 3
1208 if (!lua_toboolean(L, 3)) {
1209 lua_settop(L, 2);
1210 lua_getfield(L,
1211 LUA_REGISTRYINDEX,
1212 MONDELEFANT_CLASS_PROTO_REGKEY
1213 ); // 3
1215 lua_getfield(L, 1, "_type"); // 4
1216 result_type = lua_tostring(L, 4);
1217 if (result_type && !strcmp(result_type, "object")) {
1218 lua_settop(L, 3);
1219 // try inherited attributes, methods or getter functions:
1220 while (lua_toboolean(L, 3)) {
1221 lua_getfield(L, 3, "object"); // 4
1222 lua_pushvalue(L, 2); // 5
1223 lua_gettable(L, 4); // 5
1224 if (!lua_isnil(L, 5)) return 1;
1225 lua_settop(L, 3);
1226 lua_getfield(L, 3, "object_get"); // 4
1227 lua_pushvalue(L, 2); // 5
1228 lua_gettable(L, 4); // 5
1229 if (lua_toboolean(L, 5)) {
1230 lua_pushvalue(L, 1); // 6
1231 lua_call(L, 1, 1); // 5
1232 return 1;
1234 lua_settop(L, 3);
1235 lua_pushliteral(L, "prototype"); // 4
1236 lua_rawget(L, 3); // 4
1237 lua_replace(L, 3);
1239 lua_settop(L, 2);
1240 // try primary keys of referenced objects:
1241 lua_pushcfunction(L,
1242 mondelefant_class_get_foreign_key_reference_name
1243 ); // 3
1244 lua_getfield(L, 1, "_class"); // 4
1245 lua_pushvalue(L, 2); // 5
1246 lua_call(L, 2, 1); // 3
1247 if (!lua_isnil(L, 3)) {
1248 // reference name at stack position 3
1249 lua_pushcfunction(L, mondelefant_class_get_reference); // 4
1250 lua_getfield(L, 1, "_class"); // 5
1251 lua_pushvalue(L, 3); // 6
1252 lua_call(L, 2, 1); // reference info at stack position 4
1253 lua_getfield(L, 1, "_ref"); // 5
1254 lua_getfield(L, 4, "ref"); // 6
1255 lua_gettable(L, 5); // 6
1256 if (!lua_isnil(L, 6)) {
1257 if (lua_toboolean(L, 6)) {
1258 lua_getfield(L, 4, "that_key"); // 7
1259 if (lua_isnil(L, 7)) {
1260 return luaL_error(L, "Missing 'that_key' entry in model reference.");
1262 lua_gettable(L, 6); // 7
1263 } else {
1264 lua_pushnil(L);
1266 return 1;
1269 lua_settop(L, 2);
1270 // try normal data field info:
1271 lua_getfield(L, 1, "_data"); // 3
1272 lua_pushvalue(L, 2); // 4
1273 lua_gettable(L, 3); // 4
1274 if (!lua_isnil(L, 4)) return 1;
1275 lua_settop(L, 2);
1276 // try cached referenced object (or cached NULL reference):
1277 lua_getfield(L, 1, "_ref"); // 3
1278 lua_pushvalue(L, 2); // 4
1279 lua_gettable(L, 3); // 4
1280 if (lua_isboolean(L, 4) && !lua_toboolean(L, 4)) {
1281 lua_pushnil(L);
1282 return 1;
1283 } else if (!lua_isnil(L, 4)) {
1284 return 1;
1286 lua_settop(L, 2);
1287 // try to load a referenced object:
1288 lua_pushcfunction(L, mondelefant_class_get_reference); // 3
1289 lua_getfield(L, 1, "_class"); // 4
1290 lua_pushvalue(L, 2); // 5
1291 lua_call(L, 2, 1); // 3
1292 if (!lua_isnil(L, 3)) {
1293 lua_settop(L, 2);
1294 lua_getfield(L, 1, "load"); // 3
1295 lua_pushvalue(L, 1); // 4 (self)
1296 lua_pushvalue(L, 2); // 5
1297 lua_call(L, 2, 0);
1298 lua_settop(L, 2);
1299 lua_getfield(L, 1, "_ref"); // 3
1300 lua_pushvalue(L, 2); // 4
1301 lua_gettable(L, 3); // 4
1302 if (lua_isboolean(L, 4) && !lua_toboolean(L, 4)) lua_pushnil(L); // TODO: use special object instead of false
1303 return 1;
1305 return 0;
1306 } else if (result_type && !strcmp(result_type, "list")) {
1307 lua_settop(L, 3);
1308 // try inherited list attributes or methods:
1309 while (lua_toboolean(L, 3)) {
1310 lua_getfield(L, 3, "list"); // 4
1311 lua_pushvalue(L, 2); // 5
1312 lua_gettable(L, 4); // 5
1313 if (!lua_isnil(L, 5)) return 1;
1314 lua_settop(L, 3);
1315 lua_pushliteral(L, "prototype"); // 4
1316 lua_rawget(L, 3); // 4
1317 lua_replace(L, 3);
1320 return 0;
1323 static int mondelefant_result_newindex(lua_State *L) {
1324 const char *result_type;
1325 lua_settop(L, 3);
1326 if (lua_type(L, 2) != LUA_TSTRING || lua_tostring(L, 2)[0] == '_') {
1327 lua_rawset(L, 1);
1328 return 1;
1330 lua_getfield(L, 1, "_class"); // 4
1331 if (!lua_toboolean(L, 4)) {
1332 lua_settop(L, 3);
1333 lua_getfield(L,
1334 LUA_REGISTRYINDEX,
1335 MONDELEFANT_CLASS_PROTO_REGKEY
1336 ); // 4
1338 lua_getfield(L, 1, "_type"); // 5
1339 result_type = lua_tostring(L, 5);
1340 if (result_type && !strcmp(result_type, "object")) {
1341 lua_settop(L, 4);
1342 // try object setter functions:
1343 while (lua_toboolean(L, 4)) {
1344 lua_getfield(L, 4, "object_set"); // 5
1345 lua_pushvalue(L, 2); // 6
1346 lua_gettable(L, 5); // 6
1347 if (lua_toboolean(L, 6)) {
1348 lua_pushvalue(L, 1); // 7
1349 lua_pushvalue(L, 3); // 8
1350 lua_call(L, 2, 0);
1351 return 0;
1353 lua_settop(L, 4);
1354 lua_pushliteral(L, "prototype"); // 5
1355 lua_rawget(L, 4); // 5
1356 lua_replace(L, 4);
1358 lua_settop(L, 3);
1359 // check, if a object reference is changed:
1360 lua_pushcfunction(L, mondelefant_class_get_reference); // 4
1361 lua_getfield(L, 1, "_class"); // 5
1362 lua_pushvalue(L, 2); // 6
1363 lua_call(L, 2, 1); // 4
1364 if (!lua_isnil(L, 4)) {
1365 // store object in _ref table (use false for nil): // TODO: use special object instead of false
1366 lua_getfield(L, 1, "_ref"); // 5
1367 lua_pushvalue(L, 2); // 6
1368 if (lua_isnil(L, 3)) lua_pushboolean(L, 0); // 7
1369 else lua_pushvalue(L, 3); // 7
1370 lua_settable(L, 5);
1371 lua_settop(L, 4);
1372 // delete referencing key from _data table:
1373 lua_getfield(L, 4, "this_key"); // 5
1374 if (lua_isnil(L, 5)) {
1375 return luaL_error(L, "Missing 'this_key' entry in model reference.");
1377 lua_getfield(L, 1, "_data"); // 6
1378 lua_pushvalue(L, 5); // 7
1379 lua_pushnil(L); // 8
1380 lua_settable(L, 6);
1381 lua_settop(L, 5);
1382 lua_getfield(L, 1, "_dirty"); // 6
1383 lua_pushvalue(L, 5); // 7
1384 lua_pushboolean(L, 1); // 8
1385 lua_settable(L, 6);
1386 return 0;
1388 lua_settop(L, 3);
1389 // store value in data field info:
1390 lua_getfield(L, 1, "_data"); // 4
1391 lua_pushvalue(L, 2); // 5
1392 lua_pushvalue(L, 3); // 6
1393 lua_settable(L, 4);
1394 lua_settop(L, 3);
1395 // mark field as dirty (needs to be UPDATEd on save):
1396 lua_getfield(L, 1, "_dirty"); // 4
1397 lua_pushvalue(L, 2); // 5
1398 lua_pushboolean(L, 1); // 6
1399 lua_settable(L, 4);
1400 lua_settop(L, 3);
1401 // reset reference cache, if neccessary:
1402 lua_pushcfunction(L,
1403 mondelefant_class_get_foreign_key_reference_name
1404 ); // 4
1405 lua_getfield(L, 1, "_class"); // 5
1406 lua_pushvalue(L, 2); // 6
1407 lua_call(L, 2, 1); // 4
1408 if (!lua_isnil(L, 4)) {
1409 lua_getfield(L, 1, "_ref"); // 5
1410 lua_pushvalue(L, 4); // 6
1411 lua_pushnil(L); // 7
1412 lua_settable(L, 5);
1414 return 0;
1415 } else {
1416 lua_settop(L, 3);
1417 lua_rawset(L, 1);
1418 return 0;
1420 return 0;
1423 static int mondelefant_class_index(lua_State *L) {
1424 lua_settop(L, 2);
1425 lua_pushliteral(L, "prototype"); // 3
1426 lua_rawget(L, 1); // 3
1427 lua_pushvalue(L, 2); // 4
1428 lua_gettable(L, 3); // 4
1429 return 1;
1432 static const struct luaL_Reg mondelefant_module_functions[] = {
1433 {"connect", mondelefant_connect},
1434 {"set_class", mondelefant_set_class},
1435 {"new_class", mondelefant_new_class},
1436 {NULL, NULL}
1437 };
1439 static const struct luaL_Reg mondelefant_conn_mt_functions[] = {
1440 {"__gc", mondelefant_conn_free},
1441 {"__index", mondelefant_conn_index},
1442 {"__newindex", mondelefant_conn_newindex},
1443 {NULL, NULL}
1444 };
1446 static const struct luaL_Reg mondelefant_conn_methods[] = {
1447 {"close", mondelefant_conn_close},
1448 {"is_ok", mondelefant_conn_is_ok},
1449 {"get_transaction_status", mondelefant_conn_get_transaction_status},
1450 {"create_list", mondelefant_conn_create_list},
1451 {"create_object", mondelefant_conn_create_object},
1452 {"quote_string", mondelefant_conn_quote_string},
1453 {"quote_binary", mondelefant_conn_quote_binary},
1454 {"assemble_command", mondelefant_conn_assemble_command},
1455 {"try_query", mondelefant_conn_try_query},
1456 {"query", mondelefant_conn_query},
1457 {NULL, NULL}
1458 };
1460 static const struct luaL_Reg mondelefant_errorobject_mt_functions[] = {
1461 {NULL, NULL}
1462 };
1464 static const struct luaL_Reg mondelefant_errorobject_methods[] = {
1465 {"escalate", mondelefant_errorobject_escalate},
1466 {"is_kind_of", mondelefant_errorobject_is_kind_of},
1467 {NULL, NULL}
1468 };
1470 static const struct luaL_Reg mondelefant_result_mt_functions[] = {
1471 {"__index", mondelefant_result_index},
1472 {"__newindex", mondelefant_result_newindex},
1473 {NULL, NULL}
1474 };
1476 static const struct luaL_Reg mondelefant_class_mt_functions[] = {
1477 {"__index", mondelefant_class_index},
1478 {NULL, NULL}
1479 };
1481 static const struct luaL_Reg mondelefant_class_methods[] = {
1482 {"get_reference", mondelefant_class_get_reference},
1483 {"iterate_over_references", mondelefant_class_iterate_over_references},
1484 {"get_foreign_key_reference_name",
1485 mondelefant_class_get_foreign_key_reference_name},
1486 {NULL, NULL}
1487 };
1489 static const struct luaL_Reg mondelefant_object_methods[] = {
1490 {NULL, NULL}
1491 };
1493 static const struct luaL_Reg mondelefant_list_methods[] = {
1494 {NULL, NULL}
1495 };
1497 int luaopen_mondelefant_native(lua_State *L) {
1498 lua_settop(L, 0);
1499 lua_newtable(L); // module at stack position 1
1500 luaL_register(L, NULL, mondelefant_module_functions);
1502 lua_pushvalue(L, 1); // 2
1503 lua_setfield(L, LUA_REGISTRYINDEX, MONDELEFANT_MODULE_REGKEY);
1505 lua_newtable(L); // 2
1506 // NOTE: only PostgreSQL is supported yet:
1507 luaL_register(L, NULL, mondelefant_conn_methods);
1508 lua_setfield(L, 1, "postgresql_connection_prototype");
1509 lua_newtable(L); // 2
1510 lua_setfield(L, 1, "connection_prototype");
1512 luaL_newmetatable(L, MONDELEFANT_CONN_MT_REGKEY); // 2
1513 luaL_register(L, NULL, mondelefant_conn_mt_functions);
1514 lua_settop(L, 1);
1515 luaL_newmetatable(L, MONDELEFANT_RESULT_MT_REGKEY); // 2
1516 luaL_register(L, NULL, mondelefant_result_mt_functions);
1517 lua_setfield(L, 1, "result_metatable");
1518 luaL_newmetatable(L, MONDELEFANT_CLASS_MT_REGKEY); // 2
1519 luaL_register(L, NULL, mondelefant_class_mt_functions);
1520 lua_setfield(L, 1, "class_metatable");
1522 lua_newtable(L); // 2
1523 lua_newtable(L); // 3
1524 luaL_register(L, NULL, mondelefant_object_methods);
1525 lua_setfield(L, 2, "object");
1526 lua_newtable(L); // 3
1527 lua_setfield(L, 2, "object_get");
1528 lua_newtable(L); // 3
1529 lua_setfield(L, 2, "object_set");
1530 lua_newtable(L); // 3
1531 luaL_register(L, NULL, mondelefant_list_methods);
1532 lua_setfield(L, 2, "list");
1533 lua_newtable(L); // 3
1534 lua_setfield(L, 2, "references");
1535 lua_newtable(L); // 3
1536 lua_setfield(L, 2, "foreign_keys");
1537 lua_pushvalue(L, 2); // 3
1538 lua_setfield(L, LUA_REGISTRYINDEX, MONDELEFANT_CLASS_PROTO_REGKEY);
1539 lua_setfield(L, 1, "class_prototype");
1541 lua_newtable(L); // 2
1542 lua_pushliteral(L, "k"); // 3
1543 lua_setfield(L, 2, "__mode");
1544 lua_newtable(L); // 3
1545 lua_pushvalue(L, 2); // 4
1546 lua_setmetatable(L, 3);
1547 lua_setfield(L, LUA_REGISTRYINDEX, MONDELEFANT_CONN_DATA_REGKEY);
1548 lua_settop(L, 1);
1550 luaL_newmetatable(L, MONDELEFANT_ERROROBJECT_MT_REGKEY); // 2
1551 luaL_register(L, NULL, mondelefant_errorobject_mt_functions);
1552 lua_newtable(L); // 3
1553 luaL_register(L, NULL, mondelefant_errorobject_methods);
1554 lua_setfield(L, 2, "__index");
1555 lua_setfield(L, 1, "errorobject_metatable");
1557 return 1;

Impressum / About Us