Patch from Scott McKellar which plugs a couple of memory leaks, and
[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 "objson/object.h"
6 #include "opensrf/log.h"
7 #include "openils/oils_idl.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 #  define MODULENAME "open-ils.cstore"
19 #endif
20
21 #define DISABLE_I18N    2
22 #define SELECT_DISTINCT 1
23 #define AND_OP_JOIN     0
24 #define OR_OP_JOIN      1
25
26 int osrfAppChildInit();
27 int osrfAppInitialize();
28 void osrfAppChildExit();
29
30 static int verifyObjectClass ( osrfMethodContext*, const jsonObject* );
31
32 int beginTransaction ( osrfMethodContext* );
33 int commitTransaction ( osrfMethodContext* );
34 int rollbackTransaction ( osrfMethodContext* );
35
36 int setSavepoint ( osrfMethodContext* );
37 int releaseSavepoint ( osrfMethodContext* );
38 int rollbackSavepoint ( osrfMethodContext* );
39
40 int doJSONSearch ( osrfMethodContext* );
41
42 int dispatchCRUDMethod ( osrfMethodContext* );
43 static jsonObject* doCreate ( osrfMethodContext*, int* );
44 static jsonObject* doRetrieve ( osrfMethodContext*, int* );
45 static jsonObject* doUpdate ( osrfMethodContext*, int* );
46 static jsonObject* doDelete ( osrfMethodContext*, int* );
47 static jsonObject* doFieldmapperSearch ( osrfMethodContext*, osrfHash*,
48                 const jsonObject*, int* );
49 static jsonObject* oilsMakeFieldmapperFromResult( dbi_result, osrfHash* );
50 static jsonObject* oilsMakeJSONFromResult( dbi_result );
51
52 static char* searchWriteSimplePredicate ( const char*, osrfHash*,
53         const char*, const char*, const char* );
54 static char* searchSimplePredicate ( const char*, const char*, osrfHash*, const jsonObject* );
55 static char* searchFunctionPredicate ( const char*, osrfHash*, const jsonObjectNode* );
56 static char* searchFieldTransform ( const char*, osrfHash*, const jsonObject*);
57 static char* searchFieldTransformPredicate ( const char*, osrfHash*, jsonObjectNode* );
58 static char* searchBETWEENPredicate ( const char*, osrfHash*, jsonObject* );
59 static char* searchINPredicate ( const char*, osrfHash*, const jsonObject*, const char* );
60 static char* searchPredicate ( const char*, osrfHash*, jsonObject* );
61 static char* searchJOIN ( const jsonObject*, osrfHash* );
62 static char* searchWHERE ( const jsonObject*, osrfHash*, int );
63 static char* buildSELECT ( jsonObject*, jsonObject*, osrfHash*, osrfMethodContext* );
64
65 static char* SELECT ( osrfMethodContext*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, int );
66
67 void userDataFree( void* );
68 static void sessionDataFree( char*, void* );
69 static char* getSourceDefinition( osrfHash* );
70
71 static dbi_conn writehandle; /* our MASTER db connection */
72 static dbi_conn dbhandle; /* our CURRENT db connection */
73 osrfHash readHandles;
74 static jsonObject* jsonNULL = NULL; // 
75 static int max_flesh_depth = 100;
76
77 /* called when this process is about to exit */
78 void osrfAppChildExit() {
79         osrfLogDebug(OSRF_LOG_MARK, "Child is exiting, disconnecting from database...");
80
81         if (writehandle) {
82                 dbi_conn_query(writehandle, "ROLLBACK;");
83                 dbi_conn_close(writehandle);
84                 writehandle = NULL;
85         }
86
87         if (dbhandle)
88                 dbi_conn_close(dbhandle);
89
90         // XXX add cleanup of readHandles whenever that gets used
91
92         return;
93 }
94
95 int osrfAppInitialize() {
96         growing_buffer* method_name;
97
98         osrfLogInfo(OSRF_LOG_MARK, "Initializing the CStore Server...");
99         osrfLogInfo(OSRF_LOG_MARK, "Finding XML file...");
100
101         if (!oilsIDLInit( osrf_settings_host_value("/IDL") )) return 1; /* return non-zero to indicate error */
102
103         // Generic search thingy
104         method_name =  buffer_init(64);
105         buffer_fadd(method_name, "%s.json_query", MODULENAME);
106         char* method_str = buffer_data(method_name);
107         osrfAppRegisterMethod( MODULENAME, method_str, "doJSONSearch", "", 1, OSRF_METHOD_STREAMING );
108         free(method_str);
109
110         // first we register all the transaction and savepoint methods
111         buffer_reset(method_name);
112         buffer_fadd(method_name, "%s.transaction.begin", MODULENAME);
113         method_str = buffer_data(method_name);
114         osrfAppRegisterMethod( MODULENAME, method_str, "beginTransaction", "", 0, 0 );
115         free(method_str);
116
117         buffer_reset(method_name);
118         buffer_fadd(method_name, "%s.transaction.commit", MODULENAME);
119         method_str = buffer_data(method_name);
120         osrfAppRegisterMethod( MODULENAME, method_str, "commitTransaction", "", 0, 0 );
121         free(method_str);
122
123         buffer_reset(method_name);
124         buffer_fadd(method_name, "%s.transaction.rollback", MODULENAME);
125         method_str = buffer_data(method_name);
126         osrfAppRegisterMethod( MODULENAME, method_str, "rollbackTransaction", "", 0, 0 );
127         free(method_str);
128
129         buffer_reset(method_name);
130         buffer_fadd(method_name, "%s.savepoint.set", MODULENAME);
131         method_str = buffer_data(method_name);
132         osrfAppRegisterMethod( MODULENAME, method_str, "setSavepoint", "", 1, 0 );
133         free(method_str);
134
135         buffer_reset(method_name);
136         buffer_fadd(method_name, "%s.savepoint.release", MODULENAME);
137         method_str = buffer_data(method_name);
138         osrfAppRegisterMethod( MODULENAME, method_str, "releaseSavepoint", "", 1, 0 );
139         free(method_str);
140
141         buffer_reset(method_name);
142         buffer_fadd(method_name, "%s.savepoint.rollback", MODULENAME);
143         method_str = buffer_data(method_name);
144         osrfAppRegisterMethod( MODULENAME, method_str, "rollbackSavepoint", "", 1, 0 );
145         free(method_str);
146
147         buffer_free(method_name);
148
149         osrfStringArray* global_methods = osrfNewStringArray(6);
150
151         osrfStringArrayAdd( global_methods, "create" );
152         osrfStringArrayAdd( global_methods, "retrieve" );
153         osrfStringArrayAdd( global_methods, "update" );
154         osrfStringArrayAdd( global_methods, "delete" );
155         osrfStringArrayAdd( global_methods, "search" );
156         osrfStringArrayAdd( global_methods, "id_list" );
157
158         int c_index = 0; 
159         char* classname;
160         osrfStringArray* classes = osrfHashKeys( oilsIDL() );
161         osrfLogDebug(OSRF_LOG_MARK, "%d classes loaded", classes->size );
162         osrfLogDebug(OSRF_LOG_MARK, "At least %d methods will be generated", classes->size * global_methods->size);
163         
164         while ( (classname = osrfStringArrayGetString(classes, c_index++)) ) {
165                 osrfLogInfo(OSRF_LOG_MARK, "Generating class methods for %s", classname);
166                 
167                 osrfHash* idlClass = osrfHashGet(oilsIDL(), classname);
168
169                 if (!osrfStringArrayContains( osrfHashGet(idlClass, "controller"), MODULENAME )) {
170                         osrfLogInfo(OSRF_LOG_MARK, "%s is not listed as a controller for %s, moving on", MODULENAME, classname);
171                         continue;
172                 }
173
174                 char* virt = osrfHashGet(idlClass, "virtual");
175                 if (virt && !strcmp( virt, "true")) {
176                         osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
177                         continue;
178                 }
179
180                 int i = 0; 
181                 char* method_type;
182                 char* st_tmp;
183                 char* _fm;
184                 char* part;
185                 osrfHash* method_meta;
186                 while ( (method_type = osrfStringArrayGetString(global_methods, i++)) ) {
187                         osrfLogDebug(OSRF_LOG_MARK, "Using files to build %s class methods for %s", method_type, classname);
188
189                         if (!osrfHashGet(idlClass, "fieldmapper")) continue;
190
191                         char* readonly = osrfHashGet(idlClass, "readonly");
192                         if (    readonly &&
193                                 !strncasecmp( "true", readonly, 4) &&
194                                 ( *method_type == 'c' || *method_type == 'u' || *method_type == 'd')
195                         ) continue;
196
197                         method_meta = osrfNewHash();
198                         osrfHashSet(method_meta, idlClass, "class");
199
200                         _fm = strdup( (char*)osrfHashGet(idlClass, "fieldmapper") );
201                         part = strtok_r(_fm, ":", &st_tmp);
202
203                         growing_buffer* method_name =  buffer_init(64);
204                         buffer_fadd(method_name, "%s.direct.%s", MODULENAME, part);
205
206                         while ((part = strtok_r(NULL, ":", &st_tmp))) {
207                                 buffer_fadd(method_name, ".%s", part);
208                         }
209                         buffer_fadd(method_name, ".%s", method_type);
210
211
212                         char* method = buffer_release(method_name);
213                         free(_fm);
214
215                         osrfHashSet( method_meta, method, "methodname" );
216                         osrfHashSet( method_meta, strdup(method_type), "methodtype" );
217
218                         int flags = 0;
219                         if (!(strcmp( method_type, "search" )) || !(strcmp( method_type, "id_list" ))) {
220                                 flags = flags | OSRF_METHOD_STREAMING;
221                         }
222
223                         osrfAppRegisterExtendedMethod(
224                                 MODULENAME,
225                                 method,
226                                 "dispatchCRUDMethod",
227                                 "",
228                                 1,
229                                 flags,
230                                 (void*)method_meta
231                         );
232
233                         free(method);
234                 }
235         }
236
237         osrfStringArrayFree( global_methods );
238         return 0;
239 }
240
241 static char* getSourceDefinition( osrfHash* class ) {
242
243         char* tabledef = osrfHashGet(class, "tablename");
244
245         if (!tabledef) {
246                 growing_buffer* tablebuf = buffer_init(128);
247                 tabledef = osrfHashGet(class, "source_definition");
248                 if( !tabledef )
249                         tabledef = "(null)";
250                 buffer_fadd( tablebuf, "(%s)", tabledef );
251                 tabledef = buffer_release(tablebuf);
252         } else {
253                 tabledef = strdup(tabledef);
254         }
255
256         return tabledef;
257 }
258
259 /**
260  * Connects to the database 
261  */
262 int osrfAppChildInit() {
263
264         osrfLogDebug(OSRF_LOG_MARK, "Attempting to initialize libdbi...");
265         dbi_initialize(NULL);
266         osrfLogDebug(OSRF_LOG_MARK, "... libdbi initialized.");
267
268         char* driver    = osrf_settings_host_value("/apps/%s/app_settings/driver", MODULENAME);
269         char* user      = osrf_settings_host_value("/apps/%s/app_settings/database/user", MODULENAME);
270         char* host      = osrf_settings_host_value("/apps/%s/app_settings/database/host", MODULENAME);
271         char* port      = osrf_settings_host_value("/apps/%s/app_settings/database/port", MODULENAME);
272         char* db        = osrf_settings_host_value("/apps/%s/app_settings/database/db", MODULENAME);
273         char* pw        = osrf_settings_host_value("/apps/%s/app_settings/database/pw", MODULENAME);
274         char* md        = osrf_settings_host_value("/apps/%s/app_settings/max_query_recursion", MODULENAME);
275
276         osrfLogDebug(OSRF_LOG_MARK, "Attempting to load the database driver [%s]...", driver);
277         writehandle = dbi_conn_new(driver);
278
279         if(!writehandle) {
280                 osrfLogError(OSRF_LOG_MARK, "Error loading database driver [%s]", driver);
281                 return -1;
282         }
283         osrfLogDebug(OSRF_LOG_MARK, "Database driver [%s] seems OK", driver);
284
285         osrfLogInfo(OSRF_LOG_MARK, "%s connecting to database.  host=%s, "
286                 "port=%s, user=%s, pw=%s, db=%s", MODULENAME, host, port, user, pw, db );
287
288         if(host) dbi_conn_set_option(writehandle, "host", host );
289         if(port) dbi_conn_set_option_numeric( writehandle, "port", atoi(port) );
290         if(user) dbi_conn_set_option(writehandle, "username", user);
291         if(pw) dbi_conn_set_option(writehandle, "password", pw );
292         if(db) dbi_conn_set_option(writehandle, "dbname", db );
293
294         if(md) max_flesh_depth = atoi(md);
295         if(max_flesh_depth < 0) max_flesh_depth = 1;
296         if(max_flesh_depth > 1000) max_flesh_depth = 1000;
297
298         free(user);
299         free(host);
300         free(port);
301         free(db);
302         free(pw);
303
304         const char* err;
305         if (dbi_conn_connect(writehandle) < 0) {
306                 sleep(1);
307                 if (dbi_conn_connect(writehandle) < 0) {
308                         dbi_conn_error(writehandle, &err);
309                         osrfLogError( OSRF_LOG_MARK, "Error connecting to database: %s", err);
310                         return -1;
311                 }
312         }
313
314         osrfLogInfo(OSRF_LOG_MARK, "%s successfully connected to the database", MODULENAME);
315
316         int attr;
317         unsigned short type;
318         int i = 0; 
319         char* classname;
320         osrfStringArray* classes = osrfHashKeys( oilsIDL() );
321         
322         while ( (classname = osrfStringArrayGetString(classes, i++)) ) {
323                 osrfHash* class = osrfHashGet( oilsIDL(), classname );
324                 osrfHash* fields = osrfHashGet( class, "fields" );
325
326                 char* virt = osrfHashGet(class, "virtual");
327                 if (virt && !strcmp( virt, "true")) {
328                         osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
329                         continue;
330                 }
331
332                 char* tabledef = getSourceDefinition(class);
333
334                 growing_buffer* sql_buf = buffer_init(32);
335                 buffer_fadd( sql_buf, "SELECT * FROM %s AS x WHERE 1=0;", tabledef );
336
337                 free(tabledef);
338
339                 char* sql = buffer_release(sql_buf);
340                 osrfLogDebug(OSRF_LOG_MARK, "%s Investigatory SQL = %s", MODULENAME, sql);
341
342                 dbi_result result = dbi_conn_query(writehandle, sql);
343                 free(sql);
344
345                 if (result) {
346
347                         int columnIndex = 1;
348                         const char* columnName;
349                         osrfHash* _f;
350                         while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
351
352                                 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
353
354                                 /* fetch the fieldmapper index */
355                                 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
356
357                                         osrfLogDebug(OSRF_LOG_MARK, "Found [%s] in IDL hash...", (char*)columnName);
358
359                                         /* determine the field type and storage attributes */
360                                         type = dbi_result_get_field_type(result, columnName);
361                                         attr = dbi_result_get_field_attribs(result, columnName);
362
363                                         switch( type ) {
364
365                                                 case DBI_TYPE_INTEGER :
366
367                                                         if ( !osrfHashGet(_f, "primitive") )
368                                                                 osrfHashSet(_f,"number", "primitive");
369
370                                                         if( attr & DBI_INTEGER_SIZE8 ) 
371                                                                 osrfHashSet(_f,"INT8", "datatype");
372                                                         else 
373                                                                 osrfHashSet(_f,"INT", "datatype");
374                                                         break;
375
376                                                 case DBI_TYPE_DECIMAL :
377                                                         if ( !osrfHashGet(_f, "primitive") )
378                                                                 osrfHashSet(_f,"number", "primitive");
379
380                                                         osrfHashSet(_f,"NUMERIC", "datatype");
381                                                         break;
382
383                                                 case DBI_TYPE_STRING :
384                                                         if ( !osrfHashGet(_f, "primitive") )
385                                                                 osrfHashSet(_f,"string", "primitive");
386                                                         osrfHashSet(_f,"TEXT", "datatype");
387                                                         break;
388
389                                                 case DBI_TYPE_DATETIME :
390                                                         if ( !osrfHashGet(_f, "primitive") )
391                                                                 osrfHashSet(_f,"string", "primitive");
392
393                                                         osrfHashSet(_f,"TIMESTAMP", "datatype");
394                                                         break;
395
396                                                 case DBI_TYPE_BINARY :
397                                                         if ( !osrfHashGet(_f, "primitive") )
398                                                                 osrfHashSet(_f,"string", "primitive");
399
400                                                         osrfHashSet(_f,"BYTEA", "datatype");
401                                         }
402
403                                         osrfLogDebug(
404                                                 OSRF_LOG_MARK,
405                                                 "Setting [%s] to primitive [%s] and datatype [%s]...",
406                                                 (char*)columnName,
407                                                 osrfHashGet(_f, "primitive"),
408                                                 osrfHashGet(_f, "datatype")
409                                         );
410                                 }
411                         }
412                         dbi_result_free(result);
413                 } else {
414                         osrfLogDebug(OSRF_LOG_MARK, "No data found for class [%s]...", (char*)classname);
415                 }
416         }
417
418         osrfStringArrayFree(classes);
419
420         return 0;
421 }
422
423 void userDataFree( void* blob ) {
424         osrfHashFree( (osrfHash*)blob );
425         return;
426 }
427
428 static void sessionDataFree( char* key, void* item ) {
429         if (!(strcmp(key,"xact_id"))) {
430                 if (writehandle)
431                         dbi_conn_query(writehandle, "ROLLBACK;");
432                 free(item);
433         }
434
435         return;
436 }
437
438 int beginTransaction ( osrfMethodContext* ctx ) {
439         OSRF_METHOD_VERIFY_CONTEXT(ctx);
440
441         dbi_result result = dbi_conn_query(writehandle, "START TRANSACTION;");
442         if (!result) {
443                 osrfLogError(OSRF_LOG_MARK, "%s: Error starting transaction", MODULENAME );
444                 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error starting transaction" );
445                 return -1;
446         } else {
447                 jsonObject* ret = jsonNewObject(ctx->session->session_id);
448                 osrfAppRespondComplete( ctx, ret );
449                 jsonObjectFree(ret);
450                 
451                 if (!ctx->session->userData) {
452                         ctx->session->userData = osrfNewHash();
453                         ((osrfHash*)ctx->session->userData)->freeItem = &sessionDataFree;
454                 }
455
456                 osrfHashSet( (osrfHash*)ctx->session->userData, strdup( ctx->session->session_id ), "xact_id" );
457                 ctx->session->userDataFree = &userDataFree;
458                 
459         }
460         return 0;
461 }
462
463 int setSavepoint ( osrfMethodContext* ctx ) {
464         OSRF_METHOD_VERIFY_CONTEXT(ctx);
465
466         if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
467                 osrfAppSessionStatus(
468                         ctx->session,
469                         OSRF_STATUS_INTERNALSERVERERROR,
470                         "osrfMethodException",
471                         ctx->request,
472                         "No active transaction -- required for savepoints"
473                 );
474                 return -1;
475         }
476
477         char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
478
479         dbi_result result = dbi_conn_queryf(writehandle, "SAVEPOINT \"%s\";", spName);
480         if (!result) {
481                 osrfLogError(
482                         OSRF_LOG_MARK,
483                         "%s: Error creating savepoint %s in transaction %s",
484                         MODULENAME,
485                         spName,
486                         osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
487                 );
488                 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error creating savepoint" );
489                 free(spName);
490                 return -1;
491         } else {
492                 jsonObject* ret = jsonNewObject(spName);
493                 osrfAppRespondComplete( ctx, ret );
494                 jsonObjectFree(ret);
495         }
496         free(spName);
497         return 0;
498 }
499
500 int releaseSavepoint ( osrfMethodContext* ctx ) {
501         OSRF_METHOD_VERIFY_CONTEXT(ctx);
502
503         if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
504                 osrfAppSessionStatus(
505                         ctx->session,
506                         OSRF_STATUS_INTERNALSERVERERROR,
507                         "osrfMethodException",
508                         ctx->request,
509                         "No active transaction -- required for savepoints"
510                 );
511                 return -1;
512         }
513
514         char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
515
516         dbi_result result = dbi_conn_queryf(writehandle, "RELEASE SAVEPOINT \"%s\";", spName);
517         if (!result) {
518                 osrfLogError(
519                         OSRF_LOG_MARK,
520                         "%s: Error releasing savepoint %s in transaction %s",
521                         MODULENAME,
522                         spName,
523                         osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
524                 );
525                 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error releasing savepoint" );
526                 free(spName);
527                 return -1;
528         } else {
529                 jsonObject* ret = jsonNewObject(spName);
530                 osrfAppRespondComplete( ctx, ret );
531                 jsonObjectFree(ret);
532         }
533         free(spName);
534         return 0;
535 }
536
537 int rollbackSavepoint ( osrfMethodContext* ctx ) {
538         OSRF_METHOD_VERIFY_CONTEXT(ctx);
539
540         if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
541                 osrfAppSessionStatus(
542                         ctx->session,
543                         OSRF_STATUS_INTERNALSERVERERROR,
544                         "osrfMethodException",
545                         ctx->request,
546                         "No active transaction -- required for savepoints"
547                 );
548                 return -1;
549         }
550
551         char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
552
553         dbi_result result = dbi_conn_queryf(writehandle, "ROLLBACK TO SAVEPOINT \"%s\";", spName);
554         if (!result) {
555                 osrfLogError(
556                         OSRF_LOG_MARK,
557                         "%s: Error rolling back savepoint %s in transaction %s",
558                         MODULENAME,
559                         spName,
560                         osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
561                 );
562                 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back savepoint" );
563                 free(spName);
564                 return -1;
565         } else {
566                 jsonObject* ret = jsonNewObject(spName);
567                 osrfAppRespondComplete( ctx, ret );
568                 jsonObjectFree(ret);
569         }
570         free(spName);
571         return 0;
572 }
573
574 int commitTransaction ( osrfMethodContext* ctx ) {
575         OSRF_METHOD_VERIFY_CONTEXT(ctx);
576
577         if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
578                 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to commit" );
579                 return -1;
580         }
581
582         dbi_result result = dbi_conn_query(writehandle, "COMMIT;");
583         if (!result) {
584                 osrfLogError(OSRF_LOG_MARK, "%s: Error committing transaction", MODULENAME );
585                 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error committing transaction" );
586                 return -1;
587         } else {
588                 osrfHashRemove(ctx->session->userData, "xact_id");
589                 jsonObject* ret = jsonNewObject(ctx->session->session_id);
590                 osrfAppRespondComplete( ctx, ret );
591                 jsonObjectFree(ret);
592         }
593         return 0;
594 }
595
596 int rollbackTransaction ( osrfMethodContext* ctx ) {
597         OSRF_METHOD_VERIFY_CONTEXT(ctx);
598
599         if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
600                 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to roll back" );
601                 return -1;
602         }
603
604         dbi_result result = dbi_conn_query(writehandle, "ROLLBACK;");
605         if (!result) {
606                 osrfLogError(OSRF_LOG_MARK, "%s: Error rolling back transaction", MODULENAME );
607                 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back transaction" );
608                 return -1;
609         } else {
610                 osrfHashRemove(ctx->session->userData, "xact_id");
611                 jsonObject* ret = jsonNewObject(ctx->session->session_id);
612                 osrfAppRespondComplete( ctx, ret );
613                 jsonObjectFree(ret);
614         }
615         return 0;
616 }
617
618 int dispatchCRUDMethod ( osrfMethodContext* ctx ) {
619         OSRF_METHOD_VERIFY_CONTEXT(ctx);
620
621         osrfHash* meta = (osrfHash*) ctx->method->userData;
622         osrfHash* class_obj = osrfHashGet( meta, "class" );
623         
624         int err = 0;
625
626         const char* methodtype = osrfHashGet(meta, "methodtype");
627         jsonObject * obj = NULL;
628
629         if (!strcmp(methodtype, "create")) {
630                 obj = doCreate(ctx, &err);
631                 osrfAppRespondComplete( ctx, obj );
632         }
633         else if (!strcmp(methodtype, "retrieve")) {
634                 obj = doRetrieve(ctx, &err);
635                 osrfAppRespondComplete( ctx, obj );
636         }
637         else if (!strcmp(methodtype, "update")) {
638                 obj = doUpdate(ctx, &err);
639                 osrfAppRespondComplete( ctx, obj );
640         }
641         else if (!strcmp(methodtype, "delete")) {
642                 obj = doDelete(ctx, &err);
643                 osrfAppRespondComplete( ctx, obj );
644         }
645         else if (!strcmp(methodtype, "search")) {
646
647                 obj = doFieldmapperSearch(ctx, class_obj, ctx->params, &err);
648                 if(err) return err;
649
650                 jsonObjectNode* cur;
651                 jsonObjectIterator* itr = jsonNewObjectIterator( obj );
652                 while ((cur = jsonObjectIteratorNext( itr ))) {
653                         osrfAppRespond( ctx, cur->item );
654                 }
655                 jsonObjectIteratorFree(itr);
656                 osrfAppRespondComplete( ctx, NULL );
657
658         } else if (!strcmp(methodtype, "id_list")) {
659
660                 jsonObject* _p = jsonObjectClone( ctx->params );
661                 if (jsonObjectGetIndex( _p, 1 )) {
662                         jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh" );
663                         jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh_columns" );
664                 } else {
665                         jsonObjectSetIndex( _p, 1, jsonParseString("{}") );
666                 }
667
668                 growing_buffer* sel_list = buffer_init(64);
669                 buffer_fadd(sel_list, "{ \"%s\":[\"%s\"] }", osrfHashGet( class_obj, "classname" ), osrfHashGet( class_obj, "primarykey" ));
670                 char* _s = buffer_release(sel_list);
671
672                 jsonObjectSetKey( jsonObjectGetIndex( _p, 1 ), "select", jsonParseString(_s) );
673                 osrfLogDebug(OSRF_LOG_MARK, "%s: Select qualifer set to [%s]", MODULENAME, _s);
674                 free(_s);
675
676                 obj = doFieldmapperSearch(ctx, class_obj, _p, &err);
677                 jsonObjectFree(_p);
678                 if(err) return err;
679
680                 jsonObjectNode* cur;
681                 jsonObjectIterator* itr = jsonNewObjectIterator( obj );
682                 while ((cur = jsonObjectIteratorNext( itr ))) {
683                         osrfAppRespond(
684                                 ctx,
685                                 jsonObjectGetIndex(
686                                         cur->item,
687                                         atoi(
688                                                 osrfHashGet(
689                                                         osrfHashGet(
690                                                                 osrfHashGet( class_obj, "fields" ),
691                                                                 osrfHashGet( class_obj, "primarykey")
692                                                         ),
693                                                         "array_position"
694                                                 )
695                                         )
696                                 )
697                         );
698                 }
699                 jsonObjectIteratorFree(itr);
700                 osrfAppRespondComplete( ctx, NULL );
701                 
702         } else {
703                 osrfAppRespondComplete( ctx, obj );
704         }
705
706         jsonObjectFree(obj);
707
708         return err;
709 }
710
711 static int verifyObjectClass ( osrfMethodContext* ctx, const jsonObject* param ) {
712         
713         osrfHash* meta = (osrfHash*) ctx->method->userData;
714         osrfHash* class = osrfHashGet( meta, "class" );
715         
716         if (!param->classname || (strcmp( osrfHashGet(class, "classname"), param->classname ))) {
717
718                 growing_buffer* msg = buffer_init(128);
719                 buffer_fadd(
720                         msg,
721                         "%s: %s method for type %s was passed a %s",
722                         MODULENAME,
723                         osrfHashGet(meta, "methodtype"),
724                         osrfHashGet(class, "classname"),
725                         param->classname
726                 );
727
728                 char* m = buffer_release(msg);
729                 osrfAppSessionStatus( ctx->session, OSRF_STATUS_BADREQUEST, "osrfMethodException", ctx->request, m );
730
731                 free(m);
732
733                 return 0;
734         }
735         return 1;
736 }
737
738 static jsonObject* doCreate(osrfMethodContext* ctx, int* err ) {
739
740         osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
741         jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
742         jsonObject* options = jsonObjectGetIndex( ctx->params, 1 );
743
744         if (!verifyObjectClass(ctx, target)) {
745                 *err = -1;
746                 return jsonNULL;
747         }
748
749         osrfLogDebug( OSRF_LOG_MARK, "Object seems to be of the correct type" );
750
751         if (!ctx->session || !ctx->session->userData || !osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
752                 osrfLogError( OSRF_LOG_MARK, "No active transaction -- required for CREATE" );
753
754                 osrfAppSessionStatus(
755                         ctx->session,
756                         OSRF_STATUS_BADREQUEST,
757                         "osrfMethodException",
758                         ctx->request,
759                         "No active transaction -- required for CREATE"
760                 );
761                 *err = -1;
762                 return jsonNULL;
763         }
764
765         if (osrfHashGet( meta, "readonly" ) && strncasecmp("true", osrfHashGet( meta, "readonly" ), 4)) {
766                 osrfAppSessionStatus(
767                         ctx->session,
768                         OSRF_STATUS_BADREQUEST,
769                         "osrfMethodException",
770                         ctx->request,
771                         "Cannot INSERT readonly class"
772                 );
773                 *err = -1;
774                 return jsonNULL;
775         }
776
777
778         char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
779
780         // Set the last_xact_id
781         osrfHash* last_xact_id;
782         if ((last_xact_id = oilsIDLFindPath("/%s/fields/last_xact_id", target->classname))) {
783                 int index = atoi( osrfHashGet(last_xact_id, "array_position") );
784                 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
785                 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
786         }       
787
788         osrfLogDebug( OSRF_LOG_MARK, "There is a transaction running..." );
789
790         dbhandle = writehandle;
791
792         osrfHash* fields = osrfHashGet(meta, "fields");
793         char* pkey = osrfHashGet(meta, "primarykey");
794         char* seq = osrfHashGet(meta, "sequence");
795
796         growing_buffer* table_buf = buffer_init(128);
797         growing_buffer* col_buf = buffer_init(128);
798         growing_buffer* val_buf = buffer_init(128);
799
800         buffer_fadd(table_buf,"INSERT INTO %s", osrfHashGet(meta, "tablename"));
801         buffer_add(col_buf,"(");
802         buffer_add(val_buf,"VALUES (");
803
804
805         int i = 0;
806         int first = 1;
807         char* field_name;
808         osrfStringArray* field_list = osrfHashKeys( fields );
809         while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
810
811                 osrfHash* field = osrfHashGet( fields, field_name );
812
813                 if(!( strcmp( osrfHashGet(osrfHashGet(fields,field_name), "virtual"), "true" ) )) continue;
814
815                 jsonObject* field_object = jsonObjectGetIndex( target, atoi(osrfHashGet(field, "array_position")) );
816
817                 char* value;
818                 if (field_object && field_object->classname) {
819                         value = jsonObjectToSimpleString(
820                                         jsonObjectGetIndex(
821                                                 field_object,
822                                                 atoi(
823                                                         osrfHashGet(
824                                                                 osrfHashGet(
825                                                                         oilsIDLFindPath("/%s/fields", field_object->classname),
826                                                                         (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
827                                                                 ),
828                                                                 "array_position"
829                                                         )
830                                                 )
831                                         )
832                                 );
833
834                 } else {
835                         value = jsonObjectToSimpleString( field_object );
836                 }
837
838
839                 if (first) {
840                         first = 0;
841                 } else {
842                         buffer_add(col_buf, ",");
843                         buffer_add(val_buf, ",");
844                 }
845
846                 buffer_add(col_buf, field_name);
847
848                 if (!field_object || field_object->type == JSON_NULL) {
849                         buffer_add( val_buf, "DEFAULT" );
850                         
851                 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
852                         if ( !strcmp(osrfHashGet(field, "datatype"), "INT8") ) {
853                                 buffer_fadd( val_buf, "%lld", atoll(value) );
854                                 
855                         } else if ( !strcmp(osrfHashGet(field, "datatype"), "INT") ) {
856                                 buffer_fadd( val_buf, "%d", atoi(value) );
857                                 
858                         } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
859                                 buffer_fadd( val_buf, "%f", atof(value) );
860                         }
861                 } else {
862                         if ( dbi_conn_quote_string(writehandle, &value) ) {
863                                 buffer_fadd( val_buf, "%s", value );
864
865                         } else {
866                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
867                                 osrfAppSessionStatus(
868                                         ctx->session,
869                                         OSRF_STATUS_INTERNALSERVERERROR,
870                                         "osrfMethodException",
871                                         ctx->request,
872                                         "Error quoting string -- please see the error log for more details"
873                                 );
874                                 free(value);
875                                 buffer_free(table_buf);
876                                 buffer_free(col_buf);
877                                 buffer_free(val_buf);
878                                 *err = -1;
879                                 return jsonNULL;
880                         }
881                 }
882
883                 free(value);
884                 
885         }
886
887
888         buffer_add(col_buf,")");
889         buffer_add(val_buf,")");
890
891         char* table_str = buffer_release(table_buf);
892         char* col_str   = buffer_release(col_buf);
893         char* val_str   = buffer_release(val_buf);
894         growing_buffer* sql = buffer_init(128);
895         buffer_fadd( sql, "%s %s %s;", table_str, col_str, val_str );
896         free(table_str);
897         free(col_str);
898         free(val_str);
899
900         char* query = buffer_release(sql);
901
902         osrfLogDebug(OSRF_LOG_MARK, "%s: Insert SQL [%s]", MODULENAME, query);
903
904         
905         dbi_result result = dbi_conn_query(writehandle, query);
906
907         jsonObject* obj = NULL;
908
909         if (!result) {
910                 obj = jsonNewObject(NULL);
911                 osrfLogError(
912                         OSRF_LOG_MARK,
913                         "%s ERROR inserting %s object using query [%s]",
914                         MODULENAME,
915                         osrfHashGet(meta, "fieldmapper"),
916                         query
917                 );
918                 osrfAppSessionStatus(
919                         ctx->session,
920                         OSRF_STATUS_INTERNALSERVERERROR,
921                         "osrfMethodException",
922                         ctx->request,
923                         "INSERT error -- please see the error log for more details"
924                 );
925                 *err = -1;
926         } else {
927
928                 int pos = atoi(osrfHashGet( osrfHashGet(fields, pkey), "array_position" ));
929                 char* id = jsonObjectToSimpleString(jsonObjectGetIndex(target, pos));
930                 if (!id) {
931                         unsigned long long new_id = dbi_conn_sequence_last(writehandle, seq);
932                         growing_buffer* _id = buffer_init(10);
933                         buffer_fadd(_id, "%lld", new_id);
934                         id = buffer_release(_id);
935                 }
936
937                 // Find quietness specification, if present
938                 char* quiet_str = NULL;
939                 if ( options ) {
940                         const jsonObject* quiet_obj = jsonObjectGetKeyConst( options, "quiet" );
941                         if( quiet_obj )
942                                 quiet_str = jsonObjectToSimpleString( quiet_obj );
943                 }
944
945                 if( quiet_str && !strcmp( quiet_str, "true" )) {  // if quietness is specified
946                         obj = jsonNewObject(id);
947                 }
948                 else {
949
950                         jsonObject* fake_params = jsonParseString("[]");
951                         jsonObjectPush(fake_params, jsonParseString("{}"));
952
953                         jsonObjectSetKey(
954                                 jsonObjectGetIndex(fake_params, 0),
955                                 osrfHashGet(meta, "primarykey"),
956                                 jsonNewObject(id)
957                         );
958
959                         jsonObject* list = doFieldmapperSearch( ctx,meta, fake_params, err);
960
961                         if(*err) {
962                                 jsonObjectFree( fake_params );
963                                 obj = jsonNULL;
964                         } else {
965                                 obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
966                         }
967
968                         jsonObjectFree( list );
969                         jsonObjectFree( fake_params );
970                 }
971
972                 if(quiet_str) free(quiet_str);
973                 free(id);
974         }
975
976         free(query);
977
978         return obj;
979
980 }
981
982
983 static jsonObject* doRetrieve(osrfMethodContext* ctx, int* err ) {
984
985         osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
986
987         jsonObject* obj;
988
989         char* id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
990         jsonObject* order_hash = jsonObjectGetIndex(ctx->params, 1);
991
992         osrfLogDebug(
993                 OSRF_LOG_MARK,
994                 "%s retrieving %s object with id %s",
995                 MODULENAME,
996                 osrfHashGet(meta, "fieldmapper"),
997                 id
998         );
999
1000         jsonObject* fake_params = jsonParseString("[]");
1001         jsonObjectPush(fake_params, jsonParseString("{}"));
1002
1003         jsonObjectSetKey(
1004                 jsonObjectGetIndex(fake_params, 0),
1005                 osrfHashGet(meta, "primarykey"),
1006                 jsonParseString(id)
1007         );
1008
1009         free(id);
1010
1011         if (order_hash) jsonObjectPush(fake_params, jsonObjectClone(order_hash) );
1012
1013         jsonObject* list = doFieldmapperSearch( ctx,meta, fake_params, err);
1014
1015         if(*err) {
1016                 jsonObjectFree( fake_params );
1017                 return jsonNULL;
1018         }
1019
1020         obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
1021
1022         jsonObjectFree( list );
1023         jsonObjectFree( fake_params );
1024
1025         return obj;
1026 }
1027
1028 static char* jsonNumberToDBString ( osrfHash* field, const jsonObject* value ) {
1029         growing_buffer* val_buf = buffer_init(32);
1030
1031         if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
1032                 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%ld", (long)jsonObjectGetNumber(value) );
1033                 else {
1034                         char* val_str = jsonObjectToSimpleString(value);
1035                         buffer_fadd( val_buf, "%ld", atol(val_str) );
1036                         free(val_str);
1037                 }
1038
1039         } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
1040                 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%f",  jsonObjectGetNumber(value) );
1041                 else {
1042                         char* val_str = jsonObjectToSimpleString(value);
1043                         buffer_fadd( val_buf, "%f", atof(val_str) );
1044                         free(val_str);
1045                 }
1046         }
1047
1048         return buffer_release(val_buf);
1049 }
1050
1051 static char* searchINPredicate (const char* class, osrfHash* field,
1052                 const jsonObject* node, const char* op) {
1053         growing_buffer* sql_buf = buffer_init(32);
1054         
1055         buffer_fadd(
1056                 sql_buf,
1057                 "\"%s\".%s ",
1058                 class,
1059                 osrfHashGet(field, "name")
1060         );
1061
1062         if (!op) {
1063                 buffer_add(sql_buf, "IN (");
1064         } else if (!(strcasecmp(op,"not in"))) {
1065                 buffer_add(sql_buf, "NOT IN (");
1066         } else {
1067                 buffer_add(sql_buf, "IN (");
1068         }
1069
1070         int in_item_index = 0;
1071         int in_item_first = 1;
1072         jsonObject* in_item;
1073         while ( (in_item = jsonObjectGetIndex(node, in_item_index++)) ) {
1074
1075                 if (in_item_first)
1076                         in_item_first = 0;
1077                 else
1078                         buffer_add(sql_buf, ", ");
1079
1080                 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1081                         char* val = jsonNumberToDBString( field, in_item );
1082                         buffer_fadd( sql_buf, "%s", val );
1083                         free(val);
1084
1085                 } else {
1086                         char* key_string = jsonObjectToSimpleString(in_item);
1087                         if ( dbi_conn_quote_string(dbhandle, &key_string) ) {
1088                                 buffer_fadd( sql_buf, "%s", key_string );
1089                                 free(key_string);
1090                         } else {
1091                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, key_string);
1092                                 free(key_string);
1093                                 buffer_free(sql_buf);
1094                                 return NULL;
1095                         }
1096                 }
1097         }
1098
1099         buffer_add(
1100                 sql_buf,
1101                 ")"
1102         );
1103
1104         return buffer_release(sql_buf);
1105 }
1106
1107 static char* searchValueTransform( const jsonObject* array ) {
1108         growing_buffer* sql_buf = buffer_init(32);
1109
1110         char* val = NULL;
1111         int func_item_index = 0;
1112         int func_item_first = 2;
1113         jsonObject* func_item;
1114         while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1115
1116                 val = jsonObjectToSimpleString(func_item);
1117
1118                 if (func_item_first == 2) {
1119                         buffer_fadd(sql_buf, "%s( ", val);
1120                         free(val);
1121                         func_item_first--;
1122                         continue;
1123                 }
1124
1125                 if (func_item_first)
1126                         func_item_first--;
1127                 else
1128                         buffer_add(sql_buf, ", ");
1129
1130                 if ( dbi_conn_quote_string(dbhandle, &val) ) {
1131                         buffer_fadd( sql_buf, "%s", val );
1132                         free(val);
1133                 } else {
1134                         osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1135                         free(val);
1136                         buffer_free(sql_buf);
1137                         return NULL;
1138                 }
1139         }
1140
1141         buffer_add(
1142                 sql_buf,
1143                 " )"
1144         );
1145
1146         return buffer_release(sql_buf);
1147 }
1148
1149 static char* searchFunctionPredicate (const char* class, osrfHash* field,
1150                 const jsonObjectNode* node) {
1151         growing_buffer* sql_buf = buffer_init(32);
1152
1153         char* val = searchValueTransform(node->item);
1154         
1155         buffer_fadd(
1156                 sql_buf,
1157                 "\"%s\".%s %s %s",
1158                 class,
1159                 osrfHashGet(field, "name"),
1160                 node->key,
1161                 val
1162         );
1163
1164         free(val);
1165
1166         return buffer_release(sql_buf);
1167 }
1168
1169 static char* searchFieldTransform (const char* class, osrfHash* field, const jsonObject* node) {
1170         growing_buffer* sql_buf = buffer_init(32);
1171         
1172         char* field_transform = jsonObjectToSimpleString( jsonObjectGetKeyConst( node, "transform" ) );
1173         char* transform_subcolumn = jsonObjectToSimpleString( jsonObjectGetKeyConst( node, "result_field" ) );
1174
1175         if (field_transform) {
1176                 buffer_fadd( sql_buf, "%s(\"%s\".%s", field_transform, class, osrfHashGet(field, "name"));
1177             const jsonObject* array = jsonObjectGetKeyConst( node, "params" );
1178
1179         if (array) {
1180                 int func_item_index = 0;
1181                 jsonObject* func_item;
1182                 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1183
1184                         char* val = jsonObjectToSimpleString(func_item);
1185
1186                     if ( dbi_conn_quote_string(dbhandle, &val) ) {
1187                             buffer_fadd( sql_buf, ",%s", val );
1188                         } else {
1189                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1190                             free(field_transform);
1191                                         free(val);
1192                                 buffer_free(sql_buf);
1193                                 return NULL;
1194                 }
1195                                 free(val);
1196                         }
1197
1198         }
1199
1200         buffer_add(
1201                 sql_buf,
1202                 " )"
1203         );
1204
1205         } else {
1206                 buffer_fadd( sql_buf, "\"%s\".%s", class, osrfHashGet(field, "name"));
1207         }
1208
1209     if (transform_subcolumn) {
1210         char * tmp = buffer_release(sql_buf);
1211         sql_buf = buffer_init(32);
1212         buffer_fadd(
1213             sql_buf,
1214             "(%s).\"%s\"",
1215             tmp,
1216             transform_subcolumn
1217         );
1218         free(tmp);
1219     }
1220  
1221         if (field_transform) free(field_transform);
1222         if (transform_subcolumn) free(transform_subcolumn);
1223
1224         return buffer_release(sql_buf);
1225 }
1226
1227 static char* searchFieldTransformPredicate (const char* class, osrfHash* field, jsonObjectNode* node) {
1228         char* field_transform = searchFieldTransform( class, field, node->item );
1229         char* value = NULL;
1230
1231         if (!jsonObjectGetKeyConst( node->item, "value" )) {
1232                 value = searchWHERE( node->item, osrfHashGet( oilsIDL(), class ), AND_OP_JOIN );
1233         } else if (jsonObjectGetKeyConst( node->item, "value" )->type == JSON_ARRAY) {
1234                 value = searchValueTransform(jsonObjectGetKeyConst( node->item, "value" ));
1235         } else if (jsonObjectGetKeyConst( node->item, "value" )->type == JSON_HASH) {
1236                 value = searchWHERE( jsonObjectGetKeyConst( node->item, "value" ), osrfHashGet( oilsIDL(), class ), AND_OP_JOIN );
1237         } else if (jsonObjectGetKeyConst( node->item, "value" )->type != JSON_NULL) {
1238                 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1239                         value = jsonNumberToDBString( field, jsonObjectGetKeyConst( node->item, "value" ) );
1240                 } else {
1241                         value = jsonObjectToSimpleString(jsonObjectGetKeyConst( node->item, "value" ));
1242                         if ( !dbi_conn_quote_string(dbhandle, &value) ) {
1243                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, value);
1244                                 free(value);
1245                                 free(field_transform);
1246                                 return NULL;
1247                         }
1248                 }
1249         }
1250
1251         growing_buffer* sql_buf = buffer_init(32);
1252         
1253         buffer_fadd(
1254                 sql_buf,
1255                 "%s %s %s",
1256                 field_transform,
1257                 node->key,
1258                 value
1259         );
1260
1261         free(value);
1262         free(field_transform);
1263
1264         return buffer_release(sql_buf);
1265 }
1266
1267 static char* searchSimplePredicate (const char* orig_op, const char* class,
1268                 osrfHash* field, const jsonObject* node) {
1269
1270         char* val = NULL;
1271
1272         if (node->type != JSON_NULL) {
1273                 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1274                         val = jsonNumberToDBString( field, node );
1275                 } else {
1276                         val = jsonObjectToSimpleString(node);
1277                 }
1278         }
1279
1280         char* pred = searchWriteSimplePredicate( class, field, osrfHashGet(field, "name"), orig_op, val );
1281
1282         if (val) free(val);
1283
1284         return pred;
1285 }
1286
1287 static char* searchWriteSimplePredicate ( const char* class, osrfHash* field,
1288         const char* left, const char* orig_op, const char* right ) {
1289
1290         char* val = NULL;
1291         char* op = NULL;
1292         if (right == NULL) {
1293                 val = strdup("NULL");
1294
1295                 if (strcmp( orig_op, "=" ))
1296                         op = strdup("IS NOT");
1297                 else
1298                         op = strdup("IS");
1299
1300         } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1301                 val = strdup(right);
1302                 op = strdup(orig_op);
1303
1304         } else {
1305                 val = strdup(right);
1306                 if ( !dbi_conn_quote_string(dbhandle, &val) ) {
1307                         osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1308                         free(val);
1309                         return NULL;
1310                 }
1311                 op = strdup(orig_op);
1312         }
1313
1314         growing_buffer* sql_buf = buffer_init(16);
1315         buffer_fadd( sql_buf, "\"%s\".%s %s %s", class, left, op, val );
1316         free(val);
1317         free(op);
1318
1319         return buffer_release(sql_buf);
1320 }
1321
1322 static char* searchBETWEENPredicate (const char* class, osrfHash* field, jsonObject* node) {
1323
1324         char* x_string;
1325         char* y_string;
1326
1327         if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1328                 x_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,0));
1329                 y_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,1));
1330
1331         } else {
1332                 x_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,0));
1333                 y_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,1));
1334                 if ( !(dbi_conn_quote_string(dbhandle, &x_string) && dbi_conn_quote_string(dbhandle, &y_string)) ) {
1335                         osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key strings [%s] and [%s]", MODULENAME, x_string, y_string);
1336                         free(x_string);
1337                         free(y_string);
1338                         return NULL;
1339                 }
1340         }
1341
1342         growing_buffer* sql_buf = buffer_init(32);
1343         buffer_fadd( sql_buf, "%s BETWEEN %s AND %s", osrfHashGet(field, "name"), x_string, y_string );
1344         free(x_string);
1345         free(y_string);
1346
1347         return buffer_release(sql_buf);
1348 }
1349
1350 static char* searchPredicate ( const char* class, osrfHash* field, jsonObject* node ) {
1351
1352         char* pred = NULL;
1353         if (node->type == JSON_ARRAY) { // equality IN search
1354                 pred = searchINPredicate( class, field, node, NULL );
1355         } else if (node->type == JSON_HASH) { // non-equality search
1356                 jsonObjectNode* pred_node;
1357                 jsonObjectIterator* pred_itr = jsonNewObjectIterator( node );
1358                 while ( (pred_node = jsonObjectIteratorNext( pred_itr )) ) {
1359                         if ( !(strcasecmp( pred_node->key,"between" )) )
1360                                 pred = searchBETWEENPredicate( class, field, pred_node->item );
1361                         else if ( !(strcasecmp( pred_node->key,"in" )) || !(strcasecmp( pred_node->key,"not in" )) )
1362                                 pred = searchINPredicate( class, field, pred_node->item, pred_node->key );
1363                         else if ( pred_node->item->type == JSON_ARRAY )
1364                                 pred = searchFunctionPredicate( class, field, pred_node );
1365                         else if ( pred_node->item->type == JSON_HASH )
1366                                 pred = searchFieldTransformPredicate( class, field, pred_node );
1367                         else 
1368                                 pred = searchSimplePredicate( pred_node->key, class, field, pred_node->item );
1369
1370                         break;
1371                 }
1372         jsonObjectIteratorFree(pred_itr);
1373         } else if (node->type == JSON_NULL) { // IS NULL search
1374                 growing_buffer* _p = buffer_init(64);
1375                 buffer_fadd(
1376                         _p,
1377                         "\"%s\".%s IS NULL",
1378                         class,
1379                         osrfHashGet(field, "name")
1380                 );
1381                 pred = buffer_release(_p);
1382         } else { // equality search
1383                 pred = searchSimplePredicate( "=", class, field, node );
1384         }
1385
1386         return pred;
1387
1388 }
1389
1390
1391 /*
1392
1393 join : {
1394         acn : {
1395                 field : record,
1396                 fkey : id
1397                 type : left
1398                 filter_op : or
1399                 filter : { ... },
1400                 join : {
1401                         acp : {
1402                                 field : call_number,
1403                                 fkey : id,
1404                                 filter : { ... },
1405                         },
1406                 },
1407         },
1408         mrd : {
1409                 field : record,
1410                 type : inner
1411                 fkey : id,
1412                 filter : { ... },
1413         }
1414 }
1415
1416 */
1417
1418 static char* searchJOIN ( const jsonObject* join_hash, osrfHash* leftmeta ) {
1419
1420         const jsonObject* working_hash;
1421         jsonObject* freeable_hash = NULL;
1422
1423         if (join_hash->type == JSON_STRING) {
1424                 // create a wrapper around a copy of the original
1425                 char* _tmp = jsonObjectToSimpleString( join_hash );
1426                 freeable_hash = jsonParseString("{}");
1427                 jsonObjectSetKey(freeable_hash, _tmp, NULL);
1428                 free(_tmp);
1429                 working_hash = freeable_hash;
1430         }
1431         else
1432                 working_hash = join_hash;
1433
1434         growing_buffer* join_buf = buffer_init(128);
1435         char* leftclass = osrfHashGet(leftmeta, "classname");
1436
1437         jsonObjectNode* snode = NULL;
1438         jsonObjectIterator* search_itr = jsonNewObjectIterator( working_hash );
1439         if(freeable_hash)
1440                 jsonObjectFree(freeable_hash);
1441         
1442         while ( (snode = jsonObjectIteratorNext( search_itr )) ) {
1443                 osrfHash* idlClass = osrfHashGet( oilsIDL(), snode->key );
1444
1445                 char* class = osrfHashGet(idlClass, "classname");
1446
1447                 char* fkey = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode->item, "fkey" ) );
1448                 char* field = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode->item, "field" ) );
1449
1450                 if (field && !fkey) {
1451                         fkey = (char*)oilsIDLFindPath("/%s/links/%s/key", class, field);
1452                         if (!fkey) {
1453                                 osrfLogError(
1454                                         OSRF_LOG_MARK,
1455                                         "%s: JOIN failed.  No link defined from %s.%s to %s",
1456                                         MODULENAME,
1457                                         class,
1458                                         field,
1459                                         leftclass
1460                                 );
1461                                 buffer_free(join_buf);
1462                                 free(field);
1463                                 return NULL;
1464                         }
1465                         fkey = strdup( fkey );
1466
1467                 } else if (!field && fkey) {
1468                         field = (char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, fkey );
1469                         if (!field) {
1470                                 osrfLogError(
1471                                         OSRF_LOG_MARK,
1472                                         "%s: JOIN failed.  No link defined from %s.%s to %s",
1473                                         MODULENAME,
1474                                         leftclass,
1475                                         fkey,
1476                                         class
1477                                 );
1478                                 buffer_free(join_buf);
1479                                 free(fkey);
1480                                 return NULL;
1481                         }
1482                         field = strdup( field );
1483
1484                 } else if (!field && !fkey) {
1485                         osrfHash* _links = oilsIDLFindPath("/%s/links", leftclass);
1486
1487                         int i = 0;
1488                         osrfStringArray* keys = osrfHashKeys( _links );
1489                         while ( (fkey = osrfStringArrayGetString(keys, i++)) ) {
1490                                 fkey = strdup(osrfStringArrayGetString(keys, i++));
1491                                 if ( !strcmp( (char*)oilsIDLFindPath("/%s/links/%s/class", leftclass, fkey), class) ) {
1492                                         field = strdup( (char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, fkey) );
1493                                         break;
1494                                 } else {
1495                                         free(fkey);
1496                                 }
1497                         }
1498                         osrfStringArrayFree(keys);
1499
1500                         if (!field && !fkey) {
1501                                 _links = oilsIDLFindPath("/%s/links", class);
1502
1503                                 i = 0;
1504                                 keys = osrfHashKeys( _links );
1505                                 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
1506                                         field = strdup(osrfStringArrayGetString(keys, i++));
1507                                         if ( !strcmp( (char*)oilsIDLFindPath("/%s/links/%s/class", class, field), class) ) {
1508                                                 fkey = strdup( (char*)oilsIDLFindPath("/%s/links/%s/key", class, field) );
1509                                                 break;
1510                                         } else {
1511                                                 free(field);
1512                                         }
1513                                 }
1514                                 osrfStringArrayFree(keys);
1515                         }
1516
1517                         if (!field && !fkey) {
1518                                 osrfLogError(
1519                                         OSRF_LOG_MARK,
1520                                         "%s: JOIN failed.  No link defined between %s and %s",
1521                                         MODULENAME,
1522                                         leftclass,
1523                                         class
1524                                 );
1525                                 buffer_free(join_buf);
1526                                 return NULL;
1527                         }
1528
1529                 }
1530
1531                 char* type = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode->item, "type" ) );
1532                 if (type) {
1533                         if ( !strcasecmp(type,"left") ) {
1534                                 buffer_add(join_buf, " LEFT JOIN");
1535                         } else if ( !strcasecmp(type,"right") ) {
1536                                 buffer_add(join_buf, " RIGHT JOIN");
1537                         } else if ( !strcasecmp(type,"full") ) {
1538                                 buffer_add(join_buf, " FULL JOIN");
1539                         } else {
1540                                 buffer_add(join_buf, " INNER JOIN");
1541                         }
1542                 } else {
1543                         buffer_add(join_buf, " INNER JOIN");
1544                 }
1545                 free(type);
1546
1547                 char* table = getSourceDefinition(idlClass);
1548                 buffer_fadd(join_buf, " %s AS \"%s\" ON ( \"%s\".%s = \"%s\".%s", table, class, class, field, leftclass, fkey);
1549                 free(table);
1550
1551                 const jsonObject* filter = jsonObjectGetKeyConst( snode->item, "filter" );
1552                 if (filter) {
1553                         char* filter_op = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode->item, "filter_op" ) );
1554                         if (filter_op) {
1555                                 if (!strcasecmp("or",filter_op)) {
1556                                         buffer_add( join_buf, " OR " );
1557                                 } else {
1558                                         buffer_add( join_buf, " AND " );
1559                                 }
1560                         } else {
1561                                 buffer_add( join_buf, " AND " );
1562                         }
1563
1564                         char* jpred = searchWHERE( filter, idlClass, AND_OP_JOIN );
1565                         buffer_fadd( join_buf, " %s", jpred );
1566                         free(jpred);
1567                         free(filter_op);
1568                 }
1569
1570                 buffer_add(join_buf, " ) ");
1571                 
1572                 const jsonObject* join_filter = jsonObjectGetKeyConst( snode->item, "join" );
1573                 if (join_filter) {
1574                         char* jpred = searchJOIN( join_filter, idlClass );
1575                         buffer_fadd( join_buf, " %s", jpred );
1576                         free(jpred);
1577                 }
1578
1579                 free(fkey);
1580                 free(field);
1581         }
1582
1583     jsonObjectIteratorFree(search_itr);
1584
1585         return buffer_release(join_buf);
1586 }
1587
1588 /*
1589
1590 { +class : { -or|-and : { field : { op : value }, ... } ... }, ... }
1591 { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }
1592 [ { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }, ... ]
1593
1594 */
1595 static char* searchWHERE ( const jsonObject* search_hash, osrfHash* meta, int opjoin_type ) {
1596
1597         growing_buffer* sql_buf = buffer_init(128);
1598
1599         jsonObjectNode* node = NULL;
1600
1601     int first = 1;
1602     if ( search_hash->type == JSON_ARRAY ) {
1603         jsonObjectIterator* search_itr = jsonNewObjectIterator( search_hash );
1604         while ( (node = jsonObjectIteratorNext( search_itr )) ) {
1605             if (first) {
1606                 first = 0;
1607             } else {
1608                 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
1609                 else buffer_add(sql_buf, " AND ");
1610             }
1611
1612             char* subpred = searchWHERE( node->item, meta, opjoin_type );
1613             buffer_fadd(sql_buf, "( %s )", subpred);
1614             free(subpred);
1615         }
1616         jsonObjectIteratorFree(search_itr);
1617
1618     } else if ( search_hash->type == JSON_HASH ) {
1619         jsonObjectIterator* search_itr = jsonNewObjectIterator( search_hash );
1620         while ( (node = jsonObjectIteratorNext( search_itr )) ) {
1621
1622             if (first) {
1623                 first = 0;
1624             } else {
1625                 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
1626                 else buffer_add(sql_buf, " AND ");
1627             }
1628
1629             if ( !strncmp("+",node->key,1) ) {
1630                 if ( node->item->type == JSON_STRING ) {
1631                     char* subpred = jsonObjectToSimpleString( node->item );
1632                     buffer_fadd(sql_buf, " \"%s\".%s ", node->key + 1, subpred);
1633                     free(subpred);
1634                 } else {
1635                     char* subpred = searchWHERE( node->item, osrfHashGet( oilsIDL(), node->key + 1 ), AND_OP_JOIN );
1636                     buffer_fadd(sql_buf, "( %s )", subpred);
1637                     free(subpred);
1638                 }
1639             } else if ( !strcasecmp("-or",node->key) ) {
1640                 char* subpred = searchWHERE( node->item, meta, OR_OP_JOIN );
1641                 buffer_fadd(sql_buf, "( %s )", subpred);
1642                 free(subpred);
1643             } else if ( !strcasecmp("-and",node->key) ) {
1644                 char* subpred = searchWHERE( node->item, meta, AND_OP_JOIN );
1645                 buffer_fadd(sql_buf, "( %s )", subpred);
1646                 free(subpred);
1647             } else {
1648
1649                 char* class = osrfHashGet(meta, "classname");
1650                 osrfHash* fields = osrfHashGet(meta, "fields");
1651                 osrfHash* field = osrfHashGet( fields, node->key );
1652
1653
1654                 if (!field) {
1655                     char* table = getSourceDefinition(meta);
1656                     osrfLogError(
1657                         OSRF_LOG_MARK,
1658                         "%s: Attempt to reference non-existant column %s on %s (%s)",
1659                         MODULENAME,
1660                         node->key,
1661                         table,
1662                         class
1663                     );
1664                     buffer_free(sql_buf);
1665                     free(table);
1666                     return NULL;
1667                 }
1668
1669                 char* subpred = searchPredicate( class, field, node->item );
1670                 buffer_add( sql_buf, subpred );
1671                 free(subpred);
1672             }
1673         }
1674             jsonObjectIteratorFree(search_itr);
1675
1676     } else {
1677         // ERROR ... only hash and array allowed at this level
1678         char* predicate_string = jsonObjectToJSON( search_hash );
1679         osrfLogError(
1680             OSRF_LOG_MARK,
1681             "%s: Invalid predicate structure: %s",
1682             MODULENAME,
1683             predicate_string
1684         );
1685         buffer_free(sql_buf);
1686         free(predicate_string);
1687         return NULL;
1688     }
1689
1690
1691         return buffer_release(sql_buf);
1692 }
1693
1694 static char* SELECT (
1695                 /* method context */ osrfMethodContext* ctx,
1696                 
1697                 /* SELECT   */ jsonObject* selhash,
1698                 /* FROM     */ jsonObject* join_hash,
1699                 /* WHERE    */ jsonObject* search_hash,
1700                 /* HAVING   */ jsonObject* having_hash,
1701                 /* ORDER BY */ jsonObject* order_hash,
1702                 /* LIMIT    */ jsonObject* limit,
1703                 /* OFFSET   */ jsonObject* offset,
1704                 /* flags    */ int flags
1705 ) {
1706         const char* locale = osrf_message_get_last_locale();
1707
1708         // in case we don't get a select list
1709         jsonObject* defaultselhash = NULL;
1710
1711         // general tmp objects
1712         const jsonObject* tmp_const;
1713         jsonObject* _tmp = NULL;
1714         jsonObjectNode* selclass = NULL;
1715         jsonObjectNode* selfield = NULL;
1716         jsonObjectNode* snode = NULL;
1717         jsonObjectNode* onode = NULL;
1718         jsonObject* found = NULL;
1719
1720         char* string = NULL;
1721         int first = 1;
1722         int gfirst = 1;
1723         //int hfirst = 1;
1724
1725         // the core search class
1726         char* core_class = NULL;
1727
1728         // metadata about the core search class
1729         osrfHash* core_meta = NULL;
1730         osrfHash* core_fields = NULL;
1731         osrfHash* idlClass = NULL;
1732
1733         // punt if there's no core class
1734         if (!join_hash || ( join_hash->type == JSON_HASH && !join_hash->size ))
1735                 return NULL;
1736
1737         // get the core class -- the only key of the top level FROM clause, or a string
1738         if (join_hash->type == JSON_HASH) {
1739                 jsonObjectIterator* tmp_itr = jsonNewObjectIterator( join_hash );
1740                 snode = jsonObjectIteratorNext( tmp_itr );
1741                 
1742                 core_class = strdup( snode->key );
1743                 join_hash = snode->item;
1744
1745                 jsonObjectIteratorFree( tmp_itr );
1746                 snode = NULL;
1747
1748         } else if (join_hash->type == JSON_STRING) {
1749                 core_class = jsonObjectToSimpleString( join_hash );
1750                 join_hash = NULL;
1751         }
1752
1753         // punt if we don't know about the core class
1754         if (!(core_meta = osrfHashGet( oilsIDL(), core_class ))) {
1755                 free(core_class);
1756                 return NULL;
1757         }
1758
1759         // if the select list is empty, or the core class field list is '*',
1760         // build the default select list ...
1761         if (!selhash) {
1762                 selhash = defaultselhash = jsonParseString( "{}" );
1763                 jsonObjectSetKey( selhash, core_class, jsonParseString( "[]" ) );
1764         } else if ( (tmp_const = jsonObjectGetKeyConst( selhash, core_class )) && tmp_const->type == JSON_STRING ) {
1765                 char* _x = jsonObjectToSimpleString( tmp_const );
1766                 if (!strncmp( "*", _x, 1 )) {
1767                         jsonObjectRemoveKey( selhash, core_class );
1768                         jsonObjectSetKey( selhash, core_class, jsonParseString( "[]" ) );
1769                 }
1770                 free(_x);
1771         }
1772
1773         // the query buffer
1774         growing_buffer* sql_buf = buffer_init(128);
1775
1776         // temp buffer for the SELECT list
1777         growing_buffer* select_buf = buffer_init(128);
1778         growing_buffer* order_buf = buffer_init(128);
1779         growing_buffer* group_buf = buffer_init(128);
1780         growing_buffer* having_buf = buffer_init(128);
1781
1782         core_fields = osrfHashGet(core_meta, "fields");
1783
1784         // ... and if we /are/ building the default list, do that
1785         if ( (_tmp = jsonObjectGetKey(selhash,core_class)) && !_tmp->size ) {
1786                 
1787                 int i = 0;
1788                 char* field;
1789
1790                 osrfStringArray* keys = osrfHashKeys( core_fields );
1791                 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
1792                         if ( strncasecmp( "true", osrfHashGet( osrfHashGet( core_fields, field ), "virtual" ), 4 ) )
1793                                 jsonObjectPush( _tmp, jsonNewObject( field ) );
1794                 }
1795                 osrfStringArrayFree(keys);
1796         }
1797
1798         // Now we build the actual select list
1799         int sel_pos = 1;
1800         jsonObject* is_agg = jsonObjectFindPath(selhash, "//aggregate");
1801         first = 1;
1802         gfirst = 1;
1803         jsonObjectIterator* selclass_itr = jsonNewObjectIterator( selhash );
1804         while ( (selclass = jsonObjectIteratorNext( selclass_itr )) ) {
1805
1806                 // round trip through the idl, just to be safe
1807                 idlClass = osrfHashGet( oilsIDL(), selclass->key );
1808                 if (!idlClass) continue;
1809                 char* cname = osrfHashGet(idlClass, "classname");
1810
1811                 // make sure the target relation is in the join tree
1812                 if (strcmp(core_class,cname)) {
1813                         if (!join_hash) continue;
1814
1815                         if (join_hash->type == JSON_STRING) {
1816                                 string = jsonObjectToSimpleString(join_hash);
1817                                 found = strcmp(string,cname) ? NULL : jsonParseString("{\"1\":\"1\"}");
1818                                 free(string);
1819                         } else {
1820                                 found = jsonObjectFindPath(join_hash, "//%s", cname);
1821                         }
1822
1823                         if (!found->size) {
1824                                 jsonObjectFree(found);
1825                                 continue;
1826                         }
1827
1828                         jsonObjectFree(found);
1829                 }
1830
1831                 // stitch together the column list ...
1832                 jsonObjectIterator* select_itr = jsonNewObjectIterator( selclass->item );
1833                 while ( (selfield = jsonObjectIteratorNext( select_itr )) ) {
1834
1835                         char* __column = NULL;
1836                         char* __alias = NULL;
1837
1838                         // ... if it's a sstring, just toss it on the pile
1839                         if (selfield->item->type == JSON_STRING) {
1840
1841                                 // again, just to be safe
1842                                 char* _requested_col = jsonObjectToSimpleString(selfield->item);
1843                                 osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), _requested_col );
1844                                 free(_requested_col);
1845
1846                                 if (!field) continue;
1847                                 __column = strdup(osrfHashGet(field, "name"));
1848
1849                                 if (first) {
1850                                         first = 0;
1851                                 } else {
1852                                         buffer_add(select_buf, ",");
1853                                 }
1854
1855                 if (locale) {
1856                         char* i18n = osrfHashGet(field, "i18n");
1857                                 if (flags & DISABLE_I18N)
1858                         i18n = NULL;
1859
1860                         if ( i18n && !strncasecmp("true", i18n, 4)) {
1861                             char* pkey = osrfHashGet(idlClass, "primarykey");
1862                             char* tname = osrfHashGet(idlClass, "tablename");
1863
1864                         buffer_fadd(select_buf, " oils_i18n_xlate('%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"", tname, __column, pkey, cname, pkey, locale, __column);
1865                     } else {
1866                                         buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, __column, __column);
1867                     }
1868                 } else {
1869                                     buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, __column, __column);
1870                 }
1871
1872                         // ... but it could be an object, in which case we check for a Field Transform
1873                         } else {
1874
1875                                 __column = jsonObjectToSimpleString( jsonObjectGetKeyConst( selfield->item, "column" ) );
1876
1877                                 // again, just to be safe
1878                                 osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), __column );
1879                                 if (!field) continue;
1880                                 const char* fname = osrfHashGet(field, "name");
1881
1882                                 if (first) {
1883                                         first = 0;
1884                                 } else {
1885                                         buffer_add(select_buf, ",");
1886                                 }
1887
1888                                 if ((tmp_const = jsonObjectGetKeyConst( selfield->item, "alias" ))) {
1889                                         __alias = jsonObjectToSimpleString( tmp_const );
1890                                 } else {
1891                                         __alias = strdup(__column);
1892                                 }
1893
1894                                 if (jsonObjectGetKeyConst( selfield->item, "transform" )) {
1895                                         free(__column);
1896                                         __column = searchFieldTransform(cname, field, selfield->item);
1897                                         buffer_fadd(select_buf, " %s AS \"%s\"", __column, __alias);
1898                                 } else {
1899                     if (locale) {
1900                                 char* i18n = osrfHashGet(field, "i18n");
1901                                     if (flags & DISABLE_I18N)
1902                             i18n = NULL;
1903
1904                                 if ( i18n && !strncasecmp("true", i18n, 4)) {
1905                                 char* pkey = osrfHashGet(idlClass, "primarykey");
1906                                 char* tname = osrfHashGet(idlClass, "tablename");
1907
1908                             buffer_fadd(select_buf, " oils_i18n_xlate('%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"", tname, fname, pkey, cname, pkey, locale, __alias);
1909                         } else {
1910                                                 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, fname, __alias);
1911                         }
1912                     } else {
1913                                             buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, fname, __alias);
1914                     }
1915                                 }
1916                         }
1917
1918                         if (is_agg->size || (flags & SELECT_DISTINCT)) {
1919
1920                                 if (!jsonBoolIsTrue( jsonObjectGetKey( selfield->item, "aggregate" ) )) {
1921                                         if (gfirst) {
1922                                                 gfirst = 0;
1923                                         } else {
1924                                                 buffer_add(group_buf, ",");
1925                                         }
1926
1927                                         buffer_fadd(group_buf, " %d", sel_pos);
1928                                 /*
1929                                 } else if (is_agg = jsonObjectGetKey( selfield->item, "having" )) {
1930                                         if (gfirst) {
1931                                                 gfirst = 0;
1932                                         } else {
1933                                                 buffer_add(group_buf, ",");
1934                                         }
1935
1936                                         __column = searchFieldTransform(cname, field, selfield->item);
1937                                         buffer_fadd(group_buf, " %s", __column);
1938                                         __column = searchFieldTransform(cname, field, selfield->item);
1939                                 */
1940                                 }
1941                         }
1942
1943                         if (__column) free(__column);
1944                         if (__alias) free(__alias);
1945
1946                         sel_pos++;
1947                 }
1948
1949         // jsonObjectIteratorFree(select_itr);
1950         }
1951
1952     // jsonObjectIteratorFree(selclass_itr);
1953
1954         if (is_agg) jsonObjectFree(is_agg);
1955
1956         char* col_list = buffer_release(select_buf);
1957         char* table = getSourceDefinition(core_meta);
1958
1959         // Put it all together
1960         buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\" ", col_list, table, core_class );
1961         free(col_list);
1962         free(table);
1963
1964         // Now, walk the join tree and add that clause
1965         if ( join_hash ) {
1966                 char* join_clause = searchJOIN( join_hash, core_meta );
1967                 buffer_add(sql_buf, join_clause);
1968                 free(join_clause);
1969         }
1970
1971         if ( search_hash ) {
1972                 buffer_add(sql_buf, " WHERE ");
1973
1974                 // and it's on the the WHERE clause
1975                 char* pred = searchWHERE( search_hash, core_meta, AND_OP_JOIN );
1976
1977                 if (!pred) {
1978                         osrfAppSessionStatus(
1979                                 ctx->session,
1980                                 OSRF_STATUS_INTERNALSERVERERROR,
1981                                 "osrfMethodException",
1982                                 ctx->request,
1983                                 "Severe query error in WHERE predicate -- see error log for more details"
1984                         );
1985                         free(core_class);
1986                         buffer_free(having_buf);
1987                         buffer_free(group_buf);
1988                         buffer_free(order_buf);
1989                         buffer_free(sql_buf);
1990                         if (defaultselhash) jsonObjectFree(defaultselhash);
1991                         return NULL;
1992                 } else {
1993                         buffer_add(sql_buf, pred);
1994                         free(pred);
1995                 }
1996     }
1997
1998         if ( having_hash ) {
1999                 buffer_add(sql_buf, " HAVING ");
2000
2001                 // and it's on the the WHERE clause
2002                 char* pred = searchWHERE( having_hash, core_meta, AND_OP_JOIN );
2003
2004                 if (!pred) {
2005                         osrfAppSessionStatus(
2006                                 ctx->session,
2007                                 OSRF_STATUS_INTERNALSERVERERROR,
2008                                 "osrfMethodException",
2009                                 ctx->request,
2010                                 "Severe query error in HAVING predicate -- see error log for more details"
2011                         );
2012                         free(core_class);
2013                         buffer_free(having_buf);
2014                         buffer_free(group_buf);
2015                         buffer_free(order_buf);
2016                         buffer_free(sql_buf);
2017                         if (defaultselhash) jsonObjectFree(defaultselhash);
2018                         return NULL;
2019                 } else {
2020                         buffer_add(sql_buf, pred);
2021                         free(pred);
2022                 }
2023         }
2024
2025         first = 1;
2026         jsonObjectIterator* class_itr = jsonNewObjectIterator( order_hash );
2027         while ( (snode = jsonObjectIteratorNext( class_itr )) ) {
2028
2029                 if (!jsonObjectGetKeyConst(selhash,snode->key))
2030                         continue;
2031
2032                 if ( snode->item->type == JSON_HASH ) {
2033
2034                     jsonObjectIterator* order_itr = jsonNewObjectIterator( snode->item );
2035                         while ( (onode = jsonObjectIteratorNext( order_itr )) ) {
2036
2037                                 if (!oilsIDLFindPath( "/%s/fields/%s", snode->key, onode->key ))
2038                                         continue;
2039
2040                                 char* direction = NULL;
2041                                 if ( onode->item->type == JSON_HASH ) {
2042                                         if ( jsonObjectGetKeyConst( onode->item, "transform" ) ) {
2043                                                 string = searchFieldTransform(
2044                                                         snode->key,
2045                                                         oilsIDLFindPath( "/%s/fields/%s", snode->key, onode->key ),
2046                                                         onode->item
2047                                                 );
2048                                         } else {
2049                                                 growing_buffer* field_buf = buffer_init(16);
2050                                                 buffer_fadd(field_buf, "\"%s\".%s", snode->key, onode->key);
2051                                                 string = buffer_release(field_buf);
2052                                         }
2053
2054                                         if ( (tmp_const = jsonObjectGetKeyConst( onode->item, "direction" )) ) {
2055                                                 direction = jsonObjectToSimpleString(tmp_const);
2056                                                 if (!strncasecmp(direction, "d", 1)) {
2057                                                         free(direction);
2058                                                         direction = " DESC";
2059                                                 } else {
2060                                                         free(direction);
2061                                                         direction = " ASC";
2062                                                 }
2063                                         }
2064
2065                                 } else {
2066                                         string = strdup(onode->key);
2067                                         direction = jsonObjectToSimpleString(onode->item);
2068                                         if (!strncasecmp(direction, "d", 1)) {
2069                                                 free(direction);
2070                                                 direction = " DESC";
2071                                         } else {
2072                                                 free(direction);
2073                                                 direction = " ASC";
2074                                         }
2075                                 }
2076
2077                                 if (first) {
2078                                         first = 0;
2079                                 } else {
2080                                         buffer_add(order_buf, ", ");
2081                                 }
2082
2083                                 buffer_add(order_buf, string);
2084                                 free(string);
2085
2086                                 if (direction) {
2087                                         buffer_add(order_buf, direction);
2088                                 }
2089
2090                         }
2091             // jsonObjectIteratorFree(order_itr);
2092
2093                 } else if ( snode->item->type == JSON_ARRAY ) {
2094
2095                     jsonObjectIterator* order_itr = jsonNewObjectIterator( snode->item );
2096                         while ( (onode = jsonObjectIteratorNext( order_itr )) ) {
2097
2098                                 char* _f = jsonObjectToSimpleString( onode->item );
2099
2100                                 if (!oilsIDLFindPath( "/%s/fields/%s", snode->key, _f))
2101                                         continue;
2102
2103                                 if (first) {
2104                                         first = 0;
2105                                 } else {
2106                                         buffer_add(order_buf, ", ");
2107                                 }
2108
2109                                 buffer_add(order_buf, _f);
2110                                 free(_f);
2111
2112                         }
2113             // jsonObjectIteratorFree(order_itr);
2114
2115
2116                 // IT'S THE OOOOOOOOOOOLD STYLE!
2117                 } else {
2118                         osrfLogError(OSRF_LOG_MARK, "%s: Possible SQL injection attempt; direct order by is not allowed", MODULENAME);
2119                         osrfAppSessionStatus(
2120                                 ctx->session,
2121                                 OSRF_STATUS_INTERNALSERVERERROR,
2122                                 "osrfMethodException",
2123                                 ctx->request,
2124                                 "Severe query error -- see error log for more details"
2125                         );
2126
2127                         free(core_class);
2128                         buffer_free(having_buf);
2129                         buffer_free(group_buf);
2130                         buffer_free(order_buf);
2131                         buffer_free(sql_buf);
2132                         if (defaultselhash) jsonObjectFree(defaultselhash);
2133                         return NULL;
2134                 }
2135
2136         }
2137
2138     // jsonObjectIteratorFree(class_itr);
2139
2140         string = buffer_release(group_buf);
2141
2142         if (strlen(string)) {
2143                 buffer_fadd(
2144                         sql_buf,
2145                         " GROUP BY %s",
2146                         string
2147                 );
2148         }
2149
2150         free(string);
2151
2152         string = buffer_release(having_buf);
2153  
2154         if (strlen(string)) {
2155                 buffer_fadd(
2156                         sql_buf,
2157                         " HAVING %s",
2158                         string
2159                 );
2160         }
2161
2162         free(string);
2163
2164         string = buffer_release(order_buf);
2165
2166         if (strlen(string)) {
2167                 buffer_fadd(
2168                         sql_buf,
2169                         " ORDER BY %s",
2170                         string
2171                 );
2172         }
2173
2174         free(string);
2175
2176         if ( limit ){
2177                 string = jsonObjectToSimpleString(limit);
2178                 buffer_fadd( sql_buf, " LIMIT %d", atoi(string) );
2179                 free(string);
2180         }
2181
2182         if (offset) {
2183                 string = jsonObjectToSimpleString(offset);
2184                 buffer_fadd( sql_buf, " OFFSET %d", atoi(string) );
2185                 free(string);
2186         }
2187
2188         buffer_add(sql_buf, ";");
2189
2190         free(core_class);
2191         if (defaultselhash) jsonObjectFree(defaultselhash);
2192
2193         return buffer_release(sql_buf);
2194
2195 }
2196
2197 static char* buildSELECT ( jsonObject* search_hash, jsonObject* order_hash, osrfHash* meta, osrfMethodContext* ctx ) {
2198
2199         const char* locale = osrf_message_get_last_locale();
2200
2201         osrfHash* fields = osrfHashGet(meta, "fields");
2202         char* core_class = osrfHashGet(meta, "classname");
2203
2204         const jsonObject* join_hash = jsonObjectGetKeyConst( order_hash, "join" );
2205
2206         jsonObjectNode* node = NULL;
2207         jsonObjectNode* snode = NULL;
2208         jsonObjectNode* onode = NULL;
2209         const jsonObject* _tmp = NULL;
2210         jsonObject* selhash = NULL;
2211         jsonObject* defaultselhash = NULL;
2212
2213         growing_buffer* sql_buf = buffer_init(128);
2214         growing_buffer* select_buf = buffer_init(128);
2215
2216         if ( !(selhash = jsonObjectGetKey( order_hash, "select" )) ) {
2217                 defaultselhash = jsonParseString( "{}" );
2218                 selhash = defaultselhash;
2219         }
2220         
2221         if ( !jsonObjectGetKeyConst(selhash,core_class) ) {
2222                 jsonObjectSetKey( selhash, core_class, jsonParseString( "[]" ) );
2223                 jsonObject* flist = jsonObjectGetKey( selhash, core_class );
2224                 
2225                 int i = 0;
2226                 char* field;
2227
2228                 osrfStringArray* keys = osrfHashKeys( fields );
2229                 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
2230                         if ( strcasecmp( "true", osrfHashGet( osrfHashGet( fields, field ), "virtual" ) ) )
2231                                 jsonObjectPush( flist, jsonNewObject( field ) );
2232                 }
2233                 osrfStringArrayFree(keys);
2234         }
2235
2236         int first = 1;
2237         jsonObjectIterator* class_itr = jsonNewObjectIterator( selhash );
2238         while ( (snode = jsonObjectIteratorNext( class_itr )) ) {
2239
2240                 osrfHash* idlClass = osrfHashGet( oilsIDL(), snode->key );
2241                 if (!idlClass) continue;
2242                 char* cname = osrfHashGet(idlClass, "classname");
2243
2244                 if (strcmp(core_class,snode->key)) {
2245                         if (!join_hash) continue;
2246
2247                         jsonObject* found =  jsonObjectFindPath(join_hash, "//%s", snode->key);
2248                         if (!found->size) {
2249                                 jsonObjectFree(found);
2250                                 continue;
2251                         }
2252
2253                         jsonObjectFree(found);
2254                 }
2255
2256                 jsonObjectIterator* select_itr = jsonNewObjectIterator( snode->item );
2257                 while ( (node = jsonObjectIteratorNext( select_itr )) ) {
2258                         char* item_str = jsonObjectToSimpleString(node->item);
2259                         osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), item_str );
2260                         free(item_str);
2261                         char* fname = osrfHashGet(field, "name");
2262
2263                         if (!field) continue;
2264
2265                         if (first) {
2266                                 first = 0;
2267                         } else {
2268                                 buffer_add(select_buf, ",");
2269                         }
2270
2271             if (locale) {
2272                         char* i18n = osrfHashGet(field, "i18n");
2273                     if (jsonBoolIsTrue(jsonObjectGetKey( order_hash, "no_i18n" )))
2274                     i18n = NULL;
2275
2276                         if ( i18n && !strncasecmp("true", i18n, 4)) {
2277                         char* pkey = osrfHashGet(idlClass, "primarykey");
2278                         char* tname = osrfHashGet(idlClass, "tablename");
2279
2280                     buffer_fadd(select_buf, " oils_i18n_xlate('%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"", tname, fname, pkey, cname, pkey, locale, fname);
2281                 } else {
2282                                 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
2283                 }
2284             } else {
2285                             buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
2286             }
2287                 }
2288
2289         jsonObjectIteratorFree(select_itr);
2290         }
2291
2292     jsonObjectIteratorFree(class_itr);
2293
2294         char* col_list = buffer_release(select_buf);
2295         char* table = getSourceDefinition(meta);
2296
2297         buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\"", col_list, table, core_class );
2298         free(col_list);
2299         free(table);
2300
2301         if ( join_hash ) {
2302                 char* join_clause = searchJOIN( join_hash, meta );
2303                 buffer_fadd(sql_buf, " %s", join_clause);
2304                 free(join_clause);
2305         }
2306
2307         char* tmpsql = buffer_data(sql_buf);
2308         osrfLogDebug(OSRF_LOG_MARK, "%s pre-predicate SQL =  %s", MODULENAME, tmpsql);
2309         free(tmpsql);
2310
2311         buffer_add(sql_buf, " WHERE ");
2312
2313         char* pred = searchWHERE( search_hash, meta, AND_OP_JOIN );
2314         if (!pred) {
2315                 osrfAppSessionStatus(
2316                         ctx->session,
2317                         OSRF_STATUS_INTERNALSERVERERROR,
2318                                 "osrfMethodException",
2319                                 ctx->request,
2320                                 "Severe query error -- see error log for more details"
2321                         );
2322                 buffer_free(sql_buf);
2323                 if(defaultselhash) jsonObjectFree(defaultselhash);
2324                 return NULL;
2325         } else {
2326                 buffer_add(sql_buf, pred);
2327                 free(pred);
2328         }
2329
2330         if (order_hash) {
2331                 char* string = NULL;
2332                 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "order_by" )) ){
2333
2334                         growing_buffer* order_buf = buffer_init(128);
2335
2336                         first = 1;
2337                         jsonObjectIterator* class_itr = jsonNewObjectIterator( _tmp );
2338                         while ( (snode = jsonObjectIteratorNext( class_itr )) ) {
2339
2340                                 if (!jsonObjectGetKeyConst(selhash,snode->key))
2341                                         continue;
2342
2343                                 if ( snode->item->type == JSON_HASH ) {
2344
2345                                         jsonObjectIterator* order_itr = jsonNewObjectIterator( snode->item );
2346                                         while ( (onode = jsonObjectIteratorNext( order_itr )) ) {
2347
2348                                                 if (!oilsIDLFindPath( "/%s/fields/%s", snode->key, onode->key ))
2349                                                         continue;
2350
2351                                                 char* direction = NULL;
2352                                                 if ( onode->item->type == JSON_HASH ) {
2353                                                         if ( jsonObjectGetKeyConst( onode->item, "transform" ) ) {
2354                                                                 string = searchFieldTransform(
2355                                                                         snode->key,
2356                                                                         oilsIDLFindPath( "/%s/fields/%s", snode->key, onode->key ),
2357                                                                         onode->item
2358                                                                 );
2359                                                         } else {
2360                                                                 growing_buffer* field_buf = buffer_init(16);
2361                                                                 buffer_fadd(field_buf, "\"%s\".%s", snode->key, onode->key);
2362                                                                 string = buffer_release(field_buf);
2363                                                         }
2364
2365                                                         if ( (_tmp = jsonObjectGetKeyConst( onode->item, "direction" )) ) {
2366                                                                 direction = jsonObjectToSimpleString(_tmp);
2367                                                                 if (!strncasecmp(direction, "d", 1)) {
2368                                                                         free(direction);
2369                                                                         direction = " DESC";
2370                                                                 } else {
2371                                                                         free(direction);
2372                                                                         direction = " ASC";
2373                                                                 }
2374                                                         }
2375
2376                                                 } else {
2377                                                         string = strdup(onode->key);
2378                                                         direction = jsonObjectToSimpleString(onode->item);
2379                                                         if (!strncasecmp(direction, "d", 1)) {
2380                                                                 free(direction);
2381                                                                 direction = " DESC";
2382                                                         } else {
2383                                                                 free(direction);
2384                                                                 direction = " ASC";
2385                                                         }
2386                                                 }
2387
2388                                                 if (first) {
2389                                                         first = 0;
2390                                                 } else {
2391                                                         buffer_add(order_buf, ", ");
2392                                                 }
2393
2394                                                 buffer_add(order_buf, string);
2395                                                 free(string);
2396
2397                                                 if (direction) {
2398                                                         buffer_add(order_buf, direction);
2399                                                 }
2400
2401                                         }
2402
2403                     jsonObjectIteratorFree(order_itr);
2404
2405                                 } else {
2406                                         string = jsonObjectToSimpleString(snode->item);
2407                                         buffer_add(order_buf, string);
2408                                         free(string);
2409                                         break;
2410                                 }
2411
2412                         }
2413
2414             jsonObjectIteratorFree(class_itr);
2415
2416                         string = buffer_release(order_buf);
2417
2418                         if (strlen(string)) {
2419                                 buffer_fadd(
2420                                         sql_buf,
2421                                         " ORDER BY %s",
2422                                         string
2423                                 );
2424                         }
2425
2426                         free(string);
2427                 }
2428
2429                 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "limit" )) ){
2430                         string = jsonObjectToSimpleString(_tmp);
2431                         buffer_fadd(
2432                                 sql_buf,
2433                                 " LIMIT %d",
2434                                 atoi(string)
2435                         );
2436                         free(string);
2437                 }
2438
2439                 _tmp = jsonObjectGetKeyConst( order_hash, "offset" );
2440                 if (_tmp) {
2441                         string = jsonObjectToSimpleString(_tmp);
2442                         buffer_fadd(
2443                                 sql_buf,
2444                                 " OFFSET %d",
2445                                 atoi(string)
2446                         );
2447                         free(string);
2448                 }
2449         }
2450
2451         if (defaultselhash) jsonObjectFree(defaultselhash);
2452
2453         buffer_add(sql_buf, ";");
2454         return buffer_release(sql_buf);
2455 }
2456
2457 int doJSONSearch ( osrfMethodContext* ctx ) {
2458         OSRF_METHOD_VERIFY_CONTEXT(ctx);
2459         osrfLogDebug(OSRF_LOG_MARK, "Recieved query request");
2460
2461         int err = 0;
2462
2463         // XXX for now...
2464         dbhandle = writehandle;
2465
2466         jsonObject* hash = jsonObjectGetIndex(ctx->params, 0);
2467
2468     int flags = 0;
2469
2470         if (jsonBoolIsTrue(jsonObjectGetKey( hash, "distinct" )))
2471          flags |= SELECT_DISTINCT;
2472
2473         if ( ((int)jsonObjectGetNumber(jsonObjectGetKey( hash, "distinct" ))) == 1 ) // support 1/0 for perl's sake
2474          flags |= SELECT_DISTINCT;
2475
2476         if (jsonBoolIsTrue(jsonObjectGetKey( hash, "no_i18n" )))
2477          flags |= DISABLE_I18N;
2478
2479         if ( ((int)jsonObjectGetNumber(jsonObjectGetKey( hash, "no_i18n" ))) == 1 ) // support 1/0 for perl's sake
2480          flags |= DISABLE_I18N;
2481
2482         osrfLogDebug(OSRF_LOG_MARK, "Building SQL ...");
2483         char* sql = SELECT(
2484                         ctx,
2485                         jsonObjectGetKey( hash, "select" ),
2486                         jsonObjectGetKey( hash, "from" ),
2487                         jsonObjectGetKey( hash, "where" ),
2488                         jsonObjectGetKey( hash, "having" ),
2489                         jsonObjectGetKey( hash, "order_by" ),
2490                         jsonObjectGetKey( hash, "limit" ),
2491                         jsonObjectGetKey( hash, "offset" ),
2492                         flags
2493         );
2494
2495         if (!sql) {
2496                 err = -1;
2497                 return err;
2498         }
2499         
2500         osrfLogDebug(OSRF_LOG_MARK, "%s SQL =  %s", MODULENAME, sql);
2501         dbi_result result = dbi_conn_query(dbhandle, sql);
2502
2503         if(result) {
2504                 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
2505
2506                 if (dbi_result_first_row(result)) {
2507                         /* JSONify the result */
2508                         osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
2509
2510                         do {
2511                                 jsonObject* return_val = oilsMakeJSONFromResult( result );
2512                                 osrfAppRespond( ctx, return_val );
2513                 jsonObjectFree( return_val );
2514                         } while (dbi_result_next_row(result));
2515
2516                 } else {
2517                         osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
2518                 }
2519
2520                 osrfAppRespondComplete( ctx, NULL );
2521
2522                 /* clean up the query */
2523                 dbi_result_free(result); 
2524
2525         } else {
2526                 err = -1;
2527                 osrfLogError(OSRF_LOG_MARK, "%s: Error with query [%s]", MODULENAME, sql);
2528                 osrfAppSessionStatus(
2529                         ctx->session,
2530                         OSRF_STATUS_INTERNALSERVERERROR,
2531                         "osrfMethodException",
2532                         ctx->request,
2533                         "Severe query error -- see error log for more details"
2534                 );
2535         }
2536
2537         free(sql);
2538         return err;
2539 }
2540
2541 static jsonObject* doFieldmapperSearch ( osrfMethodContext* ctx, osrfHash* meta,
2542                 const jsonObject* params, int* err ) {
2543
2544         // XXX for now...
2545         dbhandle = writehandle;
2546
2547         osrfHash* links = osrfHashGet(meta, "links");
2548         osrfHash* fields = osrfHashGet(meta, "fields");
2549         char* core_class = osrfHashGet(meta, "classname");
2550         char* pkey = osrfHashGet(meta, "primarykey");
2551
2552         const jsonObject* _tmp;
2553         jsonObject* obj;
2554         jsonObject* search_hash = jsonObjectGetIndex(params, 0);
2555         jsonObject* order_hash = jsonObjectGetIndex(params, 1);
2556
2557         char* sql = buildSELECT( search_hash, order_hash, meta, ctx );
2558         if (!sql) {
2559                 *err = -1;
2560                 return NULL;
2561         }
2562         
2563         osrfLogDebug(OSRF_LOG_MARK, "%s SQL =  %s", MODULENAME, sql);
2564         dbi_result result = dbi_conn_query(dbhandle, sql);
2565
2566         jsonObject* res_list = jsonParseString("[]");
2567         if(result) {
2568                 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
2569                 osrfHash* dedup = osrfNewHash();
2570
2571                 if (dbi_result_first_row(result)) {
2572                         /* JSONify the result */
2573                         osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
2574                         do {
2575                                 obj = oilsMakeFieldmapperFromResult( result, meta );
2576                                 int pkey_pos = atoi( osrfHashGet( osrfHashGet( fields, pkey ), "array_position" ) );
2577                                 char* pkey_val = jsonObjectToSimpleString( jsonObjectGetIndex( obj, pkey_pos ) );
2578                                 if ( osrfHashGet( dedup, pkey_val ) ) {
2579                                         jsonObjectFree(obj);
2580                                         free(pkey_val);
2581                                 } else {
2582                                         osrfHashSet( dedup, pkey_val, pkey_val );
2583                                         jsonObjectPush(res_list, obj);
2584                                 }
2585                         } while (dbi_result_next_row(result));
2586                 } else {
2587                         osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
2588                 }
2589
2590                 osrfHashFree(dedup);
2591
2592                 /* clean up the query */
2593                 dbi_result_free(result); 
2594
2595         } else {
2596                 osrfLogError(OSRF_LOG_MARK, "%s: Error retrieving %s with query [%s]", MODULENAME, osrfHashGet(meta, "fieldmapper"), sql);
2597                 osrfAppSessionStatus(
2598                         ctx->session,
2599                         OSRF_STATUS_INTERNALSERVERERROR,
2600                         "osrfMethodException",
2601                         ctx->request,
2602                         "Severe query error -- see error log for more details"
2603                 );
2604                 *err = -1;
2605                 free(sql);
2606                 jsonObjectFree(res_list);
2607                 return jsonNULL;
2608
2609         }
2610
2611         free(sql);
2612
2613         if (res_list->size && order_hash) {
2614                 _tmp = jsonObjectGetKeyConst( order_hash, "flesh" );
2615                 if (_tmp) {
2616                         int x = (int)jsonObjectGetNumber(_tmp);
2617                         if (x == -1 || x > max_flesh_depth) x = max_flesh_depth;
2618
2619                         const jsonObject* temp_blob;
2620                         if ((temp_blob = jsonObjectGetKeyConst( order_hash, "flesh_fields" )) && x > 0) {
2621
2622                                 jsonObject* flesh_blob = jsonObjectClone( temp_blob );
2623                                 const jsonObject* flesh_fields = jsonObjectGetKeyConst( flesh_blob, core_class );
2624
2625                                 osrfStringArray* link_fields = NULL;
2626
2627                                 if (flesh_fields) {
2628                                         if (flesh_fields->size == 1) {
2629                                                 char* _t = jsonObjectToSimpleString( jsonObjectGetIndex( flesh_fields, 0 ) );
2630                                                 if (!strcmp(_t,"*")) link_fields = osrfHashKeys( links );
2631                                                 free(_t);
2632                                         }
2633
2634                                         if (!link_fields) {
2635                                                 jsonObjectNode* _f;
2636                                                 link_fields = osrfNewStringArray(1);
2637                                                 jsonObjectIterator* _i = jsonNewObjectIterator( flesh_fields );
2638                                                 while ((_f = jsonObjectIteratorNext( _i ))) {
2639                                                         osrfStringArrayAdd( link_fields, jsonObjectToSimpleString( _f->item ) );
2640                                                 }
2641                         jsonObjectIteratorFree(_i);
2642                                         }
2643                                 }
2644
2645                                 jsonObjectNode* cur;
2646                                 jsonObjectIterator* itr = jsonNewObjectIterator( res_list );
2647                                 while ((cur = jsonObjectIteratorNext( itr ))) {
2648
2649                                         int i = 0;
2650                                         char* link_field;
2651                                         
2652                                         while ( (link_field = osrfStringArrayGetString(link_fields, i++)) ) {
2653
2654                                                 osrfLogDebug(OSRF_LOG_MARK, "Starting to flesh %s", link_field);
2655
2656                                                 osrfHash* kid_link = osrfHashGet(links, link_field);
2657                                                 if (!kid_link) continue;
2658
2659                                                 osrfHash* field = osrfHashGet(fields, link_field);
2660                                                 if (!field) continue;
2661
2662                                                 osrfHash* value_field = field;
2663
2664                                                 osrfHash* kid_idl = osrfHashGet(oilsIDL(), osrfHashGet(kid_link, "class"));
2665                                                 if (!kid_idl) continue;
2666
2667                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
2668                                                         value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
2669                                                 }
2670                                                         
2671                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) { // might_have
2672                                                         value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
2673                                                 }
2674
2675                                                 osrfStringArray* link_map = osrfHashGet( kid_link, "map" );
2676
2677                                                 if (link_map->size > 0) {
2678                                                         jsonObject* _kid_key = jsonParseString("[]");
2679                                                         jsonObjectPush(
2680                                                                 _kid_key,
2681                                                                 jsonNewObject( osrfStringArrayGetString( link_map, 0 ) )
2682                                                         );
2683
2684                                                         jsonObjectSetKey(
2685                                                                 flesh_blob,
2686                                                                 osrfHashGet(kid_link, "class"),
2687                                                                 _kid_key
2688                                                         );
2689                                                 };
2690
2691                                                 osrfLogDebug(
2692                                                         OSRF_LOG_MARK,
2693                                                         "Link field: %s, remote class: %s, fkey: %s, reltype: %s",
2694                                                         osrfHashGet(kid_link, "field"),
2695                                                         osrfHashGet(kid_link, "class"),
2696                                                         osrfHashGet(kid_link, "key"),
2697                                                         osrfHashGet(kid_link, "reltype")
2698                                                 );
2699
2700                                                 jsonObject* fake_params = jsonParseString("[]");
2701                                                 jsonObjectPush(fake_params, jsonParseString("{}")); // search hash
2702                                                 jsonObjectPush(fake_params, jsonParseString("{}")); // order/flesh hash
2703
2704                                                 osrfLogDebug(OSRF_LOG_MARK, "Creating dummy params object...");
2705
2706                                                 char* search_key =
2707                                                 jsonObjectToSimpleString(
2708                                                         jsonObjectGetIndex(
2709                                                                 cur->item,
2710                                                                 atoi( osrfHashGet(value_field, "array_position") )
2711                                                         )
2712                                                 );
2713
2714                                                 if (!search_key) {
2715                                                         osrfLogDebug(OSRF_LOG_MARK, "Nothing to search for!");
2716                                                         continue;
2717                                                 }
2718                                                         
2719                                                 jsonObjectSetKey(
2720                                                         jsonObjectGetIndex(fake_params, 0),
2721                                                         osrfHashGet(kid_link, "key"),
2722                                                         jsonNewObject( search_key )
2723                                                 );
2724
2725                                                 free(search_key);
2726
2727
2728                                                 jsonObjectSetKey(
2729                                                         jsonObjectGetIndex(fake_params, 1),
2730                                                         "flesh",
2731                                                         jsonNewNumberObject( (double)(x - 1 + link_map->size) )
2732                                                 );
2733
2734                                                 if (flesh_blob)
2735                                                         jsonObjectSetKey( jsonObjectGetIndex(fake_params, 1), "flesh_fields", jsonObjectClone(flesh_blob) );
2736
2737                                                 if (jsonObjectGetKeyConst(order_hash, "order_by")) {
2738                                                         jsonObjectSetKey(
2739                                                                 jsonObjectGetIndex(fake_params, 1),
2740                                                                 "order_by",
2741                                                                 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "order_by"))
2742                                                         );
2743                                                 }
2744
2745                                                 if (jsonObjectGetKeyConst(order_hash, "select")) {
2746                                                         jsonObjectSetKey(
2747                                                                 jsonObjectGetIndex(fake_params, 1),
2748                                                                 "select",
2749                                                                 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "select"))
2750                                                         );
2751                                                 }
2752
2753                                                 jsonObject* kids = doFieldmapperSearch(ctx, kid_idl, fake_params, err);
2754
2755                                                 if(*err) {
2756                                                         jsonObjectFree( fake_params );
2757                                                         osrfStringArrayFree(link_fields);
2758                                                         jsonObjectIteratorFree(itr);
2759                                                         jsonObjectFree(res_list);
2760                                                         jsonObjectFree(flesh_blob);
2761                                                         return jsonNULL;
2762                                                 }
2763
2764                                                 osrfLogDebug(OSRF_LOG_MARK, "Search for %s return %d linked objects", osrfHashGet(kid_link, "class"), kids->size);
2765
2766                                                 jsonObject* X = NULL;
2767                                                 if ( link_map->size > 0 && kids->size > 0 ) {
2768                                                         X = kids;
2769                                                         kids = jsonParseString("[]");
2770
2771                                                         jsonObjectNode* _k_node;
2772                                                         jsonObjectIterator* _k = jsonNewObjectIterator( X );
2773                                                         while ((_k_node = jsonObjectIteratorNext( _k ))) {
2774                                                                 jsonObjectPush(
2775                                                                         kids,
2776                                                                         jsonObjectClone(
2777                                                                                 jsonObjectGetIndex(
2778                                                                                         _k_node->item,
2779                                                                                         (unsigned long)atoi(
2780                                                                                                 osrfHashGet(
2781                                                                                                         osrfHashGet(
2782                                                                                                                 osrfHashGet(
2783                                                                                                                         osrfHashGet(
2784                                                                                                                                 oilsIDL(),
2785                                                                                                                                 osrfHashGet(kid_link, "class")
2786                                                                                                                         ),
2787                                                                                                                         "fields"
2788                                                                                                                 ),
2789                                                                                                                 osrfStringArrayGetString( link_map, 0 )
2790                                                                                                         ),
2791                                                                                                         "array_position"
2792                                                                                                 )
2793                                                                                         )
2794                                                                                 )
2795                                                                         )
2796                                                                 );
2797                                                         }
2798                                                 }
2799
2800                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_a" )) || !(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) {
2801                                                         osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
2802                                                         jsonObjectSetIndex(
2803                                                                 cur->item,
2804                                                                 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
2805                                                                 jsonObjectClone( jsonObjectGetIndex(kids, 0) )
2806                                                         );
2807                                                 }
2808
2809                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
2810                                                         osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
2811                                                         jsonObjectSetIndex(
2812                                                                 cur->item,
2813                                                                 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
2814                                                                 jsonObjectClone( kids )
2815                                                         );
2816                                                 }
2817
2818                                                 if (X) {
2819                                                         jsonObjectFree(kids);
2820                                                         kids = X;
2821                                                 }
2822
2823                                                 jsonObjectFree( kids );
2824                                                 jsonObjectFree( fake_params );
2825
2826                                                 osrfLogDebug(OSRF_LOG_MARK, "Fleshing of %s complete", osrfHashGet(kid_link, "field"));
2827                                                 osrfLogDebug(OSRF_LOG_MARK, "%s", jsonObjectToJSON(cur->item));
2828
2829                                         }
2830                                 }
2831                                 jsonObjectFree( flesh_blob );
2832                                 osrfStringArrayFree(link_fields);
2833                                 jsonObjectIteratorFree(itr);
2834                         }
2835                 }
2836         }
2837
2838         return res_list;
2839 }
2840
2841
2842 static jsonObject* doUpdate(osrfMethodContext* ctx, int* err ) {
2843
2844         osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );