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