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