add support for selecting from a function, given the function name and all params...
[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 from_function = 0;
1729         int first = 1;
1730         int gfirst = 1;
1731         //int hfirst = 1;
1732
1733         // the core search class
1734         char* core_class = NULL;
1735
1736         // metadata about the core search class
1737         osrfHash* core_meta = NULL;
1738         osrfHash* core_fields = NULL;
1739         osrfHash* idlClass = NULL;
1740
1741         // punt if there's no core class
1742         if (!join_hash || ( join_hash->type == JSON_HASH && !join_hash->size ))
1743                 return NULL;
1744
1745         // get the core class -- the only key of the top level FROM clause, or a string
1746         if (join_hash->type == JSON_HASH) {
1747                 jsonIterator* tmp_itr = jsonNewIterator( join_hash );
1748                 snode = jsonIteratorNext( tmp_itr );
1749                 
1750                 core_class = strdup( tmp_itr->key );
1751                 join_hash = snode;
1752
1753                 jsonIteratorFree( tmp_itr );
1754                 snode = NULL;
1755
1756         } else if (join_hash->type == JSON_ARRAY) {
1757         from_function = 1;
1758         selhash = NULL;
1759
1760         } else if (join_hash->type == JSON_STRING) {
1761                 core_class = jsonObjectToSimpleString( join_hash );
1762                 join_hash = NULL;
1763         }
1764
1765         // punt if we don't know about the core class (and it's not a function)
1766         if (!from_function && !(core_meta = osrfHashGet( oilsIDL(), core_class ))) {
1767                 free(core_class);
1768                 return NULL;
1769         }
1770
1771         // if the select list is empty, or the core class field list is '*',
1772         // build the default select list ...
1773         if (!selhash) {
1774                 selhash = defaultselhash = jsonNewObjectType(JSON_HASH);
1775                 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
1776         } else if ( (tmp_const = jsonObjectGetKeyConst( selhash, core_class )) && tmp_const->type == JSON_STRING ) {
1777                 char* _x = jsonObjectToSimpleString( tmp_const );
1778                 if (!strncmp( "*", _x, 1 )) {
1779                         jsonObjectRemoveKey( selhash, core_class );
1780                         jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
1781                 }
1782                 free(_x);
1783         }
1784
1785         // the query buffer
1786         growing_buffer* sql_buf = buffer_init(128);
1787
1788         // temp buffer for the SELECT list
1789         growing_buffer* select_buf = buffer_init(128);
1790         growing_buffer* order_buf = buffer_init(128);
1791         growing_buffer* group_buf = buffer_init(128);
1792         growing_buffer* having_buf = buffer_init(128);
1793
1794         if (!from_function) 
1795         core_fields = osrfHashGet(core_meta, "fields");
1796
1797         // ... and if we /are/ building the default list, do that
1798         if ( (_tmp = jsonObjectGetKey(selhash,core_class)) && !_tmp->size ) {
1799                 
1800                 int i = 0;
1801                 char* field;
1802
1803         if (!from_function) {
1804                 osrfStringArray* keys = osrfHashKeys( core_fields );
1805                 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
1806                         if ( strncasecmp( "true", osrfHashGet( osrfHashGet( core_fields, field ), "virtual" ), 4 ) )
1807                                 jsonObjectPush( _tmp, jsonNewObject( field ) );
1808                 }
1809                 osrfStringArrayFree(keys);
1810         }
1811         }
1812
1813         // Now we build the actual select list
1814         if (!from_function) {
1815             int sel_pos = 1;
1816             jsonObject* is_agg = jsonObjectFindPath(selhash, "//aggregate");
1817             first = 1;
1818             gfirst = 1;
1819             jsonIterator* selclass_itr = jsonNewIterator( selhash );
1820             while ( (selclass = jsonIteratorNext( selclass_itr )) ) {
1821
1822                     // round trip through the idl, just to be safe
1823                     idlClass = osrfHashGet( oilsIDL(), selclass_itr->key );
1824                     if (!idlClass) continue;
1825                     char* cname = osrfHashGet(idlClass, "classname");
1826
1827                     // make sure the target relation is in the join tree
1828                     if (strcmp(core_class,cname)) {
1829                             if (!join_hash) continue;
1830
1831                             if (join_hash->type == JSON_STRING) {
1832                                     string = jsonObjectToSimpleString(join_hash);
1833                                     found = strcmp(string,cname) ? NULL : jsonParseString("{\"1\":\"1\"}");
1834                                     free(string);
1835                             } else {
1836                                     found = jsonObjectFindPath(join_hash, "//%s", cname);
1837                             }
1838
1839                             if (!found->size) {
1840                                     jsonObjectFree(found);
1841                                     continue;
1842                             }
1843
1844                             jsonObjectFree(found);
1845                     }
1846
1847                     // stitch together the column list ...
1848                     jsonIterator* select_itr = jsonNewIterator( selclass );
1849                     while ( (selfield = jsonIteratorNext( select_itr )) ) {
1850
1851                             char* __column = NULL;
1852                             char* __alias = NULL;
1853
1854                             // ... if it's a sstring, just toss it on the pile
1855                             if (selfield->type == JSON_STRING) {
1856
1857                                     // again, just to be safe
1858                                     char* _requested_col = jsonObjectToSimpleString(selfield);
1859                                     osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), _requested_col );
1860                                     free(_requested_col);
1861
1862                                     if (!field) continue;
1863                                     __column = strdup(osrfHashGet(field, "name"));
1864
1865                                     if (first) {
1866                                             first = 0;
1867                                     } else {
1868                                             buffer_add(select_buf, ",");
1869                                     }
1870
1871                     if (locale) {
1872                             char* i18n = osrfHashGet(field, "i18n");
1873                                     if (flags & DISABLE_I18N)
1874                             i18n = NULL;
1875
1876                             if ( i18n && !strncasecmp("true", i18n, 4)) {
1877                                 char* pkey = osrfHashGet(idlClass, "primarykey");
1878                                 char* tname = osrfHashGet(idlClass, "tablename");
1879
1880                             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);
1881                         } else {
1882                                             buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, __column, __column);
1883                         }
1884                     } else {
1885                                         buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, __column, __column);
1886                     }
1887
1888                             // ... but it could be an object, in which case we check for a Field Transform
1889                             } else {
1890
1891                                     __column = jsonObjectToSimpleString( jsonObjectGetKeyConst( selfield, "column" ) );
1892
1893                                     // again, just to be safe
1894                                     osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), __column );
1895                                     if (!field) continue;
1896                                     const char* fname = osrfHashGet(field, "name");
1897
1898                                     if (first) {
1899                                             first = 0;
1900                                     } else {
1901                                             buffer_add(select_buf, ",");
1902                                     }
1903
1904                                     if ((tmp_const = jsonObjectGetKeyConst( selfield, "alias" ))) {
1905                                             __alias = jsonObjectToSimpleString( tmp_const );
1906                                     } else {
1907                                             __alias = strdup(__column);
1908                                     }
1909
1910                                     if (jsonObjectGetKeyConst( selfield, "transform" )) {
1911                                             free(__column);
1912                                             __column = searchFieldTransform(cname, field, selfield);
1913                                             buffer_fadd(select_buf, " %s AS \"%s\"", __column, __alias);
1914                                     } else {
1915                         if (locale) {
1916                                     char* i18n = osrfHashGet(field, "i18n");
1917                                         if (flags & DISABLE_I18N)
1918                                 i18n = NULL;
1919     
1920                                     if ( i18n && !strncasecmp("true", i18n, 4)) {
1921                                     char* pkey = osrfHashGet(idlClass, "primarykey");
1922                                     char* tname = osrfHashGet(idlClass, "tablename");
1923
1924                                 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);
1925                             } else {
1926                                                     buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, fname, __alias);
1927                             }
1928                         } else {
1929                                                 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, fname, __alias);
1930                         }
1931                                     }
1932                             }
1933
1934                             if (is_agg->size || (flags & SELECT_DISTINCT)) {
1935
1936                                     if (!jsonBoolIsTrue( jsonObjectGetKey( selfield, "aggregate" ) )) {
1937                                             if (gfirst) {
1938                                                     gfirst = 0;
1939                                             } else {
1940                                                     buffer_add(group_buf, ",");
1941                                             }
1942
1943                                             buffer_fadd(group_buf, " %d", sel_pos);
1944                                     /*
1945                                     } else if (is_agg = jsonObjectGetKey( selfield, "having" )) {
1946                                             if (gfirst) {
1947                                                     gfirst = 0;
1948                                             } else {
1949                                                     buffer_add(group_buf, ",");
1950                                             }
1951
1952                                             __column = searchFieldTransform(cname, field, selfield);
1953                                             buffer_fadd(group_buf, " %s", __column);
1954                                             __column = searchFieldTransform(cname, field, selfield);
1955                                     */
1956                                     }
1957                             }
1958
1959                             if (__column) free(__column);
1960                             if (__alias) free(__alias);
1961
1962                             sel_pos++;
1963                     }
1964
1965             // jsonIteratorFree(select_itr);
1966             }
1967
1968         // jsonIteratorFree(selclass_itr);
1969
1970             if (is_agg) jsonObjectFree(is_agg);
1971     } else {
1972         buffer_add(select_buf, "*");
1973     }
1974
1975
1976         char* col_list = buffer_release(select_buf);
1977         char* table = NULL;
1978     if (!from_function) table = getSourceDefinition(core_meta);
1979     else table = searchValueTransform(join_hash);
1980
1981         // Put it all together
1982         buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\" ", col_list, table, core_class );
1983         free(col_list);
1984         free(table);
1985
1986     if (!from_function) {
1987             // Now, walk the join tree and add that clause
1988             if ( join_hash ) {
1989                     char* join_clause = searchJOIN( join_hash, core_meta );
1990                     buffer_add(sql_buf, join_clause);
1991                     free(join_clause);
1992             }
1993
1994             if ( search_hash ) {
1995                     buffer_add(sql_buf, " WHERE ");
1996
1997                     // and it's on the the WHERE clause
1998                     char* pred = searchWHERE( search_hash, core_meta, AND_OP_JOIN );
1999
2000                     if (!pred) {
2001                             osrfAppSessionStatus(
2002                                     ctx->session,
2003                                     OSRF_STATUS_INTERNALSERVERERROR,
2004                                     "osrfMethodException",
2005                                     ctx->request,
2006                                     "Severe query error in WHERE predicate -- see error log for more details"
2007                             );
2008                             free(core_class);
2009                             buffer_free(having_buf);
2010                             buffer_free(group_buf);
2011                             buffer_free(order_buf);
2012                             buffer_free(sql_buf);
2013                             if (defaultselhash) jsonObjectFree(defaultselhash);
2014                             return NULL;
2015                     } else {
2016                             buffer_add(sql_buf, pred);
2017                             free(pred);
2018                     }
2019         }
2020
2021             if ( having_hash ) {
2022                     buffer_add(sql_buf, " HAVING ");
2023
2024                     // and it's on the the WHERE clause
2025                     char* pred = searchWHERE( having_hash, core_meta, AND_OP_JOIN );
2026
2027                     if (!pred) {
2028                             osrfAppSessionStatus(
2029                                     ctx->session,
2030                                     OSRF_STATUS_INTERNALSERVERERROR,
2031                                     "osrfMethodException",
2032                                     ctx->request,
2033                                     "Severe query error in HAVING predicate -- see error log for more details"
2034                             );
2035                             free(core_class);
2036                             buffer_free(having_buf);
2037                             buffer_free(group_buf);
2038                             buffer_free(order_buf);
2039                             buffer_free(sql_buf);
2040                             if (defaultselhash) jsonObjectFree(defaultselhash);
2041                             return NULL;
2042                     } else {
2043                             buffer_add(sql_buf, pred);
2044                             free(pred);
2045                     }
2046             }
2047
2048             first = 1;
2049             jsonIterator* class_itr = jsonNewIterator( order_hash );
2050             while ( (snode = jsonIteratorNext( class_itr )) ) {
2051
2052                     if (!jsonObjectGetKeyConst(selhash,class_itr->key))
2053                             continue;
2054
2055                     if ( snode->type == JSON_HASH ) {
2056
2057                         jsonIterator* order_itr = jsonNewIterator( snode );
2058                             while ( (onode = jsonIteratorNext( order_itr )) ) {
2059
2060                                     if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
2061                                             continue;
2062
2063                                     char* direction = NULL;
2064                                     if ( onode->type == JSON_HASH ) {
2065                                             if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
2066                                                     string = searchFieldTransform(
2067                                                             class_itr->key,
2068                                                             oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
2069                                                             onode
2070                                                     );
2071                                             } else {
2072                                                     growing_buffer* field_buf = buffer_init(16);
2073                                                     buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
2074                                                     string = buffer_release(field_buf);
2075                                             }
2076
2077                                             if ( (tmp_const = jsonObjectGetKeyConst( onode, "direction" )) ) {
2078                                                     direction = jsonObjectToSimpleString(tmp_const);
2079                                                     if (!strncasecmp(direction, "d", 1)) {
2080                                                             free(direction);
2081                                                             direction = " DESC";
2082                                                     } else {
2083                                                             free(direction);
2084                                                             direction = " ASC";
2085                                                     }
2086                                             }
2087
2088                                     } else {
2089                                             string = strdup(order_itr->key);
2090                                             direction = jsonObjectToSimpleString(onode);
2091                                             if (!strncasecmp(direction, "d", 1)) {
2092                                                     free(direction);
2093                                                     direction = " DESC";
2094                                             } else {
2095                                                     free(direction);
2096                                                     direction = " ASC";
2097                                             }
2098                                     }
2099
2100                                     if (first) {
2101                                             first = 0;
2102                                     } else {
2103                                             buffer_add(order_buf, ", ");
2104                                     }
2105
2106                                     buffer_add(order_buf, string);
2107                                     free(string);
2108
2109                                     if (direction) {
2110                                             buffer_add(order_buf, direction);
2111                                     }
2112
2113                             }
2114                 // jsonIteratorFree(order_itr);
2115
2116                     } else if ( snode->type == JSON_ARRAY ) {
2117
2118                         jsonIterator* order_itr = jsonNewIterator( snode );
2119                             while ( (onode = jsonIteratorNext( order_itr )) ) {
2120
2121                                     char* _f = jsonObjectToSimpleString( onode );
2122
2123                                     if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, _f))
2124                                             continue;
2125
2126                                     if (first) {
2127                                             first = 0;
2128                                     } else {
2129                                             buffer_add(order_buf, ", ");
2130                                     }
2131
2132                                     buffer_add(order_buf, _f);
2133                                     free(_f);
2134
2135                             }
2136                 // jsonIteratorFree(order_itr);
2137
2138
2139                     // IT'S THE OOOOOOOOOOOLD STYLE!
2140                     } else {
2141                             osrfLogError(OSRF_LOG_MARK, "%s: Possible SQL injection attempt; direct order by is not allowed", MODULENAME);
2142                             osrfAppSessionStatus(
2143                                     ctx->session,
2144                                     OSRF_STATUS_INTERNALSERVERERROR,
2145                                     "osrfMethodException",
2146                                     ctx->request,
2147                                     "Severe query error -- see error log for more details"
2148                             );
2149
2150                             free(core_class);
2151                             buffer_free(having_buf);
2152                             buffer_free(group_buf);
2153                             buffer_free(order_buf);
2154                             buffer_free(sql_buf);
2155                             if (defaultselhash) jsonObjectFree(defaultselhash);
2156                             jsonIteratorFree(class_itr);
2157                             return NULL;
2158                     }
2159
2160             }
2161     }
2162
2163     // jsonIteratorFree(class_itr);
2164
2165         string = buffer_release(group_buf);
2166
2167         if (strlen(string)) {
2168                 buffer_fadd(
2169                         sql_buf,
2170                         " GROUP BY %s",
2171                         string
2172                 );
2173         }
2174
2175         free(string);
2176
2177         string = buffer_release(having_buf);
2178  
2179         if (strlen(string)) {
2180                 buffer_fadd(
2181                         sql_buf,
2182                         " HAVING %s",
2183                         string
2184                 );
2185         }
2186
2187         free(string);
2188
2189         string = buffer_release(order_buf);
2190
2191         if (strlen(string)) {
2192                 buffer_fadd(
2193                         sql_buf,
2194                         " ORDER BY %s",
2195                         string
2196                 );
2197         }
2198
2199         free(string);
2200
2201         if ( limit ){
2202                 string = jsonObjectToSimpleString(limit);
2203                 buffer_fadd( sql_buf, " LIMIT %d", atoi(string) );
2204                 free(string);
2205         }
2206
2207         if (offset) {
2208                 string = jsonObjectToSimpleString(offset);
2209                 buffer_fadd( sql_buf, " OFFSET %d", atoi(string) );
2210                 free(string);
2211         }
2212
2213         buffer_add(sql_buf, ";");
2214
2215         free(core_class);
2216         if (defaultselhash) jsonObjectFree(defaultselhash);
2217
2218         return buffer_release(sql_buf);
2219
2220 }
2221
2222 static char* buildSELECT ( jsonObject* search_hash, jsonObject* order_hash, osrfHash* meta, osrfMethodContext* ctx ) {
2223
2224         const char* locale = osrf_message_get_last_locale();
2225
2226         osrfHash* fields = osrfHashGet(meta, "fields");
2227         char* core_class = osrfHashGet(meta, "classname");
2228
2229         const jsonObject* join_hash = jsonObjectGetKeyConst( order_hash, "join" );
2230
2231         jsonObject* node = NULL;
2232         jsonObject* snode = NULL;
2233         jsonObject* onode = NULL;
2234         const jsonObject* _tmp = NULL;
2235         jsonObject* selhash = NULL;
2236         jsonObject* defaultselhash = NULL;
2237
2238         growing_buffer* sql_buf = buffer_init(128);
2239         growing_buffer* select_buf = buffer_init(128);
2240
2241         if ( !(selhash = jsonObjectGetKey( order_hash, "select" )) ) {
2242                 defaultselhash = jsonNewObjectType(JSON_HASH);
2243                 selhash = defaultselhash;
2244         }
2245         
2246         if ( !jsonObjectGetKeyConst(selhash,core_class) ) {
2247                 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2248                 jsonObject* flist = jsonObjectGetKey( selhash, core_class );
2249                 
2250                 int i = 0;
2251                 char* field;
2252
2253                 osrfStringArray* keys = osrfHashKeys( fields );
2254                 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
2255                         if ( strcasecmp( "true", osrfHashGet( osrfHashGet( fields, field ), "virtual" ) ) )
2256                                 jsonObjectPush( flist, jsonNewObject( field ) );
2257                 }
2258                 osrfStringArrayFree(keys);
2259         }
2260
2261         int first = 1;
2262         jsonIterator* class_itr = jsonNewIterator( selhash );
2263         while ( (snode = jsonIteratorNext( class_itr )) ) {
2264
2265                 osrfHash* idlClass = osrfHashGet( oilsIDL(), class_itr->key );
2266                 if (!idlClass) continue;
2267                 char* cname = osrfHashGet(idlClass, "classname");
2268
2269                 if (strcmp(core_class,class_itr->key)) {
2270                         if (!join_hash) continue;
2271
2272                         jsonObject* found =  jsonObjectFindPath(join_hash, "//%s", class_itr->key);
2273                         if (!found->size) {
2274                                 jsonObjectFree(found);
2275                                 continue;
2276                         }
2277
2278                         jsonObjectFree(found);
2279                 }
2280
2281                 jsonIterator* select_itr = jsonNewIterator( snode );
2282                 while ( (node = jsonIteratorNext( select_itr )) ) {
2283                         char* item_str = jsonObjectToSimpleString(node);
2284                         osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), item_str );
2285                         free(item_str);
2286                         char* fname = osrfHashGet(field, "name");
2287
2288                         if (!field) continue;
2289
2290                         if (first) {
2291                                 first = 0;
2292                         } else {
2293                                 buffer_add(select_buf, ",");
2294                         }
2295
2296             if (locale) {
2297                         char* i18n = osrfHashGet(field, "i18n");
2298                     if (jsonBoolIsTrue(jsonObjectGetKey( order_hash, "no_i18n" )))
2299                     i18n = NULL;
2300
2301                         if ( i18n && !strncasecmp("true", i18n, 4)) {
2302                         char* pkey = osrfHashGet(idlClass, "primarykey");
2303                         char* tname = osrfHashGet(idlClass, "tablename");
2304
2305                     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);
2306                 } else {
2307                                 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
2308                 }
2309             } else {
2310                             buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
2311             }
2312                 }
2313
2314         jsonIteratorFree(select_itr);
2315         }
2316
2317     jsonIteratorFree(class_itr);
2318
2319         char* col_list = buffer_release(select_buf);
2320         char* table = getSourceDefinition(meta);
2321
2322         buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\"", col_list, table, core_class );
2323         free(col_list);
2324         free(table);
2325
2326         if ( join_hash ) {
2327                 char* join_clause = searchJOIN( join_hash, meta );
2328                 buffer_fadd(sql_buf, " %s", join_clause);
2329                 free(join_clause);
2330         }
2331
2332         char* tmpsql = buffer_data(sql_buf);
2333         osrfLogDebug(OSRF_LOG_MARK, "%s pre-predicate SQL =  %s", MODULENAME, tmpsql);
2334         free(tmpsql);
2335
2336         buffer_add(sql_buf, " WHERE ");
2337
2338         char* pred = searchWHERE( search_hash, meta, AND_OP_JOIN );
2339         if (!pred) {
2340                 osrfAppSessionStatus(
2341                         ctx->session,
2342                         OSRF_STATUS_INTERNALSERVERERROR,
2343                                 "osrfMethodException",
2344                                 ctx->request,
2345                                 "Severe query error -- see error log for more details"
2346                         );
2347                 buffer_free(sql_buf);
2348                 if(defaultselhash) jsonObjectFree(defaultselhash);
2349                 return NULL;
2350         } else {
2351                 buffer_add(sql_buf, pred);
2352                 free(pred);
2353         }
2354
2355         if (order_hash) {
2356                 char* string = NULL;
2357                 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "order_by" )) ){
2358
2359                         growing_buffer* order_buf = buffer_init(128);
2360
2361                         first = 1;
2362                         jsonIterator* class_itr = jsonNewIterator( _tmp );
2363                         while ( (snode = jsonIteratorNext( class_itr )) ) {
2364
2365                                 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
2366                                         continue;
2367
2368                                 if ( snode->type == JSON_HASH ) {
2369
2370                                         jsonIterator* order_itr = jsonNewIterator( snode );
2371                                         while ( (onode = jsonIteratorNext( order_itr )) ) {
2372
2373                                                 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
2374                                                         continue;
2375
2376                                                 char* direction = NULL;
2377                                                 if ( onode->type == JSON_HASH ) {
2378                                                         if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
2379                                                                 string = searchFieldTransform(
2380                                                                         class_itr->key,
2381                                                                         oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
2382                                                                         onode
2383                                                                 );
2384                                                         } else {
2385                                                                 growing_buffer* field_buf = buffer_init(16);
2386                                                                 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
2387                                                                 string = buffer_release(field_buf);
2388                                                         }
2389
2390                                                         if ( (_tmp = jsonObjectGetKeyConst( onode, "direction" )) ) {
2391                                                                 direction = jsonObjectToSimpleString(_tmp);
2392                                                                 if (!strncasecmp(direction, "d", 1)) {
2393                                                                         free(direction);
2394                                                                         direction = " DESC";
2395                                                                 } else {
2396                                                                         free(direction);
2397                                                                         direction = " ASC";
2398                                                                 }
2399                                                         }
2400
2401                                                 } else {
2402                                                         string = strdup(order_itr->key);
2403                                                         direction = jsonObjectToSimpleString(onode);
2404                                                         if (!strncasecmp(direction, "d", 1)) {
2405                                                                 free(direction);
2406                                                                 direction = " DESC";
2407                                                         } else {
2408                                                                 free(direction);
2409                                                                 direction = " ASC";
2410                                                         }
2411                                                 }
2412
2413                                                 if (first) {
2414                                                         first = 0;
2415                                                 } else {
2416                                                         buffer_add(order_buf, ", ");
2417                                                 }
2418
2419                                                 buffer_add(order_buf, string);
2420                                                 free(string);
2421
2422                                                 if (direction) {
2423                                                         buffer_add(order_buf, direction);
2424                                                 }
2425
2426                                         }
2427
2428                     jsonIteratorFree(order_itr);
2429
2430                                 } else {
2431                                         string = jsonObjectToSimpleString(snode);
2432                                         buffer_add(order_buf, string);
2433                                         free(string);
2434                                         break;
2435                                 }
2436
2437                         }
2438
2439             jsonIteratorFree(class_itr);
2440
2441                         string = buffer_release(order_buf);
2442
2443                         if (strlen(string)) {
2444                                 buffer_fadd(
2445                                         sql_buf,
2446                                         " ORDER BY %s",
2447                                         string
2448                                 );
2449                         }
2450
2451                         free(string);
2452                 }
2453
2454                 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "limit" )) ){
2455                         string = jsonObjectToSimpleString(_tmp);
2456                         buffer_fadd(
2457                                 sql_buf,
2458                                 " LIMIT %d",
2459                                 atoi(string)
2460                         );
2461                         free(string);
2462                 }
2463
2464                 _tmp = jsonObjectGetKeyConst( order_hash, "offset" );
2465                 if (_tmp) {
2466                         string = jsonObjectToSimpleString(_tmp);
2467                         buffer_fadd(
2468                                 sql_buf,
2469                                 " OFFSET %d",
2470                                 atoi(string)
2471                         );
2472                         free(string);
2473                 }
2474         }
2475
2476         if (defaultselhash) jsonObjectFree(defaultselhash);
2477
2478         buffer_add(sql_buf, ";");
2479         return buffer_release(sql_buf);
2480 }
2481
2482 int doJSONSearch ( osrfMethodContext* ctx ) {
2483         OSRF_METHOD_VERIFY_CONTEXT(ctx);
2484         osrfLogDebug(OSRF_LOG_MARK, "Recieved query request");
2485
2486         int err = 0;
2487
2488         // XXX for now...
2489         dbhandle = writehandle;
2490
2491         jsonObject* hash = jsonObjectGetIndex(ctx->params, 0);
2492
2493     int flags = 0;
2494
2495         if (jsonBoolIsTrue(jsonObjectGetKey( hash, "distinct" )))
2496          flags |= SELECT_DISTINCT;
2497
2498         if ( ((int)jsonObjectGetNumber(jsonObjectGetKey( hash, "distinct" ))) == 1 ) // support 1/0 for perl's sake
2499          flags |= SELECT_DISTINCT;
2500
2501         if (jsonBoolIsTrue(jsonObjectGetKey( hash, "no_i18n" )))
2502          flags |= DISABLE_I18N;
2503
2504         if ( ((int)jsonObjectGetNumber(jsonObjectGetKey( hash, "no_i18n" ))) == 1 ) // support 1/0 for perl's sake
2505          flags |= DISABLE_I18N;
2506
2507         osrfLogDebug(OSRF_LOG_MARK, "Building SQL ...");
2508         char* sql = SELECT(
2509                         ctx,
2510                         jsonObjectGetKey( hash, "select" ),
2511                         jsonObjectGetKey( hash, "from" ),
2512                         jsonObjectGetKey( hash, "where" ),
2513                         jsonObjectGetKey( hash, "having" ),
2514                         jsonObjectGetKey( hash, "order_by" ),
2515                         jsonObjectGetKey( hash, "limit" ),
2516                         jsonObjectGetKey( hash, "offset" ),
2517                         flags
2518         );
2519
2520         if (!sql) {
2521                 err = -1;
2522                 return err;
2523         }
2524         
2525         osrfLogDebug(OSRF_LOG_MARK, "%s SQL =  %s", MODULENAME, sql);
2526         dbi_result result = dbi_conn_query(dbhandle, sql);
2527
2528         if(result) {
2529                 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
2530
2531                 if (dbi_result_first_row(result)) {
2532                         /* JSONify the result */
2533                         osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
2534
2535                         do {
2536                                 jsonObject* return_val = oilsMakeJSONFromResult( result );
2537                                 osrfAppRespond( ctx, return_val );
2538                 jsonObjectFree( return_val );
2539                         } while (dbi_result_next_row(result));
2540
2541                 } else {
2542                         osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
2543                 }
2544
2545                 osrfAppRespondComplete( ctx, NULL );
2546
2547                 /* clean up the query */
2548                 dbi_result_free(result); 
2549
2550         } else {
2551                 err = -1;
2552                 osrfLogError(OSRF_LOG_MARK, "%s: Error with query [%s]", MODULENAME, sql);
2553                 osrfAppSessionStatus(
2554                         ctx->session,
2555                         OSRF_STATUS_INTERNALSERVERERROR,
2556                         "osrfMethodException",
2557                         ctx->request,
2558                         "Severe query error -- see error log for more details"
2559                 );
2560         }
2561
2562         free(sql);
2563         return err;
2564 }
2565
2566 static jsonObject* doFieldmapperSearch ( osrfMethodContext* ctx, osrfHash* meta,
2567                 const jsonObject* params, int* err ) {
2568
2569         // XXX for now...
2570         dbhandle = writehandle;
2571
2572         osrfHash* links = osrfHashGet(meta, "links");
2573         osrfHash* fields = osrfHashGet(meta, "fields");
2574         char* core_class = osrfHashGet(meta, "classname");
2575         char* pkey = osrfHashGet(meta, "primarykey");
2576
2577         const jsonObject* _tmp;
2578         jsonObject* obj;
2579         jsonObject* search_hash = jsonObjectGetIndex(params, 0);
2580         jsonObject* order_hash = jsonObjectGetIndex(params, 1);
2581
2582         char* sql = buildSELECT( search_hash, order_hash, meta, ctx );
2583         if (!sql) {
2584                 *err = -1;
2585                 return NULL;
2586         }
2587         
2588         osrfLogDebug(OSRF_LOG_MARK, "%s SQL =  %s", MODULENAME, sql);
2589         dbi_result result = dbi_conn_query(dbhandle, sql);
2590
2591         jsonObject* res_list = jsonNewObjectType(JSON_ARRAY);
2592         if(result) {
2593                 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
2594                 osrfHash* dedup = osrfNewHash();
2595
2596                 if (dbi_result_first_row(result)) {
2597                         /* JSONify the result */
2598                         osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
2599                         do {
2600                                 obj = oilsMakeFieldmapperFromResult( result, meta );
2601                                 int pkey_pos = atoi( osrfHashGet( osrfHashGet( fields, pkey ), "array_position" ) );
2602                                 char* pkey_val = jsonObjectToSimpleString( jsonObjectGetIndex( obj, pkey_pos ) );
2603                                 if ( osrfHashGet( dedup, pkey_val ) ) {
2604                                         jsonObjectFree(obj);
2605                                         free(pkey_val);
2606                                 } else {
2607                                         osrfHashSet( dedup, pkey_val, pkey_val );
2608                                         jsonObjectPush(res_list, obj);
2609                                 }
2610                         } while (dbi_result_next_row(result));
2611                 } else {
2612                         osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
2613                 }
2614
2615                 osrfHashFree(dedup);
2616
2617                 /* clean up the query */
2618                 dbi_result_free(result); 
2619
2620         } else {
2621                 osrfLogError(OSRF_LOG_MARK, "%s: Error retrieving %s with query [%s]", MODULENAME, osrfHashGet(meta, "fieldmapper"), sql);
2622                 osrfAppSessionStatus(
2623                         ctx->session,
2624                         OSRF_STATUS_INTERNALSERVERERROR,
2625                         "osrfMethodException",
2626                         ctx->request,
2627                         "Severe query error -- see error log for more details"
2628                 );
2629                 *err = -1;
2630                 free(sql);
2631                 jsonObjectFree(res_list);
2632                 return jsonNULL;
2633
2634         }
2635
2636         free(sql);
2637
2638         if (res_list->size && order_hash) {
2639                 _tmp = jsonObjectGetKeyConst( order_hash, "flesh" );
2640                 if (_tmp) {
2641                         int x = (int)jsonObjectGetNumber(_tmp);
2642                         if (x == -1 || x > max_flesh_depth) x = max_flesh_depth;
2643
2644                         const jsonObject* temp_blob;
2645                         if ((temp_blob = jsonObjectGetKeyConst( order_hash, "flesh_fields" )) && x > 0) {
2646
2647                                 jsonObject* flesh_blob = jsonObjectClone( temp_blob );
2648                                 const jsonObject* flesh_fields = jsonObjectGetKeyConst( flesh_blob, core_class );
2649
2650                                 osrfStringArray* link_fields = NULL;
2651
2652                                 if (flesh_fields) {
2653                                         if (flesh_fields->size == 1) {
2654                                                 char* _t = jsonObjectToSimpleString( jsonObjectGetIndex( flesh_fields, 0 ) );
2655                                                 if (!strcmp(_t,"*")) link_fields = osrfHashKeys( links );
2656                                                 free(_t);
2657                                         }
2658
2659                                         if (!link_fields) {
2660                                                 jsonObject* _f;
2661                                                 link_fields = osrfNewStringArray(1);
2662                                                 jsonIterator* _i = jsonNewIterator( flesh_fields );
2663                                                 while ((_f = jsonIteratorNext( _i ))) {
2664                                                         osrfStringArrayAdd( link_fields, jsonObjectToSimpleString( _f ) );
2665                                                 }
2666                         jsonIteratorFree(_i);
2667                                         }
2668                                 }
2669
2670                                 jsonObject* cur;
2671                                 jsonIterator* itr = jsonNewIterator( res_list );
2672                                 while ((cur = jsonIteratorNext( itr ))) {
2673
2674                                         int i = 0;
2675                                         char* link_field;
2676                                         
2677                                         while ( (link_field = osrfStringArrayGetString(link_fields, i++)) ) {
2678
2679                                                 osrfLogDebug(OSRF_LOG_MARK, "Starting to flesh %s", link_field);
2680
2681                                                 osrfHash* kid_link = osrfHashGet(links, link_field);
2682                                                 if (!kid_link) continue;
2683
2684                                                 osrfHash* field = osrfHashGet(fields, link_field);
2685                                                 if (!field) continue;
2686
2687                                                 osrfHash* value_field = field;
2688
2689                                                 osrfHash* kid_idl = osrfHashGet(oilsIDL(), osrfHashGet(kid_link, "class"));
2690                                                 if (!kid_idl) continue;
2691
2692                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
2693                                                         value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
2694                                                 }
2695                                                         
2696                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) { // might_have
2697                                                         value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
2698                                                 }
2699
2700                                                 osrfStringArray* link_map = osrfHashGet( kid_link, "map" );
2701
2702                                                 if (link_map->size > 0) {
2703                                                         jsonObject* _kid_key = jsonNewObjectType(JSON_ARRAY);
2704                                                         jsonObjectPush(
2705                                                                 _kid_key,
2706                                                                 jsonNewObject( osrfStringArrayGetString( link_map, 0 ) )
2707                                                         );
2708
2709                                                         jsonObjectSetKey(
2710                                                                 flesh_blob,
2711                                                                 osrfHashGet(kid_link, "class"),
2712                                                                 _kid_key
2713                                                         );
2714                                                 };
2715
2716                                                 osrfLogDebug(
2717                                                         OSRF_LOG_MARK,
2718                                                         "Link field: %s, remote class: %s, fkey: %s, reltype: %s",
2719                                                         osrfHashGet(kid_link, "field"),
2720                                                         osrfHashGet(kid_link, "class"),
2721                                                         osrfHashGet(kid_link, "key"),
2722                                                         osrfHashGet(kid_link, "reltype")
2723                                                 );
2724
2725                                                 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
2726                                                 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // search hash
2727                                                 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // order/flesh hash
2728
2729                                                 osrfLogDebug(OSRF_LOG_MARK, "Creating dummy params object...");
2730
2731                                                 char* search_key =
2732                                                 jsonObjectToSimpleString(
2733                                                         jsonObjectGetIndex(
2734                                                                 cur,
2735                                                                 atoi( osrfHashGet(value_field, "array_position") )
2736                                                         )
2737                                                 );
2738
2739                                                 if (!search_key) {
2740                                                         osrfLogDebug(OSRF_LOG_MARK, "Nothing to search for!");
2741                                                         continue;
2742                                                 }
2743                                                         
2744                                                 jsonObjectSetKey(
2745                                                         jsonObjectGetIndex(fake_params, 0),
2746                                                         osrfHashGet(kid_link, "key"),
2747                                                         jsonNewObject( search_key )
2748                                                 );
2749
2750                                                 free(search_key);
2751
2752
2753                                                 jsonObjectSetKey(
2754                                                         jsonObjectGetIndex(fake_params, 1),
2755                                                         "flesh",
2756                                                         jsonNewNumberObject( (double)(x - 1 + link_map->size) )
2757                                                 );
2758
2759                                                 if (flesh_blob)
2760                                                         jsonObjectSetKey( jsonObjectGetIndex(fake_params, 1), "flesh_fields", jsonObjectClone(flesh_blob) );
2761
2762                                                 if (jsonObjectGetKeyConst(order_hash, "order_by")) {
2763                                                         jsonObjectSetKey(
2764                                                                 jsonObjectGetIndex(fake_params, 1),
2765                                                                 "order_by",
2766                                                                 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "order_by"))
2767                                                         );
2768                                                 }
2769
2770                                                 if (jsonObjectGetKeyConst(order_hash, "select")) {
2771                                                         jsonObjectSetKey(
2772                                                                 jsonObjectGetIndex(fake_params, 1),
2773                                                                 "select",
2774                                                                 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "select"))
2775                                                         );
2776                                                 }
2777
2778                                                 jsonObject* kids = doFieldmapperSearch(ctx, kid_idl, fake_params, err);
2779
2780                                                 if(*err) {
2781                                                         jsonObjectFree( fake_params );
2782                                                         osrfStringArrayFree(link_fields);
2783                                                         jsonIteratorFree(itr);
2784                                                         jsonObjectFree(res_list);
2785                                                         jsonObjectFree(flesh_blob);
2786                                                         return jsonNULL;
2787                                                 }
2788
2789                                                 osrfLogDebug(OSRF_LOG_MARK, "Search for %s return %d linked objects", osrfHashGet(kid_link, "class"), kids->size);
2790
2791                                                 jsonObject* X = NULL;
2792                                                 if ( link_map->size > 0 && kids->size > 0 ) {
2793                                                         X = kids;
2794                                                         kids = jsonNewObjectType(JSON_ARRAY);
2795
2796                                                         jsonObject* _k_node;
2797                                                         jsonIterator* _k = jsonNewIterator( X );
2798                                                         while ((_k_node = jsonIteratorNext( _k ))) {
2799                                                                 jsonObjectPush(
2800                                                                         kids,
2801                                                                         jsonObjectClone(
2802                                                                                 jsonObjectGetIndex(
2803                                                                                         _k_node,
2804                                                                                         (unsigned long)atoi(
2805                                                                                                 osrfHashGet(
2806                                                                                                         osrfHashGet(
2807                                                                                                                 osrfHashGet(
2808                                                                                                                         osrfHashGet(
2809                                                                                                                                 oilsIDL(),
2810                                                                                                                                 osrfHashGet(kid_link, "class")
2811                                                                                                                         ),
2812                                                                                                                         "fields"
2813                                                                                                                 ),
2814                                                                                                                 osrfStringArrayGetString( link_map, 0 )
2815                                                                                                         ),
2816                                                                                                         "array_position"
2817                                                                                                 )
2818                                                                                         )
2819                                                                                 )
2820                                                                         )
2821                                                                 );
2822                                                         }
2823                                                         jsonIteratorFree(_k);
2824                                                 }
2825
2826                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_a" )) || !(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) {
2827                                                         osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
2828                                                         jsonObjectSetIndex(
2829                                                                 cur,
2830                                                                 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
2831                                                                 jsonObjectClone( jsonObjectGetIndex(kids, 0) )
2832                                                         );
2833                                                 }
2834
2835                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
2836                                                     &n