]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/c-apps/oils_cstore.c
fix type (pointer * missing); rearange vars to avoid warnings about unused vars
[Evergreen.git] / Open-ILS / src / c-apps / oils_cstore.c
1 #include "opensrf/osrf_application.h"
2 #include "opensrf/osrf_settings.h"
3 #include "opensrf/osrf_message.h"
4 #include "opensrf/utils.h"
5 #include "opensrf/osrf_json.h"
6 #include "opensrf/log.h"
7 #include "openils/oils_utils.h"
8 #include <dbi/dbi.h>
9
10 #include <time.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <unistd.h>
14
15 #ifdef RSTORE
16 #  define MODULENAME "open-ils.reporter-store"
17 #else
18 #  ifdef PCRUD
19 #    define MODULENAME "open-ils.pcrud"
20 #  else
21 #    define MODULENAME "open-ils.cstore"
22 #  endif
23 #endif
24
25 #define SUBSELECT       4
26 #define DISABLE_I18N    2
27 #define SELECT_DISTINCT 1
28 #define AND_OP_JOIN     0
29 #define OR_OP_JOIN      1
30
31 int osrfAppChildInit();
32 int osrfAppInitialize();
33 void osrfAppChildExit();
34
35 static int verifyObjectClass ( osrfMethodContext*, const jsonObject* );
36
37 int beginTransaction ( osrfMethodContext* );
38 int commitTransaction ( osrfMethodContext* );
39 int rollbackTransaction ( osrfMethodContext* );
40
41 int setSavepoint ( osrfMethodContext* );
42 int releaseSavepoint ( osrfMethodContext* );
43 int rollbackSavepoint ( osrfMethodContext* );
44
45 int doJSONSearch ( osrfMethodContext* );
46
47 int dispatchCRUDMethod ( osrfMethodContext* );
48 static jsonObject* doCreate ( osrfMethodContext*, int* );
49 static jsonObject* doRetrieve ( osrfMethodContext*, int* );
50 static jsonObject* doUpdate ( osrfMethodContext*, int* );
51 static jsonObject* doDelete ( osrfMethodContext*, int* );
52 static jsonObject* doFieldmapperSearch ( osrfMethodContext*, osrfHash*,
53         const jsonObject*, int* );
54 static jsonObject* oilsMakeFieldmapperFromResult( dbi_result, osrfHash* );
55 static jsonObject* oilsMakeJSONFromResult( dbi_result );
56
57 static char* searchWriteSimplePredicate ( const char*, osrfHash*,
58         const char*, const char*, const char* );
59 static char* searchSimplePredicate ( const char*, const char*, osrfHash*, const jsonObject* );
60 static char* searchFunctionPredicate ( const char*, osrfHash*, const jsonObject*, const char* );
61 static char* searchFieldTransform ( const char*, osrfHash*, const jsonObject*);
62 static char* searchFieldTransformPredicate ( const char*, osrfHash*, jsonObject*, const char* );
63 static char* searchBETWEENPredicate ( const char*, osrfHash*, jsonObject* );
64 static char* searchINPredicate ( const char*, osrfHash*, const jsonObject*, const char* );
65 static char* searchPredicate ( const char*, osrfHash*, jsonObject* );
66 static char* searchJOIN ( const jsonObject*, osrfHash* );
67 static char* searchWHERE ( const jsonObject*, osrfHash*, int, osrfMethodContext* );
68 static char* buildSELECT ( jsonObject*, jsonObject*, osrfHash*, osrfMethodContext* );
69
70 static char* SELECT ( osrfMethodContext*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, int );
71
72 void userDataFree( void* );
73 static void sessionDataFree( char*, void* );
74 static char* getSourceDefinition( osrfHash* );
75
76 #ifdef PCRUD
77 static jsonObject* verifyUserPCRUD( osrfMethodContext* );
78 static int verifyObjectPCRUD( osrfMethodContext*, const jsonObject* );
79 #endif
80
81 static dbi_conn writehandle; /* our MASTER db connection */
82 static dbi_conn dbhandle; /* our CURRENT db connection */
83 //static osrfHash * readHandles;
84 static jsonObject* jsonNULL = NULL; // 
85 static int max_flesh_depth = 100;
86
87 /* called when this process is about to exit */
88 void osrfAppChildExit() {
89     osrfLogDebug(OSRF_LOG_MARK, "Child is exiting, disconnecting from database...");
90
91     int same = 0;
92     if (writehandle == dbhandle) same = 1;
93     if (writehandle) {
94         dbi_conn_query(writehandle, "ROLLBACK;");
95         dbi_conn_close(writehandle);
96         writehandle = NULL;
97     }
98     if (dbhandle && !same)
99         dbi_conn_close(dbhandle);
100
101     // XXX add cleanup of readHandles whenever that gets used
102
103     return;
104 }
105
106 int osrfAppInitialize() {
107
108     osrfLogInfo(OSRF_LOG_MARK, "Initializing the CStore Server...");
109     osrfLogInfo(OSRF_LOG_MARK, "Finding XML file...");
110
111     if (!oilsIDLInit( osrf_settings_host_value("/IDL") )) return 1; /* return non-zero to indicate error */
112
113     char* method_str = NULL;
114     growing_buffer* method_name = buffer_init(64);
115 #ifndef PCRUD
116     // Generic search thingy
117     buffer_fadd(method_name, "%s.json_query", MODULENAME);
118     method_str = buffer_data(method_name);
119     osrfAppRegisterMethod( MODULENAME, method_str, "doJSONSearch", "", 1, OSRF_METHOD_STREAMING );
120     free(method_str);
121 #endif
122
123     // first we register all the transaction and savepoint methods
124     buffer_reset(method_name);
125     buffer_fadd(method_name, "%s.transaction.begin", MODULENAME);
126     method_str = buffer_data(method_name);
127     osrfAppRegisterMethod( MODULENAME, method_str, "beginTransaction", "", 0, 0 );
128     free(method_str);
129
130     buffer_reset(method_name);
131     buffer_fadd(method_name, "%s.transaction.commit", MODULENAME);
132     method_str = buffer_data(method_name);
133     osrfAppRegisterMethod( MODULENAME, method_str, "commitTransaction", "", 0, 0 );
134     free(method_str);
135
136     buffer_reset(method_name);
137     buffer_fadd(method_name, "%s.transaction.rollback", MODULENAME);
138     method_str = buffer_data(method_name);
139     osrfAppRegisterMethod( MODULENAME, method_str, "rollbackTransaction", "", 0, 0 );
140     free(method_str);
141
142     buffer_reset(method_name);
143     buffer_fadd(method_name, "%s.savepoint.set", MODULENAME);
144     method_str = buffer_data(method_name);
145     osrfAppRegisterMethod( MODULENAME, method_str, "setSavepoint", "", 1, 0 );
146     free(method_str);
147
148     buffer_reset(method_name);
149     buffer_fadd(method_name, "%s.savepoint.release", MODULENAME);
150     method_str = buffer_data(method_name);
151     osrfAppRegisterMethod( MODULENAME, method_str, "releaseSavepoint", "", 1, 0 );
152     free(method_str);
153
154     buffer_reset(method_name);
155     buffer_fadd(method_name, "%s.savepoint.rollback", MODULENAME);
156     method_str = buffer_data(method_name);
157     osrfAppRegisterMethod( MODULENAME, method_str, "rollbackSavepoint", "", 1, 0 );
158     free(method_str);
159
160     buffer_free(method_name);
161
162     osrfStringArray* global_methods = osrfNewStringArray(6);
163
164     osrfStringArrayAdd( global_methods, "create" );
165     osrfStringArrayAdd( global_methods, "retrieve" );
166     osrfStringArrayAdd( global_methods, "update" );
167     osrfStringArrayAdd( global_methods, "delete" );
168     osrfStringArrayAdd( global_methods, "search" );
169     osrfStringArrayAdd( global_methods, "id_list" );
170
171     int c_index = 0; 
172     char* classname;
173     osrfStringArray* classes = osrfHashKeys( oilsIDL() );
174     osrfLogDebug(OSRF_LOG_MARK, "%d classes loaded", classes->size );
175     osrfLogDebug(OSRF_LOG_MARK, "At least %d methods will be generated", classes->size * global_methods->size);
176
177     while ( (classname = osrfStringArrayGetString(classes, c_index++)) ) {
178         osrfLogInfo(OSRF_LOG_MARK, "Generating class methods for %s", classname);
179
180         osrfHash* idlClass = osrfHashGet(oilsIDL(), classname);
181
182         if (!osrfStringArrayContains( osrfHashGet(idlClass, "controller"), MODULENAME )) {
183             osrfLogInfo(OSRF_LOG_MARK, "%s is not listed as a controller for %s, moving on", MODULENAME, classname);
184             continue;
185         }
186
187         char* virt = osrfHashGet(idlClass, "virtual");
188         if (virt && !strcmp( virt, "true")) {
189             osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
190             continue;
191         }
192
193         int i = 0; 
194         char* method_type;
195         osrfHash* method_meta;
196         while ( (method_type = osrfStringArrayGetString(global_methods, i++)) ) {
197             osrfLogDebug(OSRF_LOG_MARK, "Using files to build %s class methods for %s", method_type, classname);
198
199             if (!osrfHashGet(idlClass, "fieldmapper")) continue;
200
201 #ifdef PCRUD
202             if (!osrfHashGet(idlClass, "permacrud")) continue;
203
204             char* tmp_method = strdup(method_type);
205             if ( *tmp_method == 'i' || *tmp_method == 's') {
206                 free(tmp_method);
207                 tmp_method = strdup("retrieve");
208             }
209             if (!osrfHashGet( osrfHashGet(idlClass, "permacrud"), tmp_method )) continue;
210             free(tmp_method);
211 #endif
212
213             char* readonly = osrfHashGet(idlClass, "readonly");
214             if (        readonly &&
215                     !strncasecmp( "true", readonly, 4) &&
216                     ( *method_type == 'c' || *method_type == 'u' || *method_type == 'd')
217                ) continue;
218
219             method_meta = osrfNewHash();
220             osrfHashSet(method_meta, idlClass, "class");
221
222             method_name =  buffer_init(64);
223 #ifdef PCRUD
224             buffer_fadd(method_name, "%s.%s.%s", MODULENAME, method_type, classname);
225 #else
226             char* st_tmp = NULL;
227             char* part = NULL;
228             char* _fm = strdup( (char*)osrfHashGet(idlClass, "fieldmapper") );
229             part = strtok_r(_fm, ":", &st_tmp);
230
231             buffer_fadd(method_name, "%s.direct.%s", MODULENAME, part);
232
233             while ((part = strtok_r(NULL, ":", &st_tmp))) {
234                 buffer_fadd(method_name, ".%s", part);
235             }
236             buffer_fadd(method_name, ".%s", method_type);
237             free(_fm);
238 #endif
239
240             char* method = buffer_release(method_name);
241
242             osrfHashSet( method_meta, method, "methodname" );
243             osrfHashSet( method_meta, strdup(method_type), "methodtype" );
244
245             int flags = 0;
246             if (*method_type == 'i' || *method_type == 's') {
247                 flags = flags | OSRF_METHOD_STREAMING;
248             }
249
250             osrfAppRegisterExtendedMethod(
251                     MODULENAME,
252                     method,
253                     "dispatchCRUDMethod",
254                     "",
255                     1,
256                     flags,
257                     (void*)method_meta
258                     );
259
260             free(method);
261         }
262     }
263
264     osrfStringArrayFree( global_methods );
265     return 0;
266 }
267
268 static char* getSourceDefinition( osrfHash* class ) {
269
270     char* tabledef = osrfHashGet(class, "tablename");
271
272     if (!tabledef) {
273         growing_buffer* tablebuf = buffer_init(128);
274         tabledef = osrfHashGet(class, "source_definition");
275         if( !tabledef )
276             tabledef = "(null)";
277         buffer_fadd( tablebuf, "(%s)", tabledef );
278         tabledef = buffer_release(tablebuf);
279     } else {
280         tabledef = strdup(tabledef);
281     }
282
283     return tabledef;
284 }
285
286 /**
287  * Connects to the database 
288  */
289 int osrfAppChildInit() {
290
291     osrfLogDebug(OSRF_LOG_MARK, "Attempting to initialize libdbi...");
292     dbi_initialize(NULL);
293     osrfLogDebug(OSRF_LOG_MARK, "... libdbi initialized.");
294
295     char* driver        = osrf_settings_host_value("/apps/%s/app_settings/driver", MODULENAME);
296     char* user  = osrf_settings_host_value("/apps/%s/app_settings/database/user", MODULENAME);
297     char* host  = osrf_settings_host_value("/apps/%s/app_settings/database/host", MODULENAME);
298     char* port  = osrf_settings_host_value("/apps/%s/app_settings/database/port", MODULENAME);
299     char* db    = osrf_settings_host_value("/apps/%s/app_settings/database/db", MODULENAME);
300     char* pw    = osrf_settings_host_value("/apps/%s/app_settings/database/pw", MODULENAME);
301     char* md    = osrf_settings_host_value("/apps/%s/app_settings/max_query_recursion", MODULENAME);
302
303     osrfLogDebug(OSRF_LOG_MARK, "Attempting to load the database driver [%s]...", driver);
304     writehandle = dbi_conn_new(driver);
305
306     if(!writehandle) {
307         osrfLogError(OSRF_LOG_MARK, "Error loading database driver [%s]", driver);
308         return -1;
309     }
310     osrfLogDebug(OSRF_LOG_MARK, "Database driver [%s] seems OK", driver);
311
312     osrfLogInfo(OSRF_LOG_MARK, "%s connecting to database.  host=%s, "
313             "port=%s, user=%s, pw=%s, db=%s", MODULENAME, host, port, user, pw, db );
314
315     if(host) dbi_conn_set_option(writehandle, "host", host );
316     if(port) dbi_conn_set_option_numeric( writehandle, "port", atoi(port) );
317     if(user) dbi_conn_set_option(writehandle, "username", user);
318     if(pw) dbi_conn_set_option(writehandle, "password", pw );
319     if(db) dbi_conn_set_option(writehandle, "dbname", db );
320
321     if(md) max_flesh_depth = atoi(md);
322     if(max_flesh_depth < 0) max_flesh_depth = 1;
323     if(max_flesh_depth > 1000) max_flesh_depth = 1000;
324
325     free(user);
326     free(host);
327     free(port);
328     free(db);
329     free(pw);
330
331     const char* err;
332     if (dbi_conn_connect(writehandle) < 0) {
333         sleep(1);
334         if (dbi_conn_connect(writehandle) < 0) {
335             dbi_conn_error(writehandle, &err);
336             osrfLogError( OSRF_LOG_MARK, "Error connecting to database: %s", err);
337             return -1;
338         }
339     }
340
341     osrfLogInfo(OSRF_LOG_MARK, "%s successfully connected to the database", MODULENAME);
342
343     int attr;
344     unsigned short type;
345     int i = 0; 
346     char* classname;
347     osrfStringArray* classes = osrfHashKeys( oilsIDL() );
348
349     while ( (classname = osrfStringArrayGetString(classes, i++)) ) {
350         osrfHash* class = osrfHashGet( oilsIDL(), classname );
351         osrfHash* fields = osrfHashGet( class, "fields" );
352
353         char* virt = osrfHashGet(class, "virtual");
354         if (virt && !strcmp( virt, "true")) {
355             osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
356             continue;
357         }
358
359         char* tabledef = getSourceDefinition(class);
360
361         growing_buffer* sql_buf = buffer_init(32);
362         buffer_fadd( sql_buf, "SELECT * FROM %s AS x WHERE 1=0;", tabledef );
363
364         free(tabledef);
365
366         char* sql = buffer_release(sql_buf);
367         osrfLogDebug(OSRF_LOG_MARK, "%s Investigatory SQL = %s", MODULENAME, sql);
368
369         dbi_result result = dbi_conn_query(writehandle, sql);
370         free(sql);
371
372         if (result) {
373
374             int columnIndex = 1;
375             const char* columnName;
376             osrfHash* _f;
377             while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
378
379                 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
380
381                 /* fetch the fieldmapper index */
382                 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
383
384                     osrfLogDebug(OSRF_LOG_MARK, "Found [%s] in IDL hash...", (char*)columnName);
385
386                     /* determine the field type and storage attributes */
387                     type = dbi_result_get_field_type(result, columnName);
388                     attr = dbi_result_get_field_attribs(result, columnName);
389
390                     switch( type ) {
391
392                         case DBI_TYPE_INTEGER :
393
394                             if ( !osrfHashGet(_f, "primitive") )
395                                 osrfHashSet(_f,"number", "primitive");
396
397                             if( attr & DBI_INTEGER_SIZE8 ) 
398                                 osrfHashSet(_f,"INT8", "datatype");
399                             else 
400                                 osrfHashSet(_f,"INT", "datatype");
401                             break;
402
403                         case DBI_TYPE_DECIMAL :
404                             if ( !osrfHashGet(_f, "primitive") )
405                                 osrfHashSet(_f,"number", "primitive");
406
407                             osrfHashSet(_f,"NUMERIC", "datatype");
408                             break;
409
410                         case DBI_TYPE_STRING :
411                             if ( !osrfHashGet(_f, "primitive") )
412                                 osrfHashSet(_f,"string", "primitive");
413                             osrfHashSet(_f,"TEXT", "datatype");
414                             break;
415
416                         case DBI_TYPE_DATETIME :
417                             if ( !osrfHashGet(_f, "primitive") )
418                                 osrfHashSet(_f,"string", "primitive");
419
420                             osrfHashSet(_f,"TIMESTAMP", "datatype");
421                             break;
422
423                         case DBI_TYPE_BINARY :
424                             if ( !osrfHashGet(_f, "primitive") )
425                                 osrfHashSet(_f,"string", "primitive");
426
427                             osrfHashSet(_f,"BYTEA", "datatype");
428                     }
429
430                     osrfLogDebug(
431                             OSRF_LOG_MARK,
432                             "Setting [%s] to primitive [%s] and datatype [%s]...",
433                             (char*)columnName,
434                             osrfHashGet(_f, "primitive"),
435                             osrfHashGet(_f, "datatype")
436                             );
437                 }
438             }
439             dbi_result_free(result);
440         } else {
441             osrfLogDebug(OSRF_LOG_MARK, "No data found for class [%s]...", (char*)classname);
442         }
443     }
444
445     osrfStringArrayFree(classes);
446
447     return 0;
448 }
449
450 void userDataFree( void* blob ) {
451     osrfHashFree( (osrfHash*)blob );
452     return;
453 }
454
455 static void sessionDataFree( char* key, void* item ) {
456     if (!(strcmp(key,"xact_id"))) {
457         if (writehandle)
458             dbi_conn_query(writehandle, "ROLLBACK;");
459         free(item);
460     }
461
462     return;
463 }
464
465 int beginTransaction ( osrfMethodContext* ctx ) {
466     OSRF_METHOD_VERIFY_CONTEXT(ctx);
467
468 #ifdef PRCRUD
469     jsonObject* user = verifyUserPCRUD( ctx );
470     if (!user) {
471         jsonObjectFree(user);
472         return -1;
473     }
474     jsonObjectFree(user);
475 #endif
476
477     dbi_result result = dbi_conn_query(writehandle, "START TRANSACTION;");
478     if (!result) {
479         osrfLogError(OSRF_LOG_MARK, "%s: Error starting transaction", MODULENAME );
480         osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error starting transaction" );
481         return -1;
482     } else {
483         jsonObject* ret = jsonNewObject(ctx->session->session_id);
484         osrfAppRespondComplete( ctx, ret );
485         jsonObjectFree(ret);
486
487         if (!ctx->session->userData) {
488             ctx->session->userData = osrfNewHash();
489             osrfHashSetCallback((osrfHash*)ctx->session->userData, &sessionDataFree);
490         }
491
492         osrfHashSet( (osrfHash*)ctx->session->userData, strdup( ctx->session->session_id ), "xact_id" );
493         ctx->session->userDataFree = &userDataFree;
494
495     }
496     return 0;
497 }
498
499 int setSavepoint ( osrfMethodContext* ctx ) {
500     OSRF_METHOD_VERIFY_CONTEXT(ctx);
501
502     int spNamePos = 0;
503 #ifdef PRCRUD
504     spNamePos = 1;
505     jsonObject* user = verifyUserPCRUD( ctx );
506     if (!user) {
507         jsonObjectFree(user);
508         return -1;
509     }
510     jsonObjectFree(user);
511 #endif
512
513     if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
514         osrfAppSessionStatus(
515                 ctx->session,
516                 OSRF_STATUS_INTERNALSERVERERROR,
517                 "osrfMethodException",
518                 ctx->request,
519                 "No active transaction -- required for savepoints"
520                 );
521         return -1;
522     }
523
524     char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
525
526     dbi_result result = dbi_conn_queryf(writehandle, "SAVEPOINT \"%s\";", spName);
527     if (!result) {
528         osrfLogError(
529                 OSRF_LOG_MARK,
530                 "%s: Error creating savepoint %s in transaction %s",
531                 MODULENAME,
532                 spName,
533                 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
534                 );
535         osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error creating savepoint" );
536         free(spName);
537         return -1;
538     } else {
539         jsonObject* ret = jsonNewObject(spName);
540         osrfAppRespondComplete( ctx, ret );
541         jsonObjectFree(ret);
542     }
543     free(spName);
544     return 0;
545 }
546
547 int releaseSavepoint ( osrfMethodContext* ctx ) {
548     OSRF_METHOD_VERIFY_CONTEXT(ctx);
549
550     int spNamePos = 0;
551 #ifdef PRCRUD
552     spNamePos = 1;
553     jsonObject* user = verifyUserPCRUD( ctx );
554     if (!user) {
555         jsonObjectFree(user);
556         return -1;
557     }
558     jsonObjectFree(user);
559 #endif
560
561     if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
562         osrfAppSessionStatus(
563                 ctx->session,
564                 OSRF_STATUS_INTERNALSERVERERROR,
565                 "osrfMethodException",
566                 ctx->request,
567                 "No active transaction -- required for savepoints"
568                 );
569         return -1;
570     }
571
572     char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
573
574     dbi_result result = dbi_conn_queryf(writehandle, "RELEASE SAVEPOINT \"%s\";", spName);
575     if (!result) {
576         osrfLogError(
577                 OSRF_LOG_MARK,
578                 "%s: Error releasing savepoint %s in transaction %s",
579                 MODULENAME,
580                 spName,
581                 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
582                 );
583         osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error releasing savepoint" );
584         free(spName);
585         return -1;
586     } else {
587         jsonObject* ret = jsonNewObject(spName);
588         osrfAppRespondComplete( ctx, ret );
589         jsonObjectFree(ret);
590     }
591     free(spName);
592     return 0;
593 }
594
595 int rollbackSavepoint ( osrfMethodContext* ctx ) {
596     OSRF_METHOD_VERIFY_CONTEXT(ctx);
597
598     int spNamePos = 0;
599 #ifdef PRCRUD
600     spNamePos = 1;
601     jsonObject* user = verifyUserPCRUD( ctx );
602     if (!user) {
603         jsonObjectFree(user);
604         return -1;
605     }
606     jsonObjectFree(user);
607 #endif
608
609     if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
610         osrfAppSessionStatus(
611                 ctx->session,
612                 OSRF_STATUS_INTERNALSERVERERROR,
613                 "osrfMethodException",
614                 ctx->request,
615                 "No active transaction -- required for savepoints"
616                 );
617         return -1;
618     }
619
620     char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
621
622     dbi_result result = dbi_conn_queryf(writehandle, "ROLLBACK TO SAVEPOINT \"%s\";", spName);
623     if (!result) {
624         osrfLogError(
625                 OSRF_LOG_MARK,
626                 "%s: Error rolling back savepoint %s in transaction %s",
627                 MODULENAME,
628                 spName,
629                 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
630                 );
631         osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back savepoint" );
632         free(spName);
633         return -1;
634     } else {
635         jsonObject* ret = jsonNewObject(spName);
636         osrfAppRespondComplete( ctx, ret );
637         jsonObjectFree(ret);
638     }
639     free(spName);
640     return 0;
641 }
642
643 int commitTransaction ( osrfMethodContext* ctx ) {
644     OSRF_METHOD_VERIFY_CONTEXT(ctx);
645
646 #ifdef PRCRUD
647     jsonObject* user = verifyUserPCRUD( ctx );
648     if (!user) {
649         jsonObjectFree(user);
650         return -1;
651     }
652     jsonObjectFree(user);
653 #endif
654
655     if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
656         osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to commit" );
657         return -1;
658     }
659
660     dbi_result result = dbi_conn_query(writehandle, "COMMIT;");
661     if (!result) {
662         osrfLogError(OSRF_LOG_MARK, "%s: Error committing transaction", MODULENAME );
663         osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error committing transaction" );
664         return -1;
665     } else {
666         osrfHashRemove(ctx->session->userData, "xact_id");
667         jsonObject* ret = jsonNewObject(ctx->session->session_id);
668         osrfAppRespondComplete( ctx, ret );
669         jsonObjectFree(ret);
670     }
671     return 0;
672 }
673
674 int rollbackTransaction ( osrfMethodContext* ctx ) {
675     OSRF_METHOD_VERIFY_CONTEXT(ctx);
676
677 #ifdef PRCRUD
678     jsonObject* user = verifyUserPCRUD( ctx );
679     if (!user) {
680         jsonObjectFree(user);
681         return -1;
682     }
683     jsonObjectFree(user);
684 #endif
685
686     if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
687         osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to roll back" );
688         return -1;
689     }
690
691     dbi_result result = dbi_conn_query(writehandle, "ROLLBACK;");
692     if (!result) {
693         osrfLogError(OSRF_LOG_MARK, "%s: Error rolling back transaction", MODULENAME );
694         osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back transaction" );
695         return -1;
696     } else {
697         osrfHashRemove(ctx->session->userData, "xact_id");
698         jsonObject* ret = jsonNewObject(ctx->session->session_id);
699         osrfAppRespondComplete( ctx, ret );
700         jsonObjectFree(ret);
701     }
702     return 0;
703 }
704
705 int dispatchCRUDMethod ( osrfMethodContext* ctx ) {
706     OSRF_METHOD_VERIFY_CONTEXT(ctx);
707
708     osrfHash* meta = (osrfHash*) ctx->method->userData;
709     osrfHash* class_obj = osrfHashGet( meta, "class" );
710
711     int err = 0;
712
713     const char* methodtype = osrfHashGet(meta, "methodtype");
714     jsonObject * obj = NULL;
715
716     if (!strcmp(methodtype, "create")) {
717         obj = doCreate(ctx, &err);
718         osrfAppRespondComplete( ctx, obj );
719     }
720     else if (!strcmp(methodtype, "retrieve")) {
721         obj = doRetrieve(ctx, &err);
722         osrfAppRespondComplete( ctx, obj );
723     }
724     else if (!strcmp(methodtype, "update")) {
725         obj = doUpdate(ctx, &err);
726         osrfAppRespondComplete( ctx, obj );
727     }
728     else if (!strcmp(methodtype, "delete")) {
729         obj = doDelete(ctx, &err);
730         osrfAppRespondComplete( ctx, obj );
731     }
732     else if (!strcmp(methodtype, "search")) {
733
734         jsonObject* _p = jsonObjectClone( ctx->params );
735 #ifdef PCRUD
736         jsonObjectFree(_p);
737         _p = jsonParseString("[]");
738         jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 1)));
739         jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 2)));
740 #endif
741
742         obj = doFieldmapperSearch(ctx, class_obj, _p, &err);
743
744         jsonObjectFree(_p);
745         if(err) return err;
746
747         jsonObject* cur;
748         jsonIterator* itr = jsonNewIterator( obj );
749         while ((cur = jsonIteratorNext( itr ))) {
750 #ifdef PCRUD
751             if(!verifyObjectPCRUD(ctx, cur)) continue;
752 #endif
753             osrfAppRespond( ctx, cur );
754         }
755         jsonIteratorFree(itr);
756         osrfAppRespondComplete( ctx, NULL );
757
758     } else if (!strcmp(methodtype, "id_list")) {
759
760         jsonObject* _p = jsonObjectClone( ctx->params );
761 #ifdef PCRUD
762         jsonObjectFree(_p);
763         _p = jsonParseString("[]");
764         jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 1)));
765         jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 2)));
766 #endif
767
768         if (jsonObjectGetIndex( _p, 1 )) {
769             jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh" );
770             jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh_columns" );
771         } else {
772             jsonObjectSetIndex( _p, 1, jsonNewObjectType(JSON_HASH) );
773         }
774
775         growing_buffer* sel_list = buffer_init(64);
776         buffer_fadd(sel_list, "{ \"%s\":[\"%s\"] }", osrfHashGet( class_obj, "classname" ), osrfHashGet( class_obj, "primarykey" ));
777         char* _s = buffer_release(sel_list);
778
779         jsonObjectSetKey( jsonObjectGetIndex( _p, 1 ), "select", jsonParseString(_s) );
780         osrfLogDebug(OSRF_LOG_MARK, "%s: Select qualifer set to [%s]", MODULENAME, _s);
781         free(_s);
782
783         obj = doFieldmapperSearch(ctx, class_obj, _p, &err);
784
785         jsonObjectFree(_p);
786         if(err) return err;
787
788         jsonObject* cur;
789         jsonIterator* itr = jsonNewIterator( obj );
790         while ((cur = jsonIteratorNext( itr ))) {
791 #ifdef PCRUD
792             if(!verifyObjectPCRUD(ctx, cur)) continue;
793 #endif
794             osrfAppRespond(
795                     ctx,
796                     oilsFMGetObject( cur, osrfHashGet( class_obj, "primarykey" ) )
797                     );
798         }
799         jsonIteratorFree(itr);
800         osrfAppRespondComplete( ctx, NULL );
801
802     } else {
803         osrfAppRespondComplete( ctx, obj );
804     }
805
806     jsonObjectFree(obj);
807
808     return err;
809 }
810
811 static int verifyObjectClass ( osrfMethodContext* ctx, const jsonObject* param ) {
812
813     int ret = 1;
814     osrfHash* meta = (osrfHash*) ctx->method->userData;
815     osrfHash* class = osrfHashGet( meta, "class" );
816
817     if (!param->classname || (strcmp( osrfHashGet(class, "classname"), param->classname ))) {
818
819         growing_buffer* msg = buffer_init(128);
820         buffer_fadd(
821                 msg,
822                 "%s: %s method for type %s was passed a %s",
823                 MODULENAME,
824                 osrfHashGet(meta, "methodtype"),
825                 osrfHashGet(class, "classname"),
826                 param->classname
827                 );
828
829         char* m = buffer_release(msg);
830         osrfAppSessionStatus( ctx->session, OSRF_STATUS_BADREQUEST, "osrfMethodException", ctx->request, m );
831
832         free(m);
833
834         return 0;
835     }
836
837 #ifdef PCRUD
838     ret = verifyObjectPCRUD( ctx, param );
839 #endif
840
841     return ret;
842 }
843
844 #ifdef PCRUD
845
846 static jsonObject* verifyUserPCRUD( osrfMethodContext* ctx ) {
847     char* auth = jsonObjectToSimpleString( jsonObjectGetIndex( ctx->params, 0 ) );
848     jsonObject* auth_object = jsonNewObject(auth);
849     jsonObject* user = oilsUtilsQuickReq("open-ils.auth","open-ils.auth.session.retrieve", auth_object);
850     jsonObjectFree(auth_object);
851
852     if (!user->classname || strcmp(user->classname, "au")) {
853
854         growing_buffer* msg = buffer_init(128);
855         buffer_fadd(
856             msg,
857             "%s: permacrud received a bad auth token: %s",
858             MODULENAME,
859             auth
860         );
861
862         char* m = buffer_release(msg);
863         osrfAppSessionStatus( ctx->session, OSRF_STATUS_BADREQUEST, "osrfMethodException", ctx->request, m );
864
865         free(m);
866         free(auth);
867
868         return jsonNULL;
869     }
870
871     return user;
872
873 }
874
875 static int verifyObjectPCRUD (  osrfMethodContext* ctx, const jsonObject* obj ) {
876
877     dbhandle = writehandle;
878
879     osrfHash* meta = (osrfHash*) ctx->method->userData;
880     osrfHash* class = osrfHashGet( meta, "class" );
881     char* method_type = strdup( osrfHashGet(meta, "methodtype") );
882
883     if ( ( *method_type == 's' || *method_type == 'i' ) ) {
884         free(method_type);
885         method_type = strdup("retrieve");
886     }
887
888     osrfHash* pcrud = osrfHashGet( osrfHashGet(class, "permacrud"), method_type );
889     free(method_type);
890
891     if (!pcrud) {
892         // No permacrud for this method type on this class
893
894         growing_buffer* msg = buffer_init(128);
895         buffer_fadd(
896             msg,
897             "%s: %s on class %s has no permacrud IDL entry",
898             MODULENAME,
899             osrfHashGet(meta, "methodtype"),
900             osrfHashGet(class, "classname")
901         );
902
903         char* m = buffer_release(msg);
904         osrfAppSessionStatus( ctx->session, OSRF_STATUS_BADREQUEST, "osrfMethodException", ctx->request, m );
905
906         free(m);
907
908         return 0;
909     }
910
911     jsonObject* user = verifyUserPCRUD( ctx );
912     if (!user) return 0;
913
914     int userid = atoi( oilsFMGetString( user, "id" ) );
915     jsonObjectFree(user);
916
917     osrfStringArray* permission = osrfHashGet(pcrud, "permission");
918     char* global_required = osrfHashGet(pcrud, "global_required");
919     osrfStringArray* local_context = osrfHashGet(pcrud, "local_context");
920     osrfHash* foreign_context = osrfHashGet(pcrud, "foreign_context");
921
922     osrfStringArray* context_org_array = osrfNewStringArray(1);
923
924     char* pkey_value = NULL;
925     int err = 0;
926     if (global_required && !strcmp( "true", global_required )) {
927             osrfLogDebug( OSRF_LOG_MARK, "global-level permissions required, fetching top of the org tree" );
928
929         // check for perm at top of org tree
930         jsonObject* _tmp_params = jsonParseString("[{\"parent_ou\":null}]");
931                 jsonObject* _list = doFieldmapperSearch(ctx, osrfHashGet( oilsIDL(), "aou" ), _tmp_params, &err);
932
933         jsonObject* _tree_top = jsonObjectGetIndex(_list, 0);
934
935         if (!_tree_top) {
936             jsonObjectFree(_tmp_params);
937             jsonObjectFree(_list);
938     
939             growing_buffer* msg = buffer_init(128);
940             buffer_fadd(
941                 msg,
942                 "%s: Internal error, could not find the top of the org tree (parent_ou = NULL)",
943                 MODULENAME
944             );
945     
946             char* m = buffer_release(msg);
947             osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, m );
948             free(m);
949
950             return 0;
951         }
952
953         osrfStringArrayAdd( context_org_array, oilsFMGetString( _tree_top, "id" ) );
954             osrfLogDebug( OSRF_LOG_MARK, "top of the org tree is %s", osrfStringArrayGetString(context_org_array, 0) );
955
956         jsonObjectFree(_tmp_params);
957         jsonObjectFree(_list);
958
959     } else {
960             osrfLogDebug( OSRF_LOG_MARK, "global-level permissions not required, fetching context org ids" );
961
962         jsonObject *param = NULL;
963         if (obj) param = jsonObjectClone(obj);
964             if (!param) param = jsonObjectClone(jsonObjectGetIndex( ctx->params, 1 ));
965
966        // XXX if the object has a non-null pkey, check for object-specific perm,
967        // else context org(s) for group perm check
968             char* pkey = osrfHashGet(class, "primarykey");
969
970         if (param->classname) {
971             pkey_value = oilsFMGetString( param, pkey );
972                 osrfLogDebug( OSRF_LOG_MARK, "Object supplied, using primary key value of %s", pkey_value );
973
974         } else {
975             pkey_value = jsonObjectToSimpleString( param );
976                 osrfLogDebug( OSRF_LOG_MARK, "Object not supplied, using primary key value of %s and retrieving from the database", pkey_value );
977
978             jsonObject* _tmp_params = jsonParseStringFmt("[{\"%s\":\"%s\"}]", pkey, pkey_value);
979                 jsonObject* _list = doFieldmapperSearch(
980                 ctx,
981                 class,
982                 _tmp_params,
983                 &err
984             );
985     
986             jsonObjectFree(param);
987             param = jsonObjectClone(jsonObjectGetIndex(_list, 0));
988     
989             if (!param) {
990                     osrfLogDebug( OSRF_LOG_MARK, "Object not found in the database with primary key %s of %s", pkey, pkey_value );
991                 jsonObjectFree(_tmp_params);
992                 jsonObjectFree(_list);
993
994                 growing_buffer* msg = buffer_init(128);
995                 buffer_fadd(
996                     msg,
997                     "%s: no object found with primary key %s of %s",
998                     MODULENAME,
999                     pkey,
1000                     pkey_value
1001                 );
1002         
1003                 char* m = buffer_release(msg);
1004                 osrfAppSessionStatus( ctx->session, OSRF_STATUS_BADREQUEST, "osrfMethodException", ctx->request, m );
1005         
1006                 free(m);
1007                 free(pkey_value);
1008
1009                 return 0;
1010             }
1011
1012             free(pkey_value);
1013             jsonObjectFree(_tmp_params);
1014             jsonObjectFree(_list);
1015
1016         }
1017
1018         if (local_context->size > 0) {
1019                 osrfLogDebug( OSRF_LOG_MARK, "%d class-local context field(s) specified", local_context->size);
1020             int i = 0;
1021             char* lcontext = NULL;
1022             while ( (lcontext = osrfStringArrayGetString(local_context, i++)) ) {
1023                 osrfStringArrayAdd( context_org_array, oilsFMGetString( param, lcontext ) );
1024                     osrfLogDebug( OSRF_LOG_MARK, "adding class-local field %s (value: %s) to the context org list", lcontext, osrfStringArrayGetString(context_org_array, context_org_array->size - 1) );
1025             }
1026         }
1027
1028         osrfStringArray* class_list;
1029
1030         if (foreign_context) {
1031             class_list = osrfHashKeys( foreign_context );
1032                 osrfLogDebug( OSRF_LOG_MARK, "%d foreign context classes(s) specified", class_list->size);
1033
1034             if (class_list->size > 0) {
1035     
1036                 int i = 0;
1037                 char* class_name = NULL;
1038                 while ( (class_name = osrfStringArrayGetString(class_list, i++)) ) {
1039                     osrfHash* fcontext = osrfHashGet(foreign_context, class_name);
1040
1041                         osrfLogDebug( OSRF_LOG_MARK, "%d foreign context fields(s) specified for class %s", ((osrfStringArray*)osrfHashGet(fcontext,"context"))->size, class_name);
1042     
1043                     char* foreign_pkey = osrfHashGet(fcontext, "field");
1044                     char* foreign_pkey_value = oilsFMGetString(param, osrfHashGet(fcontext, "fkey"));
1045
1046                     jsonObject* _tmp_params = jsonParseStringFmt(
1047                         "[{\"%s\":\"%s\"}]",
1048                         foreign_pkey,
1049                         foreign_pkey_value
1050                     );
1051     
1052                         jsonObject* _list = doFieldmapperSearch(
1053                         ctx,
1054                         osrfHashGet( oilsIDL(), class_name ),
1055                         _tmp_params,
1056                         &err
1057                     );
1058
1059                     jsonObject* _fparam = jsonObjectGetIndex(_list, 0);
1060             
1061                     if (!_fparam) {
1062                         jsonObjectFree(_tmp_params);
1063                         jsonObjectFree(_list);
1064
1065                         growing_buffer* msg = buffer_init(128);
1066                         buffer_fadd(
1067                             msg,
1068                             "%s: no object found with primary key %s of %s",
1069                             MODULENAME,
1070                             foreign_pkey,
1071                             foreign_pkey_value
1072                         );
1073                 
1074                         char* m = buffer_release(msg);
1075                         osrfAppSessionStatus( ctx->session, OSRF_STATUS_BADREQUEST, "osrfMethodException", ctx->request, m );
1076                         free(m);
1077                 
1078                         osrfStringArrayFree(class_list);
1079                         free(foreign_pkey_value);
1080                         jsonObjectFree(param);
1081
1082                         return 0;
1083                     }
1084         
1085                     jsonObjectFree(_tmp_params);
1086                     free(foreign_pkey_value);
1087     
1088                     int j = 0;
1089                     char* foreign_field = NULL;
1090                     while ( (foreign_field = osrfStringArrayGetString(osrfHashGet(fcontext,"context"), j++)) ) {
1091                         osrfStringArrayAdd( context_org_array, oilsFMGetString( _fparam, foreign_field ) );
1092                             osrfLogDebug(
1093                             OSRF_LOG_MARK,
1094                             "adding foreign class %s field %s (value: %s) to the context org list",
1095                             class_name,
1096                             foreign_field,
1097                             osrfStringArrayGetString(context_org_array, context_org_array->size - 1)
1098                         );
1099                     }
1100        
1101                     jsonObjectFree(_list);
1102                 }
1103     
1104                 osrfStringArrayFree(class_list);
1105             }
1106         }
1107
1108         jsonObjectFree(param);
1109     }
1110
1111     char* context_org = NULL;
1112     char* perm = NULL;
1113     int OK = 0;
1114
1115     if (permission->size == 0) {
1116             osrfLogDebug( OSRF_LOG_MARK, "No permission specified for this action, passing through" );
1117         OK = 1;
1118     }
1119     
1120     int i = 0;
1121     while ( (perm = osrfStringArrayGetString(permission, i++)) ) {
1122         int j = 0;
1123         while ( (context_org = osrfStringArrayGetString(context_org_array, j++)) ) {
1124             dbi_result result;
1125
1126             if (pkey_value) {
1127                     osrfLogDebug(
1128                     OSRF_LOG_MARK,
1129                     "Checking object permission [%s] for user %d on object %s (class %s) at org %d",
1130                     perm,
1131                     userid,
1132                     pkey_value,
1133                     osrfHashGet(class, "classname"),
1134                     atoi(context_org)
1135                 );
1136
1137                 result = dbi_conn_queryf(
1138                     writehandle,
1139                     "SELECT permission.usr_has_object_perm(%d, '%s', '%s', '%s', %d) AS has_perm;",
1140                     userid,
1141                     perm,
1142                     osrfHashGet(class, "classname"),
1143                     pkey_value,
1144                     atoi(context_org)
1145                 );
1146
1147                 if (result) {
1148                     osrfLogDebug(
1149                         OSRF_LOG_MARK,
1150                         "Recieved a result for object permission [%s] for user %d on object %s (class %s) at org %d",
1151                         perm,
1152                         userid,
1153                         pkey_value,
1154                         osrfHashGet(class, "classname"),
1155                         atoi(context_org)
1156                     );
1157
1158                     if (dbi_result_first_row(result)) {
1159                         jsonObject* return_val = oilsMakeJSONFromResult( result );
1160                         char* has_perm = jsonObjectToSimpleString( jsonObjectGetKeyConst(return_val, "has_perm") );
1161
1162                             osrfLogDebug(
1163                             OSRF_LOG_MARK,
1164                             "Status of object permission [%s] for user %d on object %s (class %s) at org %d is %s",
1165                             perm,
1166                             userid,
1167                             pkey_value,
1168                             osrfHashGet(class, "classname"),
1169                             atoi(context_org),
1170                             has_perm
1171                         );
1172
1173                         if ( *has_perm == 't' ) OK = 1;
1174                         free(has_perm); 
1175                         jsonObjectFree(return_val);
1176                     }
1177
1178                     dbi_result_free(result); 
1179                     if (OK) break;
1180                 }
1181             }
1182
1183                 osrfLogDebug( OSRF_LOG_MARK, "Checking non-object permission [%s] for user %d at org %d", perm, userid, atoi(context_org) );
1184             result = dbi_conn_queryf(
1185                 writehandle,
1186                 "SELECT permission.usr_has_perm(%d, '%s', %d) AS has_perm;",
1187                 userid,
1188                 perm,
1189                 atoi(context_org)
1190             );
1191
1192             if (result) {
1193                     osrfLogDebug( OSRF_LOG_MARK, "Recieved a result for permission [%s] for user %d at org %d", perm, userid, atoi(context_org) );
1194                 if (dbi_result_first_row(result)) {
1195                     jsonObject* return_val = oilsMakeJSONFromResult( result );
1196                     char* has_perm = jsonObjectToSimpleString( jsonObjectGetKeyConst(return_val, "has_perm") );
1197                         osrfLogDebug( OSRF_LOG_MARK, "Status of permission [%s] for user %d at org %d is [%s]", perm, userid, atoi(context_org), has_perm );
1198                     if ( *has_perm == 't' ) OK = 1;
1199                     free(has_perm); 
1200                     jsonObjectFree(return_val);
1201                 }
1202
1203                 dbi_result_free(result); 
1204                 if (OK) break;
1205             }
1206
1207         }
1208         if (OK) break;
1209     }
1210
1211     if (pkey_value) free(pkey_value);
1212     osrfStringArrayFree(context_org_array);
1213
1214     return OK;
1215 }
1216 #endif
1217
1218
1219 static jsonObject* doCreate(osrfMethodContext* ctx, int* err ) {
1220
1221         osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1222 #ifdef PCRUD
1223         jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
1224         jsonObject* options = jsonObjectGetIndex( ctx->params, 2 );
1225 #else
1226         jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
1227         jsonObject* options = jsonObjectGetIndex( ctx->params, 1 );
1228 #endif
1229
1230         if (!verifyObjectClass(ctx, target)) {
1231                 *err = -1;
1232                 return jsonNULL;
1233         }
1234
1235         osrfLogDebug( OSRF_LOG_MARK, "Object seems to be of the correct type" );
1236
1237         if (!ctx->session || !ctx->session->userData || !osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
1238                 osrfLogError( OSRF_LOG_MARK, "No active transaction -- required for CREATE" );
1239
1240                 osrfAppSessionStatus(
1241                         ctx->session,
1242                         OSRF_STATUS_BADREQUEST,
1243                         "osrfMethodException",
1244                         ctx->request,
1245                         "No active transaction -- required for CREATE"
1246                 );
1247                 *err = -1;
1248                 return jsonNULL;
1249         }
1250
1251         if (osrfHashGet( meta, "readonly" ) && strncasecmp("true", osrfHashGet( meta, "readonly" ), 4)) {
1252                 osrfAppSessionStatus(
1253                         ctx->session,
1254                         OSRF_STATUS_BADREQUEST,
1255                         "osrfMethodException",
1256                         ctx->request,
1257                         "Cannot INSERT readonly class"
1258                 );
1259                 *err = -1;
1260                 return jsonNULL;
1261         }
1262
1263
1264         char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
1265
1266         // Set the last_xact_id
1267         int index = oilsIDL_ntop( target->classname, "last_xact_id" );
1268         if (index > -1) {
1269                 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
1270                 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
1271         }       
1272
1273         osrfLogDebug( OSRF_LOG_MARK, "There is a transaction running..." );
1274
1275         dbhandle = writehandle;
1276
1277         osrfHash* fields = osrfHashGet(meta, "fields");
1278         char* pkey = osrfHashGet(meta, "primarykey");
1279         char* seq = osrfHashGet(meta, "sequence");
1280
1281         growing_buffer* table_buf = buffer_init(128);
1282         growing_buffer* col_buf = buffer_init(128);
1283         growing_buffer* val_buf = buffer_init(128);
1284
1285         buffer_fadd(table_buf,"INSERT INTO %s", osrfHashGet(meta, "tablename"));
1286         buffer_add(col_buf,"(");
1287         buffer_add(val_buf,"VALUES (");
1288
1289
1290         int i = 0;
1291         int first = 1;
1292         char* field_name;
1293         osrfStringArray* field_list = osrfHashKeys( fields );
1294         while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
1295
1296                 osrfHash* field = osrfHashGet( fields, field_name );
1297
1298                 if(!( strcmp( osrfHashGet(osrfHashGet(fields,field_name), "virtual"), "true" ) )) continue;
1299
1300                 const jsonObject* field_object = oilsFMGetObject( target, field_name );
1301
1302                 char* value;
1303                 if (field_object && field_object->classname) {
1304                         value = oilsFMGetString(
1305                                 field_object,
1306                                 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
1307                         );
1308                 } else {
1309                         value = jsonObjectToSimpleString( field_object );
1310                 }
1311
1312
1313                 if (first) {
1314                         first = 0;
1315                 } else {
1316                         buffer_add(col_buf, ",");
1317                         buffer_add(val_buf, ",");
1318                 }
1319
1320                 buffer_add(col_buf, field_name);
1321
1322                 if (!field_object || field_object->type == JSON_NULL) {
1323                         buffer_add( val_buf, "DEFAULT" );
1324                         
1325                 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1326                         if ( !strcmp(osrfHashGet(field, "datatype"), "INT8") ) {
1327                                 buffer_fadd( val_buf, "%lld", atoll(value) );
1328                                 
1329                         } else if ( !strcmp(osrfHashGet(field, "datatype"), "INT") ) {
1330                                 buffer_fadd( val_buf, "%d", atoi(value) );
1331                                 
1332                         } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
1333                                 buffer_fadd( val_buf, "%f", atof(value) );
1334                         }
1335                 } else {
1336                         if ( dbi_conn_quote_string(writehandle, &value) ) {
1337                                 buffer_fadd( val_buf, "%s", value );
1338
1339                         } else {
1340                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
1341                                 osrfAppSessionStatus(
1342                                         ctx->session,
1343                                         OSRF_STATUS_INTERNALSERVERERROR,
1344                                         "osrfMethodException",
1345                                         ctx->request,
1346                                         "Error quoting string -- please see the error log for more details"
1347                                 );
1348                                 free(value);
1349                                 buffer_free(table_buf);
1350                                 buffer_free(col_buf);
1351                                 buffer_free(val_buf);
1352                                 *err = -1;
1353                                 return jsonNULL;
1354                         }
1355                 }
1356
1357                 free(value);
1358                 
1359         }
1360
1361
1362         buffer_add(col_buf,")");
1363         buffer_add(val_buf,")");
1364
1365         char* table_str = buffer_release(table_buf);
1366         char* col_str   = buffer_release(col_buf);
1367         char* val_str   = buffer_release(val_buf);
1368         growing_buffer* sql = buffer_init(128);
1369         buffer_fadd( sql, "%s %s %s;", table_str, col_str, val_str );
1370         free(table_str);
1371         free(col_str);
1372         free(val_str);
1373
1374         char* query = buffer_release(sql);
1375
1376         osrfLogDebug(OSRF_LOG_MARK, "%s: Insert SQL [%s]", MODULENAME, query);
1377
1378         
1379         dbi_result result = dbi_conn_query(writehandle, query);
1380
1381         jsonObject* obj = NULL;
1382
1383         if (!result) {
1384                 obj = jsonNewObject(NULL);
1385                 osrfLogError(
1386                         OSRF_LOG_MARK,
1387                         "%s ERROR inserting %s object using query [%s]",
1388                         MODULENAME,
1389                         osrfHashGet(meta, "fieldmapper"),
1390                         query
1391                 );
1392                 osrfAppSessionStatus(
1393                         ctx->session,
1394                         OSRF_STATUS_INTERNALSERVERERROR,
1395                         "osrfMethodException",
1396                         ctx->request,
1397                         "INSERT error -- please see the error log for more details"
1398                 );
1399                 *err = -1;
1400         } else {
1401
1402                 char* id = oilsFMGetString(target, pkey);
1403                 if (!id) {
1404                         unsigned long long new_id = dbi_conn_sequence_last(writehandle, seq);
1405                         growing_buffer* _id = buffer_init(10);
1406                         buffer_fadd(_id, "%lld", new_id);
1407                         id = buffer_release(_id);
1408                 }
1409
1410                 // Find quietness specification, if present
1411                 char* quiet_str = NULL;
1412                 if ( options ) {
1413                         const jsonObject* quiet_obj = jsonObjectGetKeyConst( options, "quiet" );
1414                         if( quiet_obj )
1415                                 quiet_str = jsonObjectToSimpleString( quiet_obj );
1416                 }
1417
1418                 if( quiet_str && !strcmp( quiet_str, "true" )) {  // if quietness is specified
1419                         obj = jsonNewObject(id);
1420                 }
1421                 else {
1422
1423                         jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
1424                         jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH));
1425
1426                         jsonObjectSetKey(
1427                                 jsonObjectGetIndex(fake_params, 0),
1428                                 pkey,
1429                                 jsonNewObject(id)
1430                         );
1431
1432                         jsonObject* list = doFieldmapperSearch( ctx,meta, fake_params, err);
1433
1434                         if(*err) {
1435                                 jsonObjectFree( fake_params );
1436                                 obj = jsonNULL;
1437                         } else {
1438                                 obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
1439                         }
1440
1441                         jsonObjectFree( list );
1442                         jsonObjectFree( fake_params );
1443                 }
1444
1445                 if(quiet_str) free(quiet_str);
1446                 free(id);
1447         }
1448
1449         free(query);
1450
1451         return obj;
1452
1453 }
1454
1455
1456 static jsonObject* doRetrieve(osrfMethodContext* ctx, int* err ) {
1457
1458     int id_pos = 0;
1459     int order_pos = 1;
1460
1461 #ifdef PCRUD
1462     id_pos = 1;
1463     order_pos = 2;
1464 #endif
1465
1466         osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1467
1468         jsonObject* obj;
1469
1470         char* id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, id_pos));
1471         jsonObject* order_hash = jsonObjectGetIndex(ctx->params, order_pos);
1472
1473         osrfLogDebug(
1474                 OSRF_LOG_MARK,
1475                 "%s retrieving %s object with primary key value of %s",
1476                 MODULENAME,
1477                 osrfHashGet(meta, "fieldmapper"),
1478                 id
1479         );
1480
1481         jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
1482         jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH));
1483
1484         jsonObjectSetKey(
1485                 jsonObjectGetIndex(fake_params, 0),
1486                 osrfHashGet(meta, "primarykey"),
1487                 jsonParseString(id)
1488         );
1489
1490         free(id);
1491
1492         if (order_hash) jsonObjectPush(fake_params, jsonObjectClone(order_hash) );
1493
1494         jsonObject* list = doFieldmapperSearch( ctx,meta, fake_params, err);
1495
1496         if(*err) {
1497                 jsonObjectFree( fake_params );
1498                 return jsonNULL;
1499         }
1500
1501         obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
1502
1503         jsonObjectFree( list );
1504         jsonObjectFree( fake_params );
1505
1506 #ifdef PCRUD
1507         if(!verifyObjectPCRUD(ctx, obj)) {
1508         jsonObjectFree(obj);
1509         *err = -1;
1510
1511         growing_buffer* msg = buffer_init(128);
1512         buffer_fadd(
1513             msg,
1514             "%s: Insufficient permissions",
1515             MODULENAME
1516         );
1517
1518         char* m = buffer_release(msg);
1519         osrfAppSessionStatus( ctx->session, OSRF_STATUS_BADREQUEST, "osrfMethodException", ctx->request, m );
1520
1521         free(m);
1522
1523                 return jsonNULL;
1524         }
1525 #endif
1526
1527         return obj;
1528 }
1529
1530 static char* jsonNumberToDBString ( osrfHash* field, const jsonObject* value ) {
1531         growing_buffer* val_buf = buffer_init(32);
1532
1533         if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
1534                 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%ld", (long)jsonObjectGetNumber(value) );
1535                 else {
1536                         char* val_str = jsonObjectToSimpleString(value);
1537                         buffer_fadd( val_buf, "%ld", atol(val_str) );
1538                         free(val_str);
1539                 }
1540
1541         } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
1542                 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%f",  jsonObjectGetNumber(value) );
1543                 else {
1544                         char* val_str = jsonObjectToSimpleString(value);
1545                         buffer_fadd( val_buf, "%f", atof(val_str) );
1546                         free(val_str);
1547                 }
1548         }
1549
1550         return buffer_release(val_buf);
1551 }
1552
1553 static char* searchINPredicate (const char* class, osrfHash* field,
1554                 const jsonObject* node, const char* op) {
1555         growing_buffer* sql_buf = buffer_init(32);
1556         
1557         buffer_fadd(
1558                 sql_buf,
1559                 "\"%s\".%s ",
1560                 class,
1561                 osrfHashGet(field, "name")
1562         );
1563
1564         if (!op) {
1565                 buffer_add(sql_buf, "IN (");
1566         } else if (!(strcasecmp(op,"not in"))) {
1567                 buffer_add(sql_buf, "NOT IN (");
1568         } else {
1569                 buffer_add(sql_buf, "IN (");
1570         }
1571
1572         int in_item_index = 0;
1573         int in_item_first = 1;
1574         jsonObject* in_item;
1575         while ( (in_item = jsonObjectGetIndex(node, in_item_index++)) ) {
1576
1577                 if (in_item_first)
1578                         in_item_first = 0;
1579                 else
1580                         buffer_add(sql_buf, ", ");
1581
1582                 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1583                         char* val = jsonNumberToDBString( field, in_item );
1584                         buffer_fadd( sql_buf, "%s", val );
1585                         free(val);
1586
1587                 } else {
1588                         char* key_string = jsonObjectToSimpleString(in_item);
1589                         if ( dbi_conn_quote_string(dbhandle, &key_string) ) {
1590                                 buffer_fadd( sql_buf, "%s", key_string );
1591                                 free(key_string);
1592                         } else {
1593                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, key_string);
1594                                 free(key_string);
1595                                 buffer_free(sql_buf);
1596                                 return NULL;
1597                         }
1598                 }
1599         }
1600
1601         buffer_add(
1602                 sql_buf,
1603                 ")"
1604         );
1605
1606         return buffer_release(sql_buf);
1607 }
1608
1609 static char* searchValueTransform( const jsonObject* array ) {
1610         growing_buffer* sql_buf = buffer_init(32);
1611
1612         char* val = NULL;
1613         int func_item_index = 0;
1614         int func_item_first = 2;
1615         jsonObject* func_item;
1616         while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1617
1618                 val = jsonObjectToSimpleString(func_item);
1619
1620                 if (func_item_first == 2) {
1621                         buffer_fadd(sql_buf, "%s( ", val);
1622                         free(val);
1623                         func_item_first--;
1624                         continue;
1625                 }
1626
1627                 if (func_item_first)
1628                         func_item_first--;
1629                 else
1630                         buffer_add(sql_buf, ", ");
1631
1632                 if (func_item->type == JSON_NULL) {
1633                         buffer_add( sql_buf, "NULL" );
1634                 } else if ( dbi_conn_quote_string(dbhandle, &val) ) {
1635                         buffer_fadd( sql_buf, "%s", val );
1636                 } else {
1637                         osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1638                         free(val);
1639                         buffer_free(sql_buf);
1640                         return NULL;
1641                 }
1642
1643                 free(val);
1644         }
1645
1646         buffer_add(
1647                 sql_buf,
1648                 " )"
1649         );
1650
1651         return buffer_release(sql_buf);
1652 }
1653
1654 static char* searchFunctionPredicate (const char* class, osrfHash* field,
1655                 const jsonObject* node, const char* node_key) {
1656         growing_buffer* sql_buf = buffer_init(32);
1657
1658         char* val = searchValueTransform(node);
1659         
1660         buffer_fadd(
1661                 sql_buf,
1662                 "\"%s\".%s %s %s",
1663                 class,
1664                 osrfHashGet(field, "name"),
1665                 node_key,
1666                 val
1667         );
1668
1669         free(val);
1670
1671         return buffer_release(sql_buf);
1672 }
1673
1674 static char* searchFieldTransform (const char* class, osrfHash* field, const jsonObject* node) {
1675         growing_buffer* sql_buf = buffer_init(32);
1676         
1677         char* field_transform = jsonObjectToSimpleString( jsonObjectGetKeyConst( node, "transform" ) );
1678         char* transform_subcolumn = jsonObjectToSimpleString( jsonObjectGetKeyConst( node, "result_field" ) );
1679
1680         if (field_transform) {
1681                 buffer_fadd( sql_buf, "%s(\"%s\".%s", field_transform, class, osrfHashGet(field, "name"));
1682             const jsonObject* array = jsonObjectGetKeyConst( node, "params" );
1683
1684         if (array) {
1685                 int func_item_index = 0;
1686                 jsonObject* func_item;
1687                 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1688
1689                         char* val = jsonObjectToSimpleString(func_item);
1690
1691                     if ( !val ) {
1692                             buffer_add( sql_buf, ",NULL" );
1693                     } else if ( dbi_conn_quote_string(dbhandle, &val) ) {
1694                             buffer_fadd( sql_buf, ",%s", val );
1695                         } else {
1696                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1697                             free(field_transform);
1698                                         free(val);
1699                                 buffer_free(sql_buf);
1700                                 return NULL;
1701                 }
1702                                 free(val);
1703                         }
1704
1705         }
1706
1707         buffer_add(
1708                 sql_buf,
1709                 " )"
1710         );
1711
1712         } else {
1713                 buffer_fadd( sql_buf, "\"%s\".%s", class, osrfHashGet(field, "name"));
1714         }
1715
1716     if (transform_subcolumn) {
1717         char * tmp = buffer_release(sql_buf);
1718         sql_buf = buffer_init(32);
1719         buffer_fadd(
1720             sql_buf,
1721             "(%s).\"%s\"",
1722             tmp,
1723             transform_subcolumn
1724         );
1725         free(tmp);
1726     }
1727  
1728         if (field_transform) free(field_transform);
1729         if (transform_subcolumn) free(transform_subcolumn);
1730
1731         return buffer_release(sql_buf);
1732 }
1733
1734 static char* searchFieldTransformPredicate (const char* class, osrfHash* field, jsonObject* node, const char* node_key) {
1735         char* field_transform = searchFieldTransform( class, field, node );
1736         char* value = NULL;
1737
1738         if (!jsonObjectGetKeyConst( node, "value" )) {
1739                 value = searchWHERE( node, osrfHashGet( oilsIDL(), class ), AND_OP_JOIN, NULL );
1740         } else if (jsonObjectGetKeyConst( node, "value" )->type == JSON_ARRAY) {
1741                 value = searchValueTransform(jsonObjectGetKeyConst( node, "value" ));
1742         } else if (jsonObjectGetKeyConst( node, "value" )->type == JSON_HASH) {
1743                 value = searchWHERE( jsonObjectGetKeyConst( node, "value" ), osrfHashGet( oilsIDL(), class ), AND_OP_JOIN, NULL );
1744         } else if (jsonObjectGetKeyConst( node, "value" )->type != JSON_NULL) {
1745                 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1746                         value = jsonNumberToDBString( field, jsonObjectGetKeyConst( node, "value" ) );
1747                 } else {
1748                         value = jsonObjectToSimpleString(jsonObjectGetKeyConst( node, "value" ));
1749                         if ( !dbi_conn_quote_string(dbhandle, &value) ) {
1750                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, value);
1751                                 free(value);
1752                                 free(field_transform);
1753                                 return NULL;
1754                         }
1755                 }
1756         }
1757
1758         growing_buffer* sql_buf = buffer_init(32);
1759         
1760         buffer_fadd(
1761                 sql_buf,
1762                 "%s %s %s",
1763                 field_transform,
1764                 node_key,
1765                 value
1766         );
1767
1768         free(value);
1769         free(field_transform);
1770
1771         return buffer_release(sql_buf);
1772 }
1773
1774 static char* searchSimplePredicate (const char* orig_op, const char* class,
1775                 osrfHash* field, const jsonObject* node) {
1776
1777         char* val = NULL;
1778
1779         if (node->type != JSON_NULL) {
1780                 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1781                         val = jsonNumberToDBString( field, node );
1782                 } else {
1783                         val = jsonObjectToSimpleString(node);
1784                 }
1785         }
1786
1787         char* pred = searchWriteSimplePredicate( class, field, osrfHashGet(field, "name"), orig_op, val );
1788
1789         if (val) free(val);
1790
1791         return pred;
1792 }
1793
1794 static char* searchWriteSimplePredicate ( const char* class, osrfHash* field,
1795         const char* left, const char* orig_op, const char* right ) {
1796
1797         char* val = NULL;
1798         char* op = NULL;
1799         if (right == NULL) {
1800                 val = strdup("NULL");
1801
1802                 if (strcmp( orig_op, "=" ))
1803                         op = strdup("IS NOT");
1804                 else
1805                         op = strdup("IS");
1806
1807         } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1808                 val = strdup(right);
1809                 op = strdup(orig_op);
1810
1811         } else {
1812                 val = strdup(right);
1813                 if ( !dbi_conn_quote_string(dbhandle, &val) ) {
1814                         osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1815                         free(val);
1816                         return NULL;
1817                 }
1818                 op = strdup(orig_op);
1819         }
1820
1821         growing_buffer* sql_buf = buffer_init(16);
1822         buffer_fadd( sql_buf, "\"%s\".%s %s %s", class, left, op, val );
1823         free(val);
1824         free(op);
1825
1826         return buffer_release(sql_buf);
1827 }
1828
1829 static char* searchBETWEENPredicate (const char* class, osrfHash* field, jsonObject* node) {
1830
1831         char* x_string;
1832         char* y_string;
1833
1834         if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1835                 x_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,0));
1836                 y_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,1));
1837
1838         } else {
1839                 x_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,0));
1840                 y_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,1));
1841                 if ( !(dbi_conn_quote_string(dbhandle, &x_string) && dbi_conn_quote_string(dbhandle, &y_string)) ) {
1842                         osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key strings [%s] and [%s]", MODULENAME, x_string, y_string);
1843                         free(x_string);
1844                         free(y_string);
1845                         return NULL;
1846                 }
1847         }
1848
1849         growing_buffer* sql_buf = buffer_init(32);
1850         buffer_fadd( sql_buf, "%s BETWEEN %s AND %s", osrfHashGet(field, "name"), x_string, y_string );
1851         free(x_string);
1852         free(y_string);
1853
1854         return buffer_release(sql_buf);
1855 }
1856
1857 static char* searchPredicate ( const char* class, osrfHash* field, jsonObject* node ) {
1858
1859         char* pred = NULL;
1860         if (node->type == JSON_ARRAY) { // equality IN search
1861                 pred = searchINPredicate( class, field, node, NULL );
1862         } else if (node->type == JSON_HASH) { // non-equality search
1863                 jsonObject* pred_node;
1864                 jsonIterator* pred_itr = jsonNewIterator( node );
1865                 while ( (pred_node = jsonIteratorNext( pred_itr )) ) {
1866                         if ( !(strcasecmp( pred_itr->key,"between" )) )
1867                                 pred = searchBETWEENPredicate( class, field, pred_node );
1868                         else if ( !(strcasecmp( pred_itr->key,"in" )) || !(strcasecmp( pred_itr->key,"not in" )) )
1869                                 pred = searchINPredicate( class, field, pred_node, pred_itr->key );
1870                         else if ( pred_node->type == JSON_ARRAY )
1871                                 pred = searchFunctionPredicate( class, field, pred_node, pred_itr->key );
1872                         else if ( pred_node->type == JSON_HASH )
1873                                 pred = searchFieldTransformPredicate( class, field, pred_node, pred_itr->key );
1874                         else 
1875                                 pred = searchSimplePredicate( pred_itr->key, class, field, pred_node );
1876
1877                         break;
1878                 }
1879         jsonIteratorFree(pred_itr);
1880         } else if (node->type == JSON_NULL) { // IS NULL search
1881                 growing_buffer* _p = buffer_init(64);
1882                 buffer_fadd(
1883                         _p,
1884                         "\"%s\".%s IS NULL",
1885                         class,
1886                         osrfHashGet(field, "name")
1887                 );
1888                 pred = buffer_release(_p);
1889         } else { // equality search
1890                 pred = searchSimplePredicate( "=", class, field, node );
1891         }
1892
1893         return pred;
1894
1895 }
1896
1897
1898 /*
1899
1900 join : {
1901         acn : {
1902                 field : record,
1903                 fkey : id
1904                 type : left
1905                 filter_op : or
1906                 filter : { ... },
1907                 join : {
1908                         acp : {
1909                                 field : call_number,
1910                                 fkey : id,
1911                                 filter : { ... },
1912                         },
1913                 },
1914         },
1915         mrd : {
1916                 field : record,
1917                 type : inner
1918                 fkey : id,
1919                 filter : { ... },
1920         }
1921 }
1922
1923 */
1924
1925 static char* searchJOIN ( const jsonObject* join_hash, osrfHash* leftmeta ) {
1926
1927         const jsonObject* working_hash;
1928         jsonObject* freeable_hash = NULL;
1929
1930         if (join_hash->type == JSON_STRING) {
1931                 // create a wrapper around a copy of the original
1932                 char* _tmp = jsonObjectToSimpleString( join_hash );
1933                 freeable_hash = jsonNewObjectType(JSON_HASH);
1934                 jsonObjectSetKey(freeable_hash, _tmp, NULL);
1935                 free(_tmp);
1936                 working_hash = freeable_hash;
1937         }
1938         else
1939                 working_hash = join_hash;
1940
1941         growing_buffer* join_buf = buffer_init(128);
1942         char* leftclass = osrfHashGet(leftmeta, "classname");
1943
1944         jsonObject* snode = NULL;
1945         jsonIterator* search_itr = jsonNewIterator( working_hash );
1946         if(freeable_hash)
1947                 jsonObjectFree(freeable_hash);
1948         
1949         while ( (snode = jsonIteratorNext( search_itr )) ) {
1950                 osrfHash* idlClass = osrfHashGet( oilsIDL(), search_itr->key );
1951
1952                 char* class = osrfHashGet(idlClass, "classname");
1953
1954                 char* fkey = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "fkey" ) );
1955                 char* field = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "field" ) );
1956
1957                 if (field && !fkey) {
1958                         fkey = (char*)oilsIDLFindPath("/%s/links/%s/key", class, field);
1959                         if (!fkey) {
1960                                 osrfLogError(
1961                                         OSRF_LOG_MARK,
1962                                         "%s: JOIN failed.  No link defined from %s.%s to %s",
1963                                         MODULENAME,
1964                                         class,
1965                                         field,
1966                                         leftclass
1967                                 );
1968                                 buffer_free(join_buf);
1969                                 free(field);
1970                                 jsonIteratorFree(search_itr);
1971                                 return NULL;
1972                         }
1973                         fkey = strdup( fkey );
1974
1975                 } else if (!field && fkey) {
1976                         field = (char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, fkey );
1977                         if (!field) {
1978                                 osrfLogError(
1979                                         OSRF_LOG_MARK,
1980                                         "%s: JOIN failed.  No link defined from %s.%s to %s",
1981                                         MODULENAME,
1982                                         leftclass,
1983                                         fkey,
1984                                         class
1985                                 );
1986                                 buffer_free(join_buf);
1987                                 free(fkey);
1988                                 jsonIteratorFree(search_itr);
1989                                 return NULL;
1990                         }
1991                         field = strdup( field );
1992
1993                 } else if (!field && !fkey) {
1994                         osrfHash* _links = oilsIDLFindPath("/%s/links", leftclass);
1995
1996                         int i = 0;
1997                         osrfStringArray* keys = osrfHashKeys( _links );
1998                         while ( (fkey = osrfStringArrayGetString(keys, i++)) ) {
1999                                 fkey = strdup(osrfStringArrayGetString(keys, i++));
2000                                 if ( !strcmp( (char*)oilsIDLFindPath("/%s/links/%s/class", leftclass, fkey), class) ) {
2001                                         field = strdup( (char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, fkey) );
2002                                         break;
2003                                 } else {
2004                                         free(fkey);
2005                                 }
2006                         }
2007                         osrfStringArrayFree(keys);
2008
2009                         if (!field && !fkey) {
2010                                 _links = oilsIDLFindPath("/%s/links", class);
2011
2012                                 i = 0;
2013                                 keys = osrfHashKeys( _links );
2014                                 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
2015                                         field = strdup(osrfStringArrayGetString(keys, i++));
2016                                         if ( !strcmp( (char*)oilsIDLFindPath("/%s/links/%s/class", class, field), class) ) {
2017                                                 fkey = strdup( (char*)oilsIDLFindPath("/%s/links/%s/key", class, field) );
2018                                                 break;
2019                                         } else {
2020                                                 free(field);
2021                                         }
2022                                 }
2023                                 osrfStringArrayFree(keys);
2024                         }
2025
2026                         if (!field && !fkey) {
2027                                 osrfLogError(
2028                                         OSRF_LOG_MARK,
2029                                         "%s: JOIN failed.  No link defined between %s and %s",
2030                                         MODULENAME,
2031                                         leftclass,
2032                                         class
2033                                 );
2034                                 buffer_free(join_buf);
2035                                 jsonIteratorFree(search_itr);
2036                                 return NULL;
2037                         }
2038
2039                 }
2040
2041                 char* type = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "type" ) );
2042                 if (type) {
2043                         if ( !strcasecmp(type,"left") ) {
2044                                 buffer_add(join_buf, " LEFT JOIN");
2045                         } else if ( !strcasecmp(type,"right") ) {
2046                                 buffer_add(join_buf, " RIGHT JOIN");
2047                         } else if ( !strcasecmp(type,"full") ) {
2048                                 buffer_add(join_buf, " FULL JOIN");
2049                         } else {
2050                                 buffer_add(join_buf, " INNER JOIN");
2051                         }
2052                 } else {
2053                         buffer_add(join_buf, " INNER JOIN");
2054                 }
2055                 free(type);
2056
2057                 char* table = getSourceDefinition(idlClass);
2058                 buffer_fadd(join_buf, " %s AS \"%s\" ON ( \"%s\".%s = \"%s\".%s", table, class, class, field, leftclass, fkey);
2059                 free(table);
2060
2061                 const jsonObject* filter = jsonObjectGetKeyConst( snode, "filter" );
2062                 if (filter) {
2063                         char* filter_op = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "filter_op" ) );
2064                         if (filter_op) {
2065                                 if (!strcasecmp("or",filter_op)) {
2066                                         buffer_add( join_buf, " OR " );
2067                                 } else {
2068                                         buffer_add( join_buf, " AND " );
2069                                 }
2070                         } else {
2071                                 buffer_add( join_buf, " AND " );
2072                         }
2073
2074                         char* jpred = searchWHERE( filter, idlClass, AND_OP_JOIN, NULL );
2075                         buffer_fadd( join_buf, " %s", jpred );
2076                         free(jpred);
2077                         free(filter_op);
2078                 }
2079
2080                 buffer_add(join_buf, " ) ");
2081                 
2082                 const jsonObject* join_filter = jsonObjectGetKeyConst( snode, "join" );
2083                 if (join_filter) {
2084                         char* jpred = searchJOIN( join_filter, idlClass );
2085                         buffer_fadd( join_buf, " %s", jpred );
2086                         free(jpred);
2087                 }
2088
2089                 free(fkey);
2090                 free(field);
2091         }
2092
2093     jsonIteratorFree(search_itr);
2094
2095         return buffer_release(join_buf);
2096 }
2097
2098 /*
2099
2100 { +class : { -or|-and : { field : { op : value }, ... } ... }, ... }
2101 { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }
2102 [ { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }, ... ]
2103
2104 */
2105
2106 static char* searchWHERE ( const jsonObject* search_hash, osrfHash* meta, int opjoin_type, osrfMethodContext* ctx ) {
2107
2108         osrfLogDebug(
2109         OSRF_LOG_MARK,
2110         "%s: Entering searchWHERE; search_hash addr = %d, meta addr = %d, opjoin_type = %d, ctx addr = %d",
2111         MODULENAME,
2112         search_hash,
2113         meta,
2114         opjoin_type,
2115         ctx
2116     );
2117
2118         growing_buffer* sql_buf = buffer_init(128);
2119
2120         jsonObject* node = NULL;
2121
2122     int first = 1;
2123     if ( search_hash->type == JSON_ARRAY ) {
2124             osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_ARRAY", MODULENAME);
2125         jsonIterator* search_itr = jsonNewIterator( search_hash );
2126         while ( (node = jsonIteratorNext( search_itr )) ) {
2127             if (first) {
2128                 first = 0;
2129             } else {
2130                 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2131                 else buffer_add(sql_buf, " AND ");
2132             }
2133
2134             char* subpred = searchWHERE( node, meta, opjoin_type, ctx );
2135             buffer_fadd(sql_buf, "( %s )", subpred);
2136             free(subpred);
2137         }
2138         jsonIteratorFree(search_itr);
2139
2140     } else if ( search_hash->type == JSON_HASH ) {
2141             osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_HASH", MODULENAME);
2142         jsonIterator* search_itr = jsonNewIterator( search_hash );
2143         while ( (node = jsonIteratorNext( search_itr )) ) {
2144
2145             if (first) {
2146                 first = 0;
2147             } else {
2148                 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2149                 else buffer_add(sql_buf, " AND ");
2150             }
2151
2152             if ( !strncmp("+",search_itr->key,1) ) {
2153                 if ( node->type == JSON_STRING ) {
2154                     char* subpred = jsonObjectToSimpleString( node );
2155                     buffer_fadd(sql_buf, " \"%s\".%s ", search_itr->key + 1, subpred);
2156                     free(subpred);
2157                 } else {
2158                     char* subpred = searchWHERE( node, osrfHashGet( oilsIDL(), search_itr->key + 1 ), AND_OP_JOIN, ctx );
2159                     buffer_fadd(sql_buf, "( %s )", subpred);
2160                     free(subpred);
2161                 }
2162             } else if ( !strcasecmp("-or",search_itr->key) ) {
2163                 char* subpred = searchWHERE( node, meta, OR_OP_JOIN, ctx );
2164                 buffer_fadd(sql_buf, "( %s )", subpred);
2165                 free(subpred);
2166             } else if ( !strcasecmp("-and",search_itr->key) ) {
2167                 char* subpred = searchWHERE( node, meta, AND_OP_JOIN, ctx );
2168                 buffer_fadd(sql_buf, "( %s )", subpred);
2169                 free(subpred);
2170             } else if ( !strcasecmp("-exists",search_itr->key) ) {
2171                 char* subpred = SELECT(
2172                     ctx,
2173                     jsonObjectGetKey( node, "select" ),
2174                     jsonObjectGetKey( node, "from" ),
2175                     jsonObjectGetKey( node, "where" ),
2176                     jsonObjectGetKey( node, "having" ),
2177                     jsonObjectGetKey( node, "order_by" ),
2178                     jsonObjectGetKey( node, "limit" ),
2179                     jsonObjectGetKey( node, "offset" ),
2180                     SUBSELECT
2181                 );
2182
2183                 buffer_fadd(sql_buf, "EXISTS ( %s )", subpred);
2184                 free(subpred);
2185             } else if ( !strcasecmp("-not-exists",search_itr->key) ) {
2186                 char* subpred = SELECT(
2187                     ctx,
2188                     jsonObjectGetKey( node, "select" ),
2189                     jsonObjectGetKey( node, "from" ),
2190                     jsonObjectGetKey( node, "where" ),
2191                     jsonObjectGetKey( node, "having" ),
2192                     jsonObjectGetKey( node, "order_by" ),
2193                     jsonObjectGetKey( node, "limit" ),
2194                     jsonObjectGetKey( node, "offset" ),
2195                     SUBSELECT
2196                 );
2197
2198                 buffer_fadd(sql_buf, "NOT EXISTS ( %s )", subpred);
2199                 free(subpred);
2200             } else {
2201
2202                 char* class = osrfHashGet(meta, "classname");
2203                 osrfHash* fields = osrfHashGet(meta, "fields");
2204                 osrfHash* field = osrfHashGet( fields, search_itr->key );
2205
2206
2207                 if (!field) {
2208                     char* table = getSourceDefinition(meta);
2209                     osrfLogError(
2210                         OSRF_LOG_MARK,
2211                         "%s: Attempt to reference non-existant column %s on %s (%s)",
2212                         MODULENAME,
2213                         search_itr->key,
2214                         table,
2215                         class
2216                     );
2217                     buffer_free(sql_buf);
2218                     free(table);
2219                                         jsonIteratorFree(search_itr);
2220                                         return NULL;
2221                 }
2222
2223                 char* subpred = searchPredicate( class, field, node );
2224                 buffer_add( sql_buf, subpred );
2225                 free(subpred);
2226             }
2227         }
2228             jsonIteratorFree(search_itr);
2229
2230     } else {
2231         // ERROR ... only hash and array allowed at this level
2232         char* predicate_string = jsonObjectToJSON( search_hash );
2233         osrfLogError(
2234             OSRF_LOG_MARK,
2235             "%s: Invalid predicate structure: %s",
2236             MODULENAME,
2237             predicate_string
2238         );
2239         buffer_free(sql_buf);
2240         free(predicate_string);
2241         return NULL;
2242     }
2243
2244
2245         return buffer_release(sql_buf);
2246 }
2247
2248 static char* SELECT (
2249                 /* method context */ osrfMethodContext* ctx,
2250                 
2251                 /* SELECT   */ jsonObject* selhash,
2252                 /* FROM     */ jsonObject* join_hash,
2253                 /* WHERE    */ jsonObject* search_hash,
2254                 /* HAVING   */ jsonObject* having_hash,
2255                 /* ORDER BY */ jsonObject* order_hash,
2256                 /* LIMIT    */ jsonObject* limit,
2257                 /* OFFSET   */ jsonObject* offset,
2258                 /* flags    */ int flags
2259 ) {
2260         const char* locale = osrf_message_get_last_locale();
2261
2262         // in case we don't get a select list
2263         jsonObject* defaultselhash = NULL;
2264
2265         // general tmp objects
2266         const jsonObject* tmp_const;
2267         jsonObject* _tmp = NULL;
2268         jsonObject* selclass = NULL;
2269         jsonObject* selfield = NULL;
2270         jsonObject* snode = NULL;
2271         jsonObject* onode = NULL;
2272         jsonObject* found = NULL;
2273
2274         char* string = NULL;
2275         int from_function = 0;
2276         int first = 1;
2277         int gfirst = 1;
2278         //int hfirst = 1;
2279
2280         // the core search class
2281         char* core_class = NULL;
2282
2283         // metadata about the core search class
2284         osrfHash* core_meta = NULL;
2285         osrfHash* core_fields = NULL;
2286         osrfHash* idlClass = NULL;
2287
2288         // punt if there's no core class
2289         if (!join_hash || ( join_hash->type == JSON_HASH && !join_hash->size ))
2290                 return NULL;
2291
2292         // get the core class -- the only key of the top level FROM clause, or a string
2293         if (join_hash->type == JSON_HASH) {
2294                 jsonIterator* tmp_itr = jsonNewIterator( join_hash );
2295                 snode = jsonIteratorNext( tmp_itr );
2296                 
2297                 core_class = strdup( tmp_itr->key );
2298                 join_hash = snode;
2299
2300                 jsonIteratorFree( tmp_itr );
2301                 snode = NULL;
2302
2303         } else if (join_hash->type == JSON_ARRAY) {
2304         from_function = 1;
2305         selhash = NULL;
2306
2307         } else if (join_hash->type == JSON_STRING) {
2308                 core_class = jsonObjectToSimpleString( join_hash );
2309                 join_hash = NULL;
2310         }
2311
2312         // punt if we don't know about the core class (and it's not a function)
2313         if (!from_function && !(core_meta = osrfHashGet( oilsIDL(), core_class ))) {
2314                 free(core_class);
2315                 return NULL;
2316         }
2317
2318         // if the select list is empty, or the core class field list is '*',
2319         // build the default select list ...
2320         if (!selhash) {
2321                 selhash = defaultselhash = jsonNewObjectType(JSON_HASH);
2322                 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2323         } else if ( (tmp_const = jsonObjectGetKeyConst( selhash, core_class )) && tmp_const->type == JSON_STRING ) {
2324                 char* _x = jsonObjectToSimpleString( tmp_const );
2325                 if (!strncmp( "*", _x, 1 )) {
2326                         jsonObjectRemoveKey( selhash, core_class );
2327                         jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2328                 }
2329                 free(_x);
2330         }
2331
2332         // the query buffer
2333         growing_buffer* sql_buf = buffer_init(128);
2334
2335         // temp buffer for the SELECT list
2336         growing_buffer* select_buf = buffer_init(128);
2337         growing_buffer* order_buf = buffer_init(128);
2338         growing_buffer* group_buf = buffer_init(128);
2339         growing_buffer* having_buf = buffer_init(128);
2340
2341         if (!from_function) 
2342         core_fields = osrfHashGet(core_meta, "fields");
2343
2344         // ... and if we /are/ building the default list, do that
2345         if ( (_tmp = jsonObjectGetKey(selhash,core_class)) && !_tmp->size ) {
2346                 
2347                 int i = 0;
2348                 char* field;
2349
2350         if (!from_function) {
2351                 osrfStringArray* keys = osrfHashKeys( core_fields );
2352                 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
2353                         if ( strncasecmp( "true", osrfHashGet( osrfHashGet( core_fields, field ), "virtual" ), 4 ) )
2354                                 jsonObjectPush( _tmp, jsonNewObject( field ) );
2355                 }
2356                 osrfStringArrayFree(keys);
2357         }
2358         }
2359
2360         // Now we build the actual select list
2361         if (!from_function) {
2362             int sel_pos = 1;
2363             jsonObject* is_agg = jsonObjectFindPath(selhash, "//aggregate");
2364             first = 1;
2365             gfirst = 1;
2366             jsonIterator* selclass_itr = jsonNewIterator( selhash );
2367             while ( (selclass = jsonIteratorNext( selclass_itr )) ) {
2368
2369                     // round trip through the idl, just to be safe
2370                     idlClass = osrfHashGet( oilsIDL(), selclass_itr->key );
2371                     if (!idlClass) continue;
2372                     char* cname = osrfHashGet(idlClass, "classname");
2373
2374                     // make sure the target relation is in the join tree
2375                     if (strcmp(core_class,cname)) {
2376                             if (!join_hash) continue;
2377
2378                             if (join_hash->type == JSON_STRING) {
2379                                     string = jsonObjectToSimpleString(join_hash);
2380                                     found = strcmp(string,cname) ? NULL : jsonParseString("{\"1\":\"1\"}");
2381                                     free(string);
2382                             } else {
2383                                     found = jsonObjectFindPath(join_hash, "//%s", cname);
2384                             }
2385
2386                             if (!found->size) {
2387                                     jsonObjectFree(found);
2388                                     continue;
2389                             }
2390
2391                             jsonObjectFree(found);
2392                     }
2393
2394                     // stitch together the column list ...
2395                     jsonIterator* select_itr = jsonNewIterator( selclass );
2396                     while ( (selfield = jsonIteratorNext( select_itr )) ) {
2397
2398                             char* __column = NULL;
2399                             char* __alias = NULL;
2400
2401                             // ... if it's a sstring, just toss it on the pile
2402                             if (selfield->type == JSON_STRING) {
2403
2404                                     // again, just to be safe
2405                                     char* _requested_col = jsonObjectToSimpleString(selfield);
2406                                     osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), _requested_col );
2407                                     free(_requested_col);
2408
2409                                     if (!field) continue;
2410                                     __column = strdup(osrfHashGet(field, "name"));
2411
2412                                     if (first) {
2413                                             first = 0;
2414                                     } else {
2415                                             buffer_add(select_buf, ",");
2416                                     }
2417
2418                     if (locale) {
2419                             char* i18n = osrfHashGet(field, "i18n");
2420                                     if (flags & DISABLE_I18N)
2421                             i18n = NULL;
2422
2423                             if ( i18n && !strncasecmp("true", i18n, 4)) {
2424                                 char* pkey = osrfHashGet(idlClass, "primarykey");
2425                                 char* tname = osrfHashGet(idlClass, "tablename");
2426
2427                             buffer_fadd(select_buf, " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"", tname, cname, __column, pkey, cname, pkey, locale, __column);
2428                         } else {
2429                                             buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, __column, __column);
2430                         }
2431                     } else {
2432                                         buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, __column, __column);
2433                     }
2434
2435                             // ... but it could be an object, in which case we check for a Field Transform
2436                             } else {
2437
2438                                     __column = jsonObjectToSimpleString( jsonObjectGetKeyConst( selfield, "column" ) );
2439
2440                                     // again, just to be safe
2441                                     osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), __column );
2442                                     if (!field) continue;
2443                                     const char* fname = osrfHashGet(field, "name");
2444
2445                                     if (first) {
2446                                             first = 0;
2447                                     } else {
2448                                             buffer_add(select_buf, ",");
2449                                     }
2450
2451                                     if ((tmp_const = jsonObjectGetKeyConst( selfield, "alias" ))) {
2452                                             __alias = jsonObjectToSimpleString( tmp_const );
2453                                     } else {
2454                                             __alias = strdup(__column);
2455                                     }
2456
2457                                     if (jsonObjectGetKeyConst( selfield, "transform" )) {
2458                                             free(__column);
2459                                             __column = searchFieldTransform(cname, field, selfield);
2460                                             buffer_fadd(select_buf, " %s AS \"%s\"", __column, __alias);
2461                                     } else {
2462                         if (locale) {
2463                                     char* i18n = osrfHashGet(field, "i18n");
2464                                         if (flags & DISABLE_I18N)
2465                                 i18n = NULL;
2466     
2467                                     if ( i18n && !strncasecmp("true", i18n, 4)) {
2468                                     char* pkey = osrfHashGet(idlClass, "primarykey");
2469                                     char* tname = osrfHashGet(idlClass, "tablename");
2470
2471                                 buffer_fadd(select_buf, " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"", tname, cname, fname, pkey, cname, pkey, locale, __alias);
2472                             } else {
2473                                                     buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, fname, __alias);
2474                             }
2475                         } else {
2476                                                 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, fname, __alias);
2477                         }
2478                                     }
2479                             }
2480
2481                             if (is_agg->size || (flags & SELECT_DISTINCT)) {
2482
2483                                     if ( !(
2484                             jsonBoolIsTrue( jsonObjectGetKey( selfield, "aggregate" ) ) ||
2485                                 ((int)jsonObjectGetNumber(jsonObjectGetKey( selfield, "aggregate" ))) == 1 // support 1/0 for perl's sake
2486                          )
2487                     ) {
2488                                             if (gfirst) {
2489                                                     gfirst = 0;
2490                                             } else {
2491                                                     buffer_add(group_buf, ",");
2492                                             }
2493
2494                                             buffer_fadd(group_buf, " %d", sel_pos);
2495                                     /*
2496                                     } else if (is_agg = jsonObjectGetKey( selfield, "having" )) {
2497                                             if (gfirst) {
2498                                                     gfirst = 0;
2499                                             } else {
2500                                                     buffer_add(group_buf, ",");
2501                                             }
2502
2503                                             __column = searchFieldTransform(cname, field, selfield);
2504                                             buffer_fadd(group_buf, " %s", __column);
2505                                             __column = searchFieldTransform(cname, field, selfield);
2506                                     */
2507                                     }
2508                             }
2509
2510                             if (__column) free(__column);
2511                             if (__alias) free(__alias);
2512
2513                             sel_pos++;
2514                     }
2515
2516             // jsonIteratorFree(select_itr);
2517             }
2518
2519         // jsonIteratorFree(selclass_itr);
2520
2521             if (is_agg) jsonObjectFree(is_agg);
2522     } else {
2523         buffer_add(select_buf, "*");
2524     }
2525
2526
2527         char* col_list = buffer_release(select_buf);
2528         char* table = NULL;
2529     if (!from_function) table = getSourceDefinition(core_meta);
2530     else table = searchValueTransform(join_hash);
2531
2532         // Put it all together
2533         buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\" ", col_list, table, core_class );
2534         free(col_list);
2535         free(table);
2536
2537     if (!from_function) {
2538             // Now, walk the join tree and add that clause
2539             if ( join_hash ) {
2540                     char* join_clause = searchJOIN( join_hash, core_meta );
2541                     buffer_add(sql_buf, join_clause);
2542                     free(join_clause);
2543             }
2544
2545             if ( search_hash ) {
2546                     buffer_add(sql_buf, " WHERE ");
2547
2548                     // and it's on the the WHERE clause
2549                     char* pred = searchWHERE( search_hash, core_meta, AND_OP_JOIN, ctx );
2550
2551                     if (!pred) {
2552                             if (ctx) {
2553                                 osrfAppSessionStatus(
2554                                         ctx->session,
2555                                         OSRF_STATUS_INTERNALSERVERERROR,
2556                                         "osrfMethodException",
2557                                         ctx->request,
2558                                         "Severe query error in WHERE predicate -- see error log for more details"
2559                                 );
2560                             }
2561                             free(core_class);
2562                             buffer_free(having_buf);
2563                             buffer_free(group_buf);
2564                             buffer_free(order_buf);
2565                             buffer_free(sql_buf);
2566                             if (defaultselhash) jsonObjectFree(defaultselhash);
2567                             return NULL;
2568                     } else {
2569                             buffer_add(sql_buf, pred);
2570                             free(pred);
2571                     }
2572         }
2573
2574             if ( having_hash ) {
2575                     buffer_add(sql_buf, " HAVING ");
2576
2577                     // and it's on the the WHERE clause
2578                     char* pred = searchWHERE( having_hash, core_meta, AND_OP_JOIN, ctx );
2579
2580                     if (!pred) {
2581                             if (ctx) {
2582                                 osrfAppSessionStatus(
2583                                         ctx->session,
2584                                         OSRF_STATUS_INTERNALSERVERERROR,
2585                                         "osrfMethodException",
2586                                         ctx->request,
2587                                         "Severe query error in HAVING predicate -- see error log for more details"
2588                                 );
2589                             }
2590                             free(core_class);
2591                             buffer_free(having_buf);
2592                             buffer_free(group_buf);
2593                             buffer_free(order_buf);
2594                             buffer_free(sql_buf);
2595                             if (defaultselhash) jsonObjectFree(defaultselhash);
2596                             return NULL;
2597                     } else {
2598                             buffer_add(sql_buf, pred);
2599                             free(pred);
2600                     }
2601             }
2602
2603             first = 1;
2604             jsonIterator* class_itr = jsonNewIterator( order_hash );
2605             while ( (snode = jsonIteratorNext( class_itr )) ) {
2606
2607                     if (!jsonObjectGetKeyConst(selhash,class_itr->key))
2608                             continue;
2609
2610                     if ( snode->type == JSON_HASH ) {
2611
2612                         jsonIterator* order_itr = jsonNewIterator( snode );
2613                             while ( (onode = jsonIteratorNext( order_itr )) ) {
2614
2615                                     if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
2616                                             continue;
2617
2618                                     char* direction = NULL;
2619                                     if ( onode->type == JSON_HASH ) {
2620                                             if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
2621                                                     string = searchFieldTransform(
2622                                                             class_itr->key,
2623                                                             oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
2624                                                             onode
2625                                                     );
2626                                             } else {
2627                                                     growing_buffer* field_buf = buffer_init(16);
2628                                                     buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
2629                                                     string = buffer_release(field_buf);
2630                                             }
2631
2632                                             if ( (tmp_const = jsonObjectGetKeyConst( onode, "direction" )) ) {
2633                                                     direction = jsonObjectToSimpleString(tmp_const);
2634                                                     if (!strncasecmp(direction, "d", 1)) {
2635                                                             free(direction);
2636                                                             direction = " DESC";
2637                                                     } else {
2638                                                             free(direction);
2639                                                             direction = " ASC";
2640                                                     }
2641                                             }
2642
2643                                     } else {
2644                                             string = strdup(order_itr->key);
2645                                             direction = jsonObjectToSimpleString(onode);
2646                                             if (!strncasecmp(direction, "d", 1)) {
2647                                                     free(direction);
2648                                                     direction = " DESC";
2649                                             } else {
2650                                                     free(direction);
2651                                                     direction = " ASC";
2652                                             }
2653                                     }
2654
2655                                     if (first) {
2656                                             first = 0;
2657                                     } else {
2658                                             buffer_add(order_buf, ", ");
2659                                     }
2660
2661                                     buffer_add(order_buf, string);
2662                                     free(string);
2663
2664                                     if (direction) {
2665                                             buffer_add(order_buf, direction);
2666                                     }
2667
2668                             }
2669                 // jsonIteratorFree(order_itr);
2670
2671                     } else if ( snode->type == JSON_ARRAY ) {
2672
2673                         jsonIterator* order_itr = jsonNewIterator( snode );
2674                             while ( (onode = jsonIteratorNext( order_itr )) ) {
2675
2676                                     char* _f = jsonObjectToSimpleString( onode );
2677
2678                                     if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, _f))
2679                                             continue;
2680
2681                                     if (first) {
2682                                             first = 0;
2683                                     } else {
2684                                             buffer_add(order_buf, ", ");
2685                                     }
2686
2687                                     buffer_add(order_buf, _f);
2688                                     free(_f);
2689
2690                             }
2691                 // jsonIteratorFree(order_itr);
2692
2693
2694                     // IT'S THE OOOOOOOOOOOLD STYLE!
2695                     } else {
2696                             osrfLogError(OSRF_LOG_MARK, "%s: Possible SQL injection attempt; direct order by is not allowed", MODULENAME);
2697                             if (ctx) {
2698                                 osrfAppSessionStatus(
2699                                         ctx->session,
2700                                         OSRF_STATUS_INTERNALSERVERERROR,
2701                                         "osrfMethodException",
2702                                         ctx->request,
2703                                         "Severe query error -- see error log for more details"
2704                                 );
2705                             }
2706
2707                             free(core_class);
2708                             buffer_free(having_buf);
2709                             buffer_free(group_buf);
2710                             buffer_free(order_buf);
2711                             buffer_free(sql_buf);
2712                             if (defaultselhash) jsonObjectFree(defaultselhash);
2713                             jsonIteratorFree(class_itr);
2714                             return NULL;
2715                     }
2716
2717             }
2718     }
2719
2720     // jsonIteratorFree(class_itr);
2721
2722         string = buffer_release(group_buf);
2723
2724         if (strlen(string)) {
2725                 buffer_fadd(
2726                         sql_buf,
2727                         " GROUP BY %s",
2728                         string
2729                 );
2730         }
2731
2732         free(string);
2733
2734         string = buffer_release(having_buf);
2735  
2736         if (strlen(string)) {
2737                 buffer_fadd(
2738                         sql_buf,
2739                         " HAVING %s",
2740                         string
2741                 );
2742         }
2743
2744         free(string);
2745
2746         string = buffer_release(order_buf);
2747
2748         if (strlen(string)) {
2749                 buffer_fadd(
2750                         sql_buf,
2751                         " ORDER BY %s",
2752                         string
2753                 );
2754         }
2755
2756         free(string);
2757
2758         if ( limit ){
2759                 string = jsonObjectToSimpleString(limit);
2760                 buffer_fadd( sql_buf, " LIMIT %d", atoi(string) );
2761                 free(string);
2762         }
2763
2764         if (offset) {
2765                 string = jsonObjectToSimpleString(offset);
2766                 buffer_fadd( sql_buf, " OFFSET %d", atoi(string) );
2767                 free(string);
2768         }
2769
2770         if (!(flags & SUBSELECT)) buffer_add(sql_buf, ";");
2771
2772         free(core_class);
2773         if (defaultselhash) jsonObjectFree(defaultselhash);
2774
2775         return buffer_release(sql_buf);
2776
2777 }
2778
2779 static char* buildSELECT ( jsonObject* search_hash, jsonObject* order_hash, osrfHash* meta, osrfMethodContext* ctx ) {
2780
2781         const char* locale = osrf_message_get_last_locale();
2782
2783         osrfHash* fields = osrfHashGet(meta, "fields");
2784         char* core_class = osrfHashGet(meta, "classname");
2785
2786         const jsonObject* join_hash = jsonObjectGetKeyConst( order_hash, "join" );
2787
2788         jsonObject* node = NULL;
2789         jsonObject* snode = NULL;
2790         jsonObject* onode = NULL;
2791         const jsonObject* _tmp = NULL;
2792         jsonObject* selhash = NULL;
2793         jsonObject* defaultselhash = NULL;
2794
2795         growing_buffer* sql_buf = buffer_init(128);
2796         growing_buffer* select_buf = buffer_init(128);
2797
2798         if ( !(selhash = jsonObjectGetKey( order_hash, "select" )) ) {
2799                 defaultselhash = jsonNewObjectType(JSON_HASH);
2800                 selhash = defaultselhash;
2801         }
2802         
2803         if ( !jsonObjectGetKeyConst(selhash,core_class) ) {
2804                 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2805                 jsonObject* flist = jsonObjectGetKey( selhash, core_class );
2806                 
2807                 int i = 0;
2808                 char* field;
2809
2810                 osrfStringArray* keys = osrfHashKeys( fields );
2811                 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
2812                         if ( strcasecmp( "true", osrfHashGet( osrfHashGet( fields, field ), "virtual" ) ) )
2813                                 jsonObjectPush( flist, jsonNewObject( field ) );
2814                 }
2815                 osrfStringArrayFree(keys);
2816         }
2817
2818         int first = 1;
2819         jsonIterator* class_itr = jsonNewIterator( selhash );
2820         while ( (snode = jsonIteratorNext( class_itr )) ) {
2821
2822                 osrfHash* idlClass = osrfHashGet( oilsIDL(), class_itr->key );
2823                 if (!idlClass) continue;
2824                 char* cname = osrfHashGet(idlClass, "classname");
2825
2826                 if (strcmp(core_class,class_itr->key)) {
2827                         if (!join_hash) continue;
2828
2829                         jsonObject* found =  jsonObjectFindPath(join_hash, "//%s", class_itr->key);
2830                         if (!found->size) {
2831                                 jsonObjectFree(found);
2832                                 continue;
2833                         }
2834
2835                         jsonObjectFree(found);
2836                 }
2837
2838                 jsonIterator* select_itr = jsonNewIterator( snode );
2839                 while ( (node = jsonIteratorNext( select_itr )) ) {
2840                         char* item_str = jsonObjectToSimpleString(node);
2841                         osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), item_str );
2842                         free(item_str);
2843                         char* fname = osrfHashGet(field, "name");
2844
2845                         if (!field) continue;
2846
2847                         if (first) {
2848                                 first = 0;
2849                         } else {
2850                                 buffer_add(select_buf, ",");
2851                         }
2852
2853             if (locale) {
2854                         char* i18n = osrfHashGet(field, "i18n");
2855                             if ( !(
2856                         jsonBoolIsTrue( jsonObjectGetKey( order_hash, "no_i18n" ) ) ||
2857                         ((int)jsonObjectGetNumber(jsonObjectGetKey( order_hash, "no_i18n" ))) == 1 // support 1/0 for perl's sake
2858                      )
2859                 ) i18n = NULL;
2860
2861                         if ( i18n && !strncasecmp("true", i18n, 4)) {
2862                         char* pkey = osrfHashGet(idlClass, "primarykey");
2863                         char* tname = osrfHashGet(idlClass, "tablename");
2864
2865                     buffer_fadd(select_buf, " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"", tname, cname, fname, pkey, cname, pkey, locale, fname);
2866                 } else {
2867                                 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
2868                 }
2869             } else {
2870                             buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
2871             }
2872                 }
2873
2874         jsonIteratorFree(select_itr);
2875         }
2876
2877     jsonIteratorFree(class_itr);
2878
2879         char* col_list = buffer_release(select_buf);
2880         char* table = getSourceDefinition(meta);
2881
2882         buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\"", col_list, table, core_class );
2883         free(col_list);
2884         free(table);
2885
2886         if ( join_hash ) {
2887                 char* join_clause = searchJOIN( join_hash, meta );
2888                 buffer_fadd(sql_buf, " %s", join_clause);
2889                 free(join_clause);
2890         }
2891
2892         char* tmpsql = buffer_data(sql_buf); // This strdup's ... no worries.
2893         osrfLogDebug(OSRF_LOG_MARK, "%s pre-predicate SQL =  %s", MODULENAME, tmpsql);
2894         free(tmpsql);
2895
2896         buffer_add(sql_buf, " WHERE ");
2897
2898         char* pred = searchWHERE( search_hash, meta, AND_OP_JOIN, ctx );
2899         if (!pred) {
2900                 osrfAppSessionStatus(
2901                         ctx->session,
2902                         OSRF_STATUS_INTERNALSERVERERROR,
2903                                 "osrfMethodException",
2904                                 ctx->request,
2905                                 "Severe query error -- see error log for more details"
2906                         );
2907                 buffer_free(sql_buf);
2908                 if(defaultselhash) jsonObjectFree(defaultselhash);
2909                 return NULL;
2910         } else {
2911                 buffer_add(sql_buf, pred);
2912                 free(pred);
2913         }
2914
2915         if (order_hash) {
2916                 char* string = NULL;
2917                 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "order_by" )) ){
2918
2919                         growing_buffer* order_buf = buffer_init(128);
2920
2921                         first = 1;
2922                         jsonIterator* class_itr = jsonNewIterator( _tmp );
2923                         while ( (snode = jsonIteratorNext( class_itr )) ) {
2924
2925                                 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
2926                                         continue;
2927
2928                                 if ( snode->type == JSON_HASH ) {
2929
2930                                         jsonIterator* order_itr = jsonNewIterator( snode );
2931                                         while ( (onode = jsonIteratorNext( order_itr )) ) {
2932
2933                                                 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
2934                                                         continue;
2935
2936                                                 char* direction = NULL;
2937                                                 if ( onode->type == JSON_HASH ) {
2938                                                         if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
2939                                                                 string = searchFieldTransform(
2940                                                                         class_itr->key,
2941                                                                         oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
2942                                                                         onode
2943                                                                 );
2944                                                         } else {
2945                                                                 growing_buffer* field_buf = buffer_init(16);
2946                                                                 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
2947                                                                 string = buffer_release(field_buf);
2948                                                         }
2949
2950                                                         if ( (_tmp = jsonObjectGetKeyConst( onode, "direction" )) ) {
2951                                                                 direction = jsonObjectToSimpleString(_tmp);
2952                                                                 if (!strncasecmp(direction, "d", 1)) {
2953                                                                         free(direction);
2954                                                                         direction = " DESC";
2955                                                                 } else {
2956                                                                         free(direction);
2957                                                                         direction = " ASC";
2958                                                                 }
2959                                                         }
2960
2961                                                 } else {
2962                                                         string = strdup(order_itr->key);
2963                                                         direction = jsonObjectToSimpleString(onode);
2964                                                         if (!strncasecmp(direction, "d", 1)) {
2965                                                                 free(direction);
2966                                                                 direction = " DESC";
2967                                                         } else {
2968                                                                 free(direction);
2969                                                                 direction = " ASC";
2970                                                         }
2971                                                 }
2972
2973                                                 if (first) {
2974                                                         first = 0;
2975                                                 } else {
2976                                                         buffer_add(order_buf, ", ");
2977                                                 }
2978
2979                                                 buffer_add(order_buf, string);
2980                                                 free(string);
2981
2982                                                 if (direction) {
2983                                                         buffer_add(order_buf, direction);
2984                                                 }
2985
2986                                         }
2987
2988                     jsonIteratorFree(order_itr);
2989
2990                                 } else {
2991                                         string = jsonObjectToSimpleString(snode);
2992                                         buffer_add(order_buf, string);
2993                                         free(string);
2994                                         break;
2995                                 }
2996
2997                         }
2998
2999             jsonIteratorFree(class_itr);
3000
3001                         string = buffer_release(order_buf);
3002
3003                         if (strlen(string)) {
3004                                 buffer_fadd(
3005                                         sql_buf,
3006                                         " ORDER BY %s",
3007                                         string
3008                                 );
3009                         }
3010
3011                         free(string);
3012                 }
3013
3014                 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "limit" )) ){
3015                         string = jsonObjectToSimpleString(_tmp);
3016                         buffer_fadd(
3017                                 sql_buf,
3018                                 " LIMIT %d",
3019                                 atoi(string)
3020                         );
3021                         free(string);
3022                 }
3023
3024                 _tmp = jsonObjectGetKeyConst( order_hash, "offset" );
3025                 if (_tmp) {
3026                         string = jsonObjectToSimpleString(_tmp);
3027                         buffer_fadd(
3028                                 sql_buf,
3029                                 " OFFSET %d",
3030                                 atoi(string)
3031                         );
3032                         free(string);
3033                 }
3034         }
3035
3036         if (defaultselhash) jsonObjectFree(defaultselhash);
3037
3038         buffer_add(sql_buf, ";");
3039         return buffer_release(sql_buf);
3040 }
3041
3042 int doJSONSearch ( osrfMethodContext* ctx ) {
3043         OSRF_METHOD_VERIFY_CONTEXT(ctx);
3044         osrfLogDebug(OSRF_LOG_MARK, "Recieved query request");
3045
3046         int err = 0;
3047
3048         // XXX for now...
3049         dbhandle = writehandle;
3050
3051         jsonObject* hash = jsonObjectGetIndex(ctx->params, 0);
3052
3053     int flags = 0;
3054
3055         if (jsonBoolIsTrue(jsonObjectGetKey( hash, "distinct" )))
3056          flags |= SELECT_DISTINCT;
3057
3058         if ( ((int)jsonObjectGetNumber(jsonObjectGetKey( hash, "distinct" ))) == 1 ) // support 1/0 for perl's sake
3059          flags |= SELECT_DISTINCT;
3060
3061         if (jsonBoolIsTrue(jsonObjectGetKey( hash, "no_i18n" )))
3062          flags |= DISABLE_I18N;
3063
3064         if ( ((int)jsonObjectGetNumber(jsonObjectGetKey( hash, "no_i18n" ))) == 1 ) // support 1/0 for perl's sake
3065          flags |= DISABLE_I18N;
3066
3067         osrfLogDebug(OSRF_LOG_MARK, "Building SQL ...");
3068         char* sql = SELECT(
3069                         ctx,
3070                         jsonObjectGetKey( hash, "select" ),
3071                         jsonObjectGetKey( hash, "from" ),
3072                         jsonObjectGetKey( hash, "where" ),
3073                         jsonObjectGetKey( hash, "having" ),
3074                         jsonObjectGetKey( hash, "order_by" ),
3075                         jsonObjectGetKey( hash, "limit" ),
3076                         jsonObjectGetKey( hash, "offset" ),
3077                         flags
3078         );
3079
3080         if (!sql) {
3081                 err = -1;
3082                 return err;
3083         }
3084         
3085         osrfLogDebug(OSRF_LOG_MARK, "%s SQL =  %s", MODULENAME, sql);
3086         dbi_result result = dbi_conn_query(dbhandle, sql);
3087
3088         if(result) {
3089                 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3090
3091                 if (dbi_result_first_row(result)) {
3092                         /* JSONify the result */
3093                         osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3094
3095                         do {
3096                                 jsonObject* return_val = oilsMakeJSONFromResult( result );
3097                                 osrfAppRespond( ctx, return_val );
3098                 jsonObjectFree( return_val );
3099                         } while (dbi_result_next_row(result));
3100
3101                 } else {
3102                         osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
3103                 }
3104
3105                 osrfAppRespondComplete( ctx, NULL );
3106
3107                 /* clean up the query */
3108                 dbi_result_free(result); 
3109
3110         } else {
3111                 err = -1;
3112                 osrfLogError(OSRF_LOG_MARK, "%s: Error with query [%s]", MODULENAME, sql);
3113                 osrfAppSessionStatus(
3114                         ctx->session,
3115                         OSRF_STATUS_INTERNALSERVERERROR,
3116                         "osrfMethodException",
3117                         ctx->request,
3118                         "Severe query error -- see error log for more details"
3119                 );
3120         }
3121
3122         free(sql);
3123         return err;
3124 }
3125
3126 static jsonObject* doFieldmapperSearch ( osrfMethodContext* ctx, osrfHash* meta,
3127                 const jsonObject* params, int* err ) {
3128
3129         // XXX for now...
3130         dbhandle = writehandle;
3131
3132         osrfHash* links = osrfHashGet(meta, "links");
3133         osrfHash* fields = osrfHashGet(meta, "fields");
3134         char* core_class = osrfHashGet(meta, "classname");
3135         char* pkey = osrfHashGet(meta, "primarykey");
3136
3137         const jsonObject* _tmp;
3138         jsonObject* obj;
3139         jsonObject* search_hash = jsonObjectGetIndex(params, 0);
3140         jsonObject* order_hash = jsonObjectGetIndex(params, 1);
3141
3142         char* sql = buildSELECT( search_hash, order_hash, meta, ctx );
3143         if (!sql) {
3144                 osrfLogDebug(OSRF_LOG_MARK, "Problem building query, returning NULL");
3145                 *err = -1;
3146                 return NULL;
3147         }
3148         
3149         osrfLogDebug(OSRF_LOG_MARK, "%s SQL =  %s", MODULENAME, sql);
3150         dbi_result result = dbi_conn_query(dbhandle, sql);
3151
3152         jsonObject* res_list = jsonNewObjectType(JSON_ARRAY);
3153         if(result) {
3154                 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3155                 osrfHash* dedup = osrfNewHash();
3156
3157                 if (dbi_result_first_row(result)) {
3158                         /* JSONify the result */
3159                         osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3160                         do {
3161                                 obj = oilsMakeFieldmapperFromResult( result, meta );
3162                                 char* pkey_val = oilsFMGetString( obj, pkey );
3163                                 if ( osrfHashGet( dedup, pkey_val ) ) {
3164                                         jsonObjectFree(obj);
3165                                         free(pkey_val);
3166                                 } else {
3167                                         osrfHashSet( dedup, pkey_val, pkey_val );
3168                                         jsonObjectPush(res_list, obj);
3169                                 }
3170                         } while (dbi_result_next_row(result));
3171                 } else {
3172                         osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
3173                 }
3174
3175                 osrfHashFree(dedup);
3176
3177                 /* clean up the query */
3178                 dbi_result_free(result); 
3179
3180         } else {
3181                 osrfLogError(OSRF_LOG_MARK, "%s: Error retrieving %s with query [%s]", MODULENAME, osrfHashGet(meta, "fieldmapper"), sql);
3182                 osrfAppSessionStatus(
3183                         ctx->session,
3184                         OSRF_STATUS_INTERNALSERVERERROR,
3185                         "osrfMethodException",
3186                         ctx->request,
3187                         "Severe query error -- see error log for more details"
3188                 );
3189                 *err = -1;
3190                 free(sql);
3191                 jsonObjectFree(res_list);
3192                 return jsonNULL;
3193
3194         }
3195
3196         free(sql);
3197
3198         if (res_list->size && order_hash) {
3199                 _tmp = jsonObjectGetKeyConst( order_hash, "flesh" );
3200                 if (_tmp) {
3201                         int x = (int)jsonObjectGetNumber(_tmp);
3202                         if (x == -1 || x > max_flesh_depth) x = max_flesh_depth;
3203
3204                         const jsonObject* temp_blob;
3205                         if ((temp_blob = jsonObjectGetKeyConst( order_hash, "flesh_fields" )) && x > 0) {
3206
3207                                 jsonObject* flesh_blob = jsonObjectClone( temp_blob );
3208                                 const jsonObject* flesh_fields = jsonObjectGetKeyConst( flesh_blob, core_class );
3209
3210                                 osrfStringArray* link_fields = NULL;
3211
3212                                 if (flesh_fields) {
3213                                         if (flesh_fields->size == 1) {
3214                                                 char* _t = jsonObjectToSimpleString( jsonObjectGetIndex( flesh_fields, 0 ) );
3215                                                 if (!strcmp(_t,"*")) link_fields = osrfHashKeys( links );
3216                                                 free(_t);
3217                                         }
3218
3219                                         if (!link_fields) {
3220                                                 jsonObject* _f;
3221                                                 link_fields = osrfNewStringArray(1);
3222                                                 jsonIterator* _i = jsonNewIterator( flesh_fields );
3223                                                 while ((_f = jsonIteratorNext( _i ))) {
3224                                                         osrfStringArrayAdd( link_fields, jsonObjectToSimpleString( _f ) );
3225                                                 }
3226                         jsonIteratorFree(_i);
3227                                         }
3228                                 }
3229
3230                                 jsonObject* cur;
3231                                 jsonIterator* itr = jsonNewIterator( res_list );
3232                                 while ((cur = jsonIteratorNext( itr ))) {
3233
3234                                         int i = 0;
3235                                         char* link_field;
3236                                         
3237                                         while ( (link_field = osrfStringArrayGetString(link_fields, i++)) ) {
3238
3239                                                 osrfLogDebug(OSRF_LOG_MARK, "Starting to flesh %s", link_field);
3240
3241                                                 osrfHash* kid_link = osrfHashGet(links, link_field);
3242                                                 if (!kid_link) continue;
3243
3244                                                 osrfHash* field = osrfHashGet(fields, link_field);
3245                                                 if (!field) continue;
3246
3247                                                 osrfHash* value_field = field;
3248
3249                                                 osrfHash* kid_idl = osrfHashGet(oilsIDL(), osrfHashGet(kid_link, "class"));
3250                                                 if (!kid_idl) continue;
3251
3252                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3253                                                         value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3254                                                 }
3255                                                         
3256                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) { // might_have
3257                                                         value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3258                                                 }
3259
3260                                                 osrfStringArray* link_map = osrfHashGet( kid_link, "map" );
3261
3262                                                 if (link_map->size > 0) {
3263                                                         jsonObject* _kid_key = jsonNewObjectType(JSON_ARRAY);
3264                                                         jsonObjectPush(
3265                                                                 _kid_key,
3266                                                                 jsonNewObject( osrfStringArrayGetString( link_map, 0 ) )
3267                                                         );
3268
3269                                                         jsonObjectSetKey(
3270                                                                 flesh_blob,
3271                                                                 osrfHashGet(kid_link, "class"),
3272                                                                 _kid_key
3273                                                         );
3274                                                 };
3275
3276                                                 osrfLogDebug(
3277                                                         OSRF_LOG_MARK,
3278                                                         "Link field: %s, remote class: %s, fkey: %s, reltype: %s",
3279                                                         osrfHashGet(kid_link, "field"),
3280                                                         osrfHashGet(kid_link, "class"),
3281                                                         osrfHashGet(kid_link, "key"),
3282                                                         osrfHashGet(kid_link, "reltype")
3283                                                 );
3284
3285                                                 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
3286                                                 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // search hash
3287                                                 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // order/flesh hash
3288
3289                                                 osrfLogDebug(OSRF_LOG_MARK, "Creating dummy params object...");
3290
3291                                                 char* search_key =
3292                                                 jsonObjectToSimpleString(
3293                                                         jsonObjectGetIndex(
3294                                                                 cur,
3295                                                                 atoi( osrfHashGet(value_field, "array_position") )
3296                                                         )
3297                                                 );
3298
3299                                                 if (!search_key) {
3300                                                         osrfLogDebug(OSRF_LOG_MARK, "Nothing to search for!");
3301                                                         continue;
3302                                                 }
3303                                                         
3304                                                 jsonObjectSetKey(
3305                                                         jsonObjectGetIndex(fake_params, 0),
3306                                                         osrfHashGet(kid_link, "key"),
3307                                                         jsonNewObject( search_key )
3308                                                 );
3309
3310                                                 free(search_key);
3311
3312
3313                                                 jsonObjectSetKey(
3314                                                         jsonObjectGetIndex(fake_params, 1),
3315                                                         "flesh",
3316                                                         jsonNewNumberObject( (double)(x - 1 + link_map->size) )
3317                                                 );
3318
3319                                                 if (flesh_blob)
3320                                                         jsonObjectSetKey( jsonObjectGetIndex(fake_params, 1), "flesh_fields", jsonObjectClone(flesh_blob) );
3321
3322                                                 if (jsonObjectGetKeyConst(order_hash, "order_by")) {
3323                                                         jsonObjectSetKey(
3324                                                                 jsonObjectGetIndex(fake_params, 1),
3325                                                                 "order_by",
3326                                                                 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "order_by"))
3327                                                         );
3328                                                 }
3329
3330                                                 if (jsonObjectGetKeyConst(order_hash, "select")) {
3331                                                         jsonObjectSetKey(
3332                                                                 jsonObjectGetIndex(fake_params, 1),
3333                                                                 "select",
3334                                                                 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "select"))
3335                                                         );
3336                                                 }
3337
3338                                                 jsonObject* kids = doFieldmapperSearch(ctx, kid_idl, fake_params, err);
3339
3340                                                 if(*err) {
3341                                                         jsonObjectFree( fake_params );
3342                                                         osrfStringArrayFree(link_fields);
3343                                                         jsonIteratorFree(itr);
3344                                                         jsonObjectFree(res_list);
3345                                                         jsonObjectFree(flesh_blob);
3346                                                         return jsonNULL;
3347                                                 }
3348
3349                                                 osrfLogDebug(OSRF_LOG_MARK, "Search for %s return %d linked objects", osrfHashGet(kid_link, "class"), kids->size);
3350
3351                                                 jsonObject* X = NULL;
3352                                                 if ( link_map->size > 0 && kids->size > 0 ) {
3353                                                         X = kids;
3354                                                         kids = jsonNewObjectType(JSON_ARRAY);
3355
3356                                                         jsonObject* _k_node;
3357                                                         jsonIterator* _k = jsonNewIterator( X );
3358                                                         while ((_k_node = jsonIteratorNext( _k ))) {
3359                                                                 jsonObjectPush(
3360                                                                         kids,
3361                                                                         jsonObjectClone(
3362                                                                                 jsonObjectGetIndex(
3363                                                                                         _k_node,
3364                                                                                         (unsigned long)atoi(
3365                                                                                                 osrfHashGet(
3366                                                                                                         osrfHashGet(
3367                                                                                                                 osrfHashGet(
3368                                                                                                                         osrfHashGet(
3369                                                                                                                                 oilsIDL(),
3370                                                                                                                                 osrfHashGet(kid_link, "class")
3371                                                                                                                         ),
3372                                                                                                                         "fields"
3373                                                                                                                 ),
3374                                                                                                                 osrfStringArrayGetString( link_map, 0 )
3375                                                                                                         ),
3376                                                                                                         "array_position"
3377                                                                                                 )
3378                                                                                         )
3379                                                                                 )
3380                                                                         )
3381                                                                 );
3382                                                         }
3383                                                         jsonIteratorFree(_k);
3384                                                 }
3385
3386                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_a" )) || !(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) {
3387                                                         osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3388                                                         jsonObjectSetIndex(
3389                                                                 cur,
3390                                                                 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3391                                                                 jsonObjectClone( jsonObjectGetIndex(kids, 0) )
3392                                                         );
3393                                                 }
3394
3395                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3396                                                         osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3397                                                         jsonObjectSetIndex(
3398                                                                 cur,
3399                                                                 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3400                                                                 jsonObjectClone( kids )
3401                                                         );
3402                                                 }
3403
3404                                                 if (X) {
3405                                                         jsonObjectFree(kids);
3406                                                         kids = X;
3407                                                 }
3408
3409                                                 jsonObjectFree( kids );
3410                                                 jsonObjectFree( fake_params );
3411
3412                                                 osrfLogDebug(OSRF_LOG_MARK, "Fleshing of %s complete", osrfHashGet(kid_link, "field"));
3413                                                 osrfLogDebug(OSRF_LOG_MARK, "%s", jsonObjectToJSON(cur));
3414
3415                                         }
3416                                 }
3417                                 jsonObjectFree( flesh_blob );
3418                                 osrfStringArrayFree(link_fields);
3419                                 jsonIteratorFree(itr);
3420                         }
3421                 }
3422         }
3423
3424         return res_list;
3425 }
3426
3427
3428 static jsonObject* doUpdate(osrfMethodContext* ctx, int* err ) {
3429
3430         osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3431 #ifdef PCRUD
3432         jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
3433 #else
3434         jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
3435 #endif
3436
3437         if (!verifyObjectClass(ctx, target)) {
3438                 *err = -1;
3439                 return jsonNULL;
3440         }
3441
3442         if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3443                 osrfAppSessionStatus(
3444                         ctx->session,
3445                         OSRF_STATUS_BADREQUEST,
3446                         "osrfMethodException",
3447                         ctx->request,
3448                         "No active transaction -- required for UPDATE"
3449                 );
3450                 *err = -1;
3451                 return jsonNULL;
3452         }
3453
3454         if (osrfHashGet( meta, "readonly" ) && strncasecmp("true", osrfHashGet( meta, "readonly" ), 4)) {
3455                 osrfAppSessionStatus(
3456                         ctx->session,
3457                         OSRF_STATUS_BADREQUEST,
3458                         "osrfMethodException",
3459                         ctx->request,
3460                         "Cannot UPDATE readonly class"
3461                 );
3462                 *err = -1;
3463                 return jsonNULL;
3464         }
3465
3466         dbhandle = writehandle;
3467
3468         char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
3469
3470         // Set the last_xact_id
3471         int index = oilsIDL_ntop( target->classname, "last_xact_id" );
3472         if (index > -1) {
3473                 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
3474                 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
3475         }       
3476
3477         char* pkey = osrfHashGet(meta, "primarykey");
3478         osrfHash* fields = osrfHashGet(meta, "fields");
3479
3480         char* id = oilsFMGetString( target, pkey );
3481
3482         osrfLogDebug(
3483                 OSRF_LOG_MARK,
3484                 "%s updating %s object with %s = %s",
3485                 MODULENAME,
3486                 osrfHashGet(meta, "fieldmapper"),
3487                 pkey,
3488                 id
3489         );
3490
3491         growing_buffer* sql = buffer_init(128);
3492         buffer_fadd(sql,"UPDATE %s SET", osrfHashGet(meta, "tablename"));
3493
3494         int i = 0;
3495         int first = 1;
3496         char* field_name;
3497         osrfStringArray* field_list = osrfHashKeys( fields );
3498         while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
3499
3500                 osrfHash* field = osrfHashGet( fields, field_name );
3501
3502                 if(!( strcmp( field_name, pkey ) )) continue;
3503                 if(!( strcmp( osrfHashGet(osrfHashGet(fields,field_name), "virtual"), "true" ) )) continue;
3504
3505                 const jsonObject* field_object = oilsFMGetObject( target, field_name );
3506
3507                 char* value;
3508                 if (field_object && field_object->classname) {
3509                         value = oilsFMGetString(
3510                                 field_object,
3511                                 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
3512             );
3513                 } else {
3514                         value = jsonObjectToSimpleString( field_object );
3515                 }
3516
3517                 osrfLogDebug( OSRF_LOG_MARK, "Updating %s object with %s = %s", osrfHashGet(meta, "fieldmapper"), field_name, value);
3518
3519                 if (!field_object || field_object->type == JSON_NULL) {
3520                         if ( !(!( strcmp( osrfHashGet(meta, "classname"), "au" ) ) && !( strcmp( field_name, "passwd" ) )) ) { // arg at the special case!
3521                                 if (first) first = 0;
3522                                 else buffer_add(sql, ",");
3523                                 buffer_fadd( sql, " %s = NULL", field_name );
3524                         }
3525                         
3526                 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
3527                         if (first) first = 0;
3528                         else buffer_add(sql, ",");
3529
3530                         if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
3531                                 buffer_fadd( sql, " %s = %ld", field_name, atol(value) );
3532                         } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
3533                                 buffer_fadd( sql, " %s = %f", field_name, atof(value) );
3534                         }
3535
3536                         osrfLogDebug( OSRF_LOG_MARK, "%s is of type %s", field_name, osrfHashGet(field, "datatype"));
3537
3538                 } else {
3539                         if ( dbi_conn_quote_string(dbhandle, &value) ) {
3540                                 if (first) first = 0;
3541                                 else buffer_add(sql, ",");
3542                                 buffer_fadd( sql, " %s = %s", field_name, value );
3543
3544                         } else {
3545                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
3546                                 osrfAppSessionStatus(
3547                                         ctx->session,
3548                                         OSRF_STATUS_INTERNALSERVERERROR,
3549                                         "osrfMethodException",
3550                                         ctx->request,
3551                                         "Error quoting string -- please see the error log for more details"
3552                                 );
3553                                 free(value);
3554                                 free(id);
3555                                 buffer_free(sql);
3556                                 *err = -1;
3557                                 return jsonNULL;
3558                         }
3559                 }
3560
3561                 free(value);
3562                 
3563         }
3564
3565         jsonObject* obj = jsonParseString(id);
3566
3567         if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
3568                 dbi_conn_quote_string(dbhandle, &id);
3569
3570         buffer_fadd( sql, " WHERE %s = %s;", pkey, id );
3571
3572         char* query = buffer_release(sql);
3573         osrfLogDebug(OSRF_LOG_MARK, "%s: Update SQL [%s]", MODULENAME, query);
3574
3575         dbi_result result = dbi_conn_query(dbhandle, query);
3576         free(query);
3577
3578         if (!result) {
3579                 jsonObjectFree(obj);
3580                 obj = jsonNewObject(NULL);
3581                 osrfLogError(
3582                         OSRF_LOG_MARK,
3583                         "%s ERROR updating %s object with %s = %s",
3584                         MODULENAME,
3585                         osrfHashGet(meta, "fieldmapper"),
3586                         pkey,
3587                         id
3588                 );
3589         }
3590
3591         free(id);
3592
3593         return obj;
3594 }
3595
3596 static jsonObject* doDelete(osrfMethodContext* ctx, int* err ) {
3597
3598         osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3599
3600         if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3601                 osrfAppSessionStatus(
3602                         ctx->session,
3603                         OSRF_STATUS_BADREQUEST,
3604                         "osrfMethodException",
3605                         ctx->request,
3606                         "No active transaction -- required for DELETE"
3607                 );
3608                 *err = -1;
3609                 return jsonNULL;
3610         }
3611
3612         if (osrfHashGet( meta, "readonly" ) && strncasecmp("true", osrfHashGet( meta, "readonly" ), 4)) {
3613                 osrfAppSessionStatus(
3614                         ctx->session,
3615                         OSRF_STATUS_BADREQUEST,
3616                         "osrfMethodException",
3617                         ctx->request,
3618                         "Cannot DELETE readonly class"
3619                 );
3620                 *err = -1;
3621                 return jsonNULL;
3622         }
3623
3624         dbhandle = writehandle;
3625
3626         jsonObject* obj;
3627
3628         char* pkey = osrfHashGet(meta, "primarykey");
3629
3630         int _obj_pos = 0;
3631 #ifdef PCRUD
3632                 _obj_pos = 1;
3633 #endif
3634
3635         char* id;
3636         if (jsonObjectGetIndex(ctx->params, _obj_pos)->classname) {
3637                 if (!verifyObjectClass(ctx, jsonObjectGetIndex( ctx->params, _obj_pos ))) {
3638                         *err = -1;
3639                         return jsonNULL;
3640                 }
3641
3642                 id = oilsFMGetString( jsonObjectGetIndex(ctx->params, _obj_pos), pkey );
3643         } else {
3644 #ifdef PCRUD
3645         if (!verifyObjectPCRUD( ctx, NULL )) {
3646                         *err = -1;
3647                         return jsonNULL;
3648         }
3649 #endif
3650                 id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, _obj_pos));
3651         }
3652
3653         osrfLogDebug(
3654                 OSRF_LOG_MARK,
3655                 "%s deleting %s object with %s = %s",
3656                 MODULENAME,
3657                 osrfHashGet(meta, "fieldmapper"),
3658                 pkey,
3659                 id
3660         );
3661
3662         obj = jsonParseString(id);
3663
3664         if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
3665                 dbi_conn_quote_string(writehandle, &id);
3666
3667         dbi_result result = dbi_conn_queryf(writehandle, "DELETE FROM %s WHERE %s = %s;", osrfHashGet(meta, "tablename"), pkey, id);
3668
3669         if (!result) {
3670                 jsonObjectFree(obj);
3671                 obj = jsonNewObject(NULL);
3672                 osrfLogError(
3673                         OSRF_LOG_MARK,
3674                         "%s ERROR deleting %s object with %s = %s",
3675                         MODULENAME,
3676                         osrfHashGet(meta, "fieldmapper"),
3677                         pkey,
3678                         id
3679                 );
3680         }
3681
3682         free(id);
3683
3684         return obj;
3685
3686 }
3687
3688
3689 static jsonObject* oilsMakeFieldmapperFromResult( dbi_result result, osrfHash* meta) {
3690         if(!(result && meta)) return jsonNULL;
3691
3692         jsonObject* object = jsonNewObject(NULL);
3693         jsonObjectSetClass(object, osrfHashGet(meta, "classname"));
3694
3695         osrfHash* fields = osrfHashGet(meta, "fields");
3696
3697         osrfLogInternal(OSRF_LOG_MARK, "Setting object class to %s ", object->classname);
3698
3699         osrfHash* _f;
3700         time_t _tmp_dt;
3701         char dt_string[256];
3702         struct tm gmdt;
3703
3704         int fmIndex;
3705         int columnIndex = 1;
3706         int attr;
3707         unsigned short type;
3708         const char* columnName;
3709
3710         /* cycle through the column list */
3711         while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
3712
3713                 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
3714
3715                 fmIndex = -1; // reset the position
3716                 
3717                 /* determine the field type and storage attributes */
3718                 type = dbi_result_get_field_type(result, columnName);
3719                 attr = dbi_result_get_field_attribs(result, columnName);
3720
3721                 /* fetch the fieldmapper index */
3722                 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
3723                         char* virt = (char*)osrfHashGet(_f, "virtual");
3724                         char* pos = (char*)osrfHashGet(_f, "array_position");
3725
3726                         if ( !virt || !pos || !(strcmp( virt, "true" )) ) continue;
3727
3728                         fmIndex = atoi( pos );
3729                         osrfLogInternal(OSRF_LOG_MARK, "... Found column at position [%s]...", pos);
3730                 } else {
3731                         continue;
3732                 }
3733
3734                 if (dbi_result_field_is_null(result, columnName)) {
3735                         jsonObjectSetIndex( object, fmIndex, jsonNewObject(NULL) );
3736                 } else {
3737
3738                         switch( type ) {
3739
3740                                 case DBI_TYPE_INTEGER :
3741
3742                                         if( attr & DBI_INTEGER_SIZE8 ) 
3743                                                 jsonObjectSetIndex( object, fmIndex, 
3744                                                         jsonNewNumberObject(dbi_result_get_longlong(result, columnName)));
3745                                         else 
3746                                                 jsonObjectSetIndex( object, fmIndex, 
3747                                                         jsonNewNumberObject(dbi_result_get_int(result, columnName)));
3748
3749                                         break;
3750
3751                                 case DBI_TYPE_DECIMAL :
3752                                         jsonObjectSetIndex( object, fmIndex, 
3753                                                         jsonNewNumberObject(dbi_result_get_double(result, columnName)));
3754                                         break;
3755
3756                                 case DBI_TYPE_STRING :
3757
3758
3759                                         jsonObjectSetIndex(
3760                                                 object,
3761                                                 fmIndex,
3762                                                 jsonNewObject( dbi_result_get_string(result, columnName) )
3763                                         );
3764
3765                                         break;
3766
3767                                 case DBI_TYPE_DATETIME :
3768
3769                                         memset(dt_string, '\0', sizeof(dt_string));
3770                                         memset(&gmdt, '\0', sizeof(gmdt));
3771
3772                                         _tmp_dt = dbi_result_get_datetime(result, columnName);
3773
3774
3775                                         if (!(attr & DBI_DATETIME_DATE)) {
3776                                                 gmtime_r( &_tmp_dt, &gmdt );
3777                                                 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
3778                                         } else if (!(attr & DBI_DATETIME_TIME)) {
3779                                                 localtime_r( &_tmp_dt, &gmdt );
3780                                                 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
3781                                         } else {
3782                                                 localtime_r( &_tmp_dt, &gmdt );
3783                                                 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
3784                                         }
3785
3786                                         jsonObjectSetIndex( object, fmIndex, jsonNewObject(dt_string) );
3787
3788                                         break;
3789
3790                                 case DBI_TYPE_BINARY :
3791                                         osrfLogError( OSRF_LOG_MARK, 
3792                                                 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
3793                         }
3794                 }
3795         }
3796
3797         return object;
3798 }
3799
3800 static jsonObject* oilsMakeJSONFromResult( dbi_result result ) {
3801         if(!result) return jsonNULL;
3802
3803         jsonObject* object = jsonNewObject(NULL);
3804
3805         time_t _tmp_dt;
3806         char dt_string[256];
3807         struct tm gmdt;
3808
3809         int fmIndex;
3810         int columnIndex = 1;
3811         int attr;
3812         unsigned short type;
3813         const char* columnName;
3814
3815         /* cycle through the column list */
3816         while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
3817
3818                 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
3819
3820                 fmIndex = -1; // reset the position
3821                 
3822                 /* determine the field type and storage attributes */
3823                 type = dbi_result_get_field_type(result, columnName);
3824                 attr = dbi_result_get_field_attribs(result, columnName);
3825
3826                 if (dbi_result_field_is_null(result, columnName)) {
3827                         jsonObjectSetKey( object, columnName, jsonNewObject(NULL) );
3828                 } else {
3829
3830                         switch( type ) {
3831
3832                                 case DBI_TYPE_INTEGER :
3833
3834                                         if( attr & DBI_INTEGER_SIZE8 ) 
3835                                                 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_longlong(result, columnName)) );
3836                                         else 
3837                                                 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_int(result, columnName)) );
3838                                         break;
3839
3840                                 case DBI_TYPE_DECIMAL :
3841                                         jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_double(result, columnName)) );
3842                                         break;
3843
3844                                 case DBI_TYPE_STRING :
3845                                         jsonObjectSetKey( object, columnName, jsonNewObject(dbi_result_get_string(result, columnName)) );
3846                                         break;
3847
3848                                 case DBI_TYPE_DATETIME :
3849
3850                                         memset(dt_string, '\0', sizeof(dt_string));
3851                                         memset(&gmdt, '\0', sizeof(gmdt));
3852
3853                                         _tmp_dt = dbi_result_get_datetime(result, columnName);
3854
3855
3856                                         if (!(attr & DBI_DATETIME_DATE)) {
3857                                                 gmtime_r( &_tmp_dt, &gmdt );
3858                                                 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
3859                                         } else if (!(attr & DBI_DATETIME_TIME)) {
3860                                                 localtime_r( &_tmp_dt, &gmdt );
3861                                                 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
3862                                         } else {
3863                                                 localtime_r( &_tmp_dt, &gmdt );
3864                                                 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
3865                                         }
3866
3867                                         jsonObjectSetKey( object, columnName, jsonNewObject(dt_string) );
3868                                         break;
3869
3870                                 case DBI_TYPE_BINARY :
3871                                         osrfLogError( OSRF_LOG_MARK, 
3872                                                 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
3873                         }
3874                 }
3875         }
3876
3877         return object;
3878 }
3879