allow NULL as a parameter in transforms and FROM clause functions
[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 (func_item->type == JSON_NULL) {
1132                         buffer_add( sql_buf, "NULL" );
1133                 } else if ( dbi_conn_quote_string(dbhandle, &val) ) {
1134                         buffer_fadd( sql_buf, "%s", val );
1135                 } else {
1136                         osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1137                         free(val);
1138                         buffer_free(sql_buf);
1139                         return NULL;
1140                 }
1141
1142                 free(val);
1143         }
1144
1145         buffer_add(
1146                 sql_buf,
1147                 " )"
1148         );
1149
1150         return buffer_release(sql_buf);
1151 }
1152
1153 static char* searchFunctionPredicate (const char* class, osrfHash* field,
1154                 const jsonObject* node, const char* node_key) {
1155         growing_buffer* sql_buf = buffer_init(32);
1156
1157         char* val = searchValueTransform(node);
1158         
1159         buffer_fadd(
1160                 sql_buf,
1161                 "\"%s\".%s %s %s",
1162                 class,
1163                 osrfHashGet(field, "name"),
1164                 node_key,
1165                 val
1166         );
1167
1168         free(val);
1169
1170         return buffer_release(sql_buf);
1171 }
1172
1173 static char* searchFieldTransform (const char* class, osrfHash* field, const jsonObject* node) {
1174         growing_buffer* sql_buf = buffer_init(32);
1175         
1176         char* field_transform = jsonObjectToSimpleString( jsonObjectGetKeyConst( node, "transform" ) );
1177         char* transform_subcolumn = jsonObjectToSimpleString( jsonObjectGetKeyConst( node, "result_field" ) );
1178
1179         if (field_transform) {
1180                 buffer_fadd( sql_buf, "%s(\"%s\".%s", field_transform, class, osrfHashGet(field, "name"));
1181             const jsonObject* array = jsonObjectGetKeyConst( node, "params" );
1182
1183         if (array) {
1184                 int func_item_index = 0;
1185                 jsonObject* func_item;
1186                 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1187
1188                         char* val = jsonObjectToSimpleString(func_item);
1189
1190                     if ( !val ) {
1191                             buffer_add( sql_buf, ",NULL" );
1192                     } else if ( dbi_conn_quote_string(dbhandle, &val) ) {
1193                             buffer_fadd( sql_buf, ",%s", val );
1194                         } else {
1195                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1196                             free(field_transform);
1197                                         free(val);
1198                                 buffer_free(sql_buf);
1199                                 return NULL;
1200                 }
1201                                 free(val);
1202                         }
1203
1204         }
1205
1206         buffer_add(
1207                 sql_buf,
1208                 " )"
1209         );
1210
1211         } else {
1212                 buffer_fadd( sql_buf, "\"%s\".%s", class, osrfHashGet(field, "name"));
1213         }
1214
1215     if (transform_subcolumn) {
1216         char * tmp = buffer_release(sql_buf);
1217         sql_buf = buffer_init(32);
1218         buffer_fadd(
1219             sql_buf,
1220             "(%s).\"%s\"",
1221             tmp,
1222             transform_subcolumn
1223         );
1224         free(tmp);
1225     }
1226  
1227         if (field_transform) free(field_transform);
1228         if (transform_subcolumn) free(transform_subcolumn);
1229
1230         return buffer_release(sql_buf);
1231 }
1232
1233 static char* searchFieldTransformPredicate (const char* class, osrfHash* field, jsonObject* node, const char* node_key) {
1234         char* field_transform = searchFieldTransform( class, field, node );
1235         char* value = NULL;
1236
1237         if (!jsonObjectGetKeyConst( node, "value" )) {
1238                 value = searchWHERE( node, osrfHashGet( oilsIDL(), class ), AND_OP_JOIN );
1239         } else if (jsonObjectGetKeyConst( node, "value" )->type == JSON_ARRAY) {
1240                 value = searchValueTransform(jsonObjectGetKeyConst( node, "value" ));
1241         } else if (jsonObjectGetKeyConst( node, "value" )->type == JSON_HASH) {
1242                 value = searchWHERE( jsonObjectGetKeyConst( node, "value" ), osrfHashGet( oilsIDL(), class ), AND_OP_JOIN );
1243         } else if (jsonObjectGetKeyConst( node, "value" )->type != JSON_NULL) {
1244                 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1245                         value = jsonNumberToDBString( field, jsonObjectGetKeyConst( node, "value" ) );
1246                 } else {
1247                         value = jsonObjectToSimpleString(jsonObjectGetKeyConst( node, "value" ));
1248                         if ( !dbi_conn_quote_string(dbhandle, &value) ) {
1249                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, value);
1250                                 free(value);
1251                                 free(field_transform);
1252                                 return NULL;
1253                         }
1254                 }
1255         }
1256
1257         growing_buffer* sql_buf = buffer_init(32);
1258         
1259         buffer_fadd(
1260                 sql_buf,
1261                 "%s %s %s",
1262                 field_transform,
1263                 node_key,
1264                 value
1265         );
1266
1267         free(value);
1268         free(field_transform);
1269
1270         return buffer_release(sql_buf);
1271 }
1272
1273 static char* searchSimplePredicate (const char* orig_op, const char* class,
1274                 osrfHash* field, const jsonObject* node) {
1275
1276         char* val = NULL;
1277
1278         if (node->type != JSON_NULL) {
1279                 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1280                         val = jsonNumberToDBString( field, node );
1281                 } else {
1282                         val = jsonObjectToSimpleString(node);
1283                 }
1284         }
1285
1286         char* pred = searchWriteSimplePredicate( class, field, osrfHashGet(field, "name"), orig_op, val );
1287
1288         if (val) free(val);
1289
1290         return pred;
1291 }
1292
1293 static char* searchWriteSimplePredicate ( const char* class, osrfHash* field,
1294         const char* left, const char* orig_op, const char* right ) {
1295
1296         char* val = NULL;
1297         char* op = NULL;
1298         if (right == NULL) {
1299                 val = strdup("NULL");
1300
1301                 if (strcmp( orig_op, "=" ))
1302                         op = strdup("IS NOT");
1303                 else
1304                         op = strdup("IS");
1305
1306         } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1307                 val = strdup(right);
1308                 op = strdup(orig_op);
1309
1310         } else {
1311                 val = strdup(right);
1312                 if ( !dbi_conn_quote_string(dbhandle, &val) ) {
1313                         osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1314                         free(val);
1315                         return NULL;
1316                 }
1317                 op = strdup(orig_op);
1318         }
1319
1320         growing_buffer* sql_buf = buffer_init(16);
1321         buffer_fadd( sql_buf, "\"%s\".%s %s %s", class, left, op, val );
1322         free(val);
1323         free(op);
1324
1325         return buffer_release(sql_buf);
1326 }
1327
1328 static char* searchBETWEENPredicate (const char* class, osrfHash* field, jsonObject* node) {
1329
1330         char* x_string;
1331         char* y_string;
1332
1333         if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1334                 x_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,0));
1335                 y_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,1));
1336
1337         } else {
1338                 x_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,0));
1339                 y_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,1));
1340                 if ( !(dbi_conn_quote_string(dbhandle, &x_string) && dbi_conn_quote_string(dbhandle, &y_string)) ) {
1341                         osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key strings [%s] and [%s]", MODULENAME, x_string, y_string);
1342                         free(x_string);
1343                         free(y_string);
1344                         return NULL;
1345                 }
1346         }
1347
1348         growing_buffer* sql_buf = buffer_init(32);
1349         buffer_fadd( sql_buf, "%s BETWEEN %s AND %s", osrfHashGet(field, "name"), x_string, y_string );
1350         free(x_string);
1351         free(y_string);
1352
1353         return buffer_release(sql_buf);
1354 }
1355
1356 static char* searchPredicate ( const char* class, osrfHash* field, jsonObject* node ) {
1357
1358         char* pred = NULL;
1359         if (node->type == JSON_ARRAY) { // equality IN search
1360                 pred = searchINPredicate( class, field, node, NULL );
1361         } else if (node->type == JSON_HASH) { // non-equality search
1362                 jsonObject* pred_node;
1363                 jsonIterator* pred_itr = jsonNewIterator( node );
1364                 while ( (pred_node = jsonIteratorNext( pred_itr )) ) {
1365                         if ( !(strcasecmp( pred_itr->key,"between" )) )
1366                                 pred = searchBETWEENPredicate( class, field, pred_node );
1367                         else if ( !(strcasecmp( pred_itr->key,"in" )) || !(strcasecmp( pred_itr->key,"not in" )) )
1368                                 pred = searchINPredicate( class, field, pred_node, pred_itr->key );
1369                         else if ( pred_node->type == JSON_ARRAY )
1370                                 pred = searchFunctionPredicate( class, field, pred_node, pred_itr->key );
1371                         else if ( pred_node->type == JSON_HASH )
1372                                 pred = searchFieldTransformPredicate( class, field, pred_node, pred_itr->key );
1373                         else 
1374                                 pred = searchSimplePredicate( pred_itr->key, class, field, pred_node );
1375
1376                         break;
1377                 }
1378         jsonIteratorFree(pred_itr);
1379         } else if (node->type == JSON_NULL) { // IS NULL search
1380                 growing_buffer* _p = buffer_init(64);
1381                 buffer_fadd(
1382                         _p,
1383                         "\"%s\".%s IS NULL",
1384                         class,
1385                         osrfHashGet(field, "name")
1386                 );
1387                 pred = buffer_release(_p);
1388         } else { // equality search
1389                 pred = searchSimplePredicate( "=", class, field, node );
1390         }
1391
1392         return pred;
1393
1394 }
1395
1396
1397 /*
1398
1399 join : {
1400         acn : {
1401                 field : record,
1402                 fkey : id
1403                 type : left
1404                 filter_op : or
1405                 filter : { ... },
1406                 join : {
1407                         acp : {
1408                                 field : call_number,
1409                                 fkey : id,
1410                                 filter : { ... },
1411                         },
1412                 },
1413         },
1414         mrd : {
1415                 field : record,
1416                 type : inner
1417                 fkey : id,
1418                 filter : { ... },
1419         }
1420 }
1421
1422 */
1423
1424 static char* searchJOIN ( const jsonObject* join_hash, osrfHash* leftmeta ) {
1425
1426         const jsonObject* working_hash;
1427         jsonObject* freeable_hash = NULL;
1428
1429         if (join_hash->type == JSON_STRING) {
1430                 // create a wrapper around a copy of the original
1431                 char* _tmp = jsonObjectToSimpleString( join_hash );
1432                 freeable_hash = jsonNewObjectType(JSON_HASH);
1433                 jsonObjectSetKey(freeable_hash, _tmp, NULL);
1434                 free(_tmp);
1435                 working_hash = freeable_hash;
1436         }
1437         else
1438                 working_hash = join_hash;
1439
1440         growing_buffer* join_buf = buffer_init(128);
1441         char* leftclass = osrfHashGet(leftmeta, "classname");
1442
1443         jsonObject* snode = NULL;
1444         jsonIterator* search_itr = jsonNewIterator( working_hash );
1445         if(freeable_hash)
1446                 jsonObjectFree(freeable_hash);
1447         
1448         while ( (snode = jsonIteratorNext( search_itr )) ) {
1449                 osrfHash* idlClass = osrfHashGet( oilsIDL(), search_itr->key );
1450
1451                 char* class = osrfHashGet(idlClass, "classname");
1452
1453                 char* fkey = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "fkey" ) );
1454                 char* field = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "field" ) );
1455
1456                 if (field && !fkey) {
1457                         fkey = (char*)oilsIDLFindPath("/%s/links/%s/key", class, field);
1458                         if (!fkey) {
1459                                 osrfLogError(
1460                                         OSRF_LOG_MARK,
1461                                         "%s: JOIN failed.  No link defined from %s.%s to %s",
1462                                         MODULENAME,
1463                                         class,
1464                                         field,
1465                                         leftclass
1466                                 );
1467                                 buffer_free(join_buf);
1468                                 free(field);
1469                                 jsonIteratorFree(search_itr);
1470                                 return NULL;
1471                         }
1472                         fkey = strdup( fkey );
1473
1474                 } else if (!field && fkey) {
1475                         field = (char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, fkey );
1476                         if (!field) {
1477                                 osrfLogError(
1478                                         OSRF_LOG_MARK,
1479                                         "%s: JOIN failed.  No link defined from %s.%s to %s",
1480                                         MODULENAME,
1481                                         leftclass,
1482                                         fkey,
1483                                         class
1484                                 );
1485                                 buffer_free(join_buf);
1486                                 free(fkey);
1487                                 jsonIteratorFree(search_itr);
1488                                 return NULL;
1489                         }
1490                         field = strdup( field );
1491
1492                 } else if (!field && !fkey) {
1493                         osrfHash* _links = oilsIDLFindPath("/%s/links", leftclass);
1494
1495                         int i = 0;
1496                         osrfStringArray* keys = osrfHashKeys( _links );
1497                         while ( (fkey = osrfStringArrayGetString(keys, i++)) ) {
1498                                 fkey = strdup(osrfStringArrayGetString(keys, i++));
1499                                 if ( !strcmp( (char*)oilsIDLFindPath("/%s/links/%s/class", leftclass, fkey), class) ) {
1500                                         field = strdup( (char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, fkey) );
1501                                         break;
1502                                 } else {
1503                                         free(fkey);
1504                                 }
1505                         }
1506                         osrfStringArrayFree(keys);
1507
1508                         if (!field && !fkey) {
1509                                 _links = oilsIDLFindPath("/%s/links", class);
1510
1511                                 i = 0;
1512                                 keys = osrfHashKeys( _links );
1513                                 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
1514                                         field = strdup(osrfStringArrayGetString(keys, i++));
1515                                         if ( !strcmp( (char*)oilsIDLFindPath("/%s/links/%s/class", class, field), class) ) {
1516                                                 fkey = strdup( (char*)oilsIDLFindPath("/%s/links/%s/key", class, field) );
1517                                                 break;
1518                                         } else {
1519                                                 free(field);
1520                                         }
1521                                 }
1522                                 osrfStringArrayFree(keys);
1523                         }
1524
1525                         if (!field && !fkey) {
1526                                 osrfLogError(
1527                                         OSRF_LOG_MARK,
1528                                         "%s: JOIN failed.  No link defined between %s and %s",
1529                                         MODULENAME,
1530                                         leftclass,
1531                                         class
1532                                 );
1533                                 buffer_free(join_buf);
1534                                 jsonIteratorFree(search_itr);
1535                                 return NULL;
1536                         }
1537
1538                 }
1539
1540                 char* type = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "type" ) );
1541                 if (type) {
1542                         if ( !strcasecmp(type,"left") ) {
1543                                 buffer_add(join_buf, " LEFT JOIN");
1544                         } else if ( !strcasecmp(type,"right") ) {
1545                                 buffer_add(join_buf, " RIGHT JOIN");
1546                         } else if ( !strcasecmp(type,"full") ) {
1547                                 buffer_add(join_buf, " FULL JOIN");
1548                         } else {
1549                                 buffer_add(join_buf, " INNER JOIN");
1550                         }
1551                 } else {
1552                         buffer_add(join_buf, " INNER JOIN");
1553                 }
1554                 free(type);
1555
1556                 char* table = getSourceDefinition(idlClass);
1557                 buffer_fadd(join_buf, " %s AS \"%s\" ON ( \"%s\".%s = \"%s\".%s", table, class, class, field, leftclass, fkey);
1558                 free(table);
1559
1560                 const jsonObject* filter = jsonObjectGetKeyConst( snode, "filter" );
1561                 if (filter) {
1562                         char* filter_op = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "filter_op" ) );
1563                         if (filter_op) {
1564                                 if (!strcasecmp("or",filter_op)) {
1565                                         buffer_add( join_buf, " OR " );
1566                                 } else {
1567                                         buffer_add( join_buf, " AND " );
1568                                 }
1569                         } else {
1570                                 buffer_add( join_buf, " AND " );
1571                         }
1572
1573                         char* jpred = searchWHERE( filter, idlClass, AND_OP_JOIN );
1574                         buffer_fadd( join_buf, " %s", jpred );
1575                         free(jpred);
1576                         free(filter_op);
1577                 }
1578
1579                 buffer_add(join_buf, " ) ");
1580                 
1581                 const jsonObject* join_filter = jsonObjectGetKeyConst( snode, "join" );
1582                 if (join_filter) {
1583                         char* jpred = searchJOIN( join_filter, idlClass );
1584                         buffer_fadd( join_buf, " %s", jpred );
1585                         free(jpred);
1586                 }
1587
1588                 free(fkey);
1589                 free(field);
1590         }
1591
1592     jsonIteratorFree(search_itr);
1593
1594         return buffer_release(join_buf);
1595 }
1596
1597 /*
1598
1599 { +class : { -or|-and : { field : { op : value }, ... } ... }, ... }
1600 { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }
1601 [ { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }, ... ]
1602
1603 */
1604 static char* searchWHERE ( const jsonObject* search_hash, osrfHash* meta, int opjoin_type ) {
1605
1606         growing_buffer* sql_buf = buffer_init(128);
1607
1608         jsonObject* node = NULL;
1609
1610     int first = 1;
1611     if ( search_hash->type == JSON_ARRAY ) {
1612         jsonIterator* search_itr = jsonNewIterator( search_hash );
1613         while ( (node = jsonIteratorNext( search_itr )) ) {
1614             if (first) {
1615                 first = 0;
1616             } else {
1617                 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
1618                 else buffer_add(sql_buf, " AND ");
1619             }
1620
1621             char* subpred = searchWHERE( node, meta, opjoin_type );
1622             buffer_fadd(sql_buf, "( %s )", subpred);
1623             free(subpred);
1624         }
1625         jsonIteratorFree(search_itr);
1626
1627     } else if ( search_hash->type == JSON_HASH ) {
1628         jsonIterator* search_itr = jsonNewIterator( search_hash );
1629         while ( (node = jsonIteratorNext( search_itr )) ) {
1630
1631             if (first) {
1632                 first = 0;
1633             } else {
1634                 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
1635                 else buffer_add(sql_buf, " AND ");
1636             }
1637
1638             if ( !strncmp("+",search_itr->key,1) ) {
1639                 if ( node->type == JSON_STRING ) {
1640                     char* subpred = jsonObjectToSimpleString( node );
1641                     buffer_fadd(sql_buf, " \"%s\".%s ", search_itr->key + 1, subpred);
1642                     free(subpred);
1643                 } else {
1644                     char* subpred = searchWHERE( node, osrfHashGet( oilsIDL(), search_itr->key + 1 ), AND_OP_JOIN );
1645                     buffer_fadd(sql_buf, "( %s )", subpred);
1646                     free(subpred);
1647                 }
1648             } else if ( !strcasecmp("-or",search_itr->key) ) {
1649                 char* subpred = searchWHERE( node, meta, OR_OP_JOIN );
1650                 buffer_fadd(sql_buf, "( %s )", subpred);
1651                 free(subpred);
1652             } else if ( !strcasecmp("-and",search_itr->key) ) {
1653                 char* subpred = searchWHERE( node, meta, AND_OP_JOIN );
1654                 buffer_fadd(sql_buf, "( %s )", subpred);
1655                 free(subpred);
1656             } else {
1657
1658                 char* class = osrfHashGet(meta, "classname");
1659                 osrfHash* fields = osrfHashGet(meta, "fields");
1660                 osrfHash* field = osrfHashGet( fields, search_itr->key );
1661
1662
1663                 if (!field) {
1664                     char* table = getSourceDefinition(meta);
1665                     osrfLogError(
1666                         OSRF_LOG_MARK,
1667                         "%s: Attempt to reference non-existant column %s on %s (%s)",
1668                         MODULENAME,
1669                         search_itr->key,
1670                         table,
1671                         class
1672                     );
1673                     buffer_free(sql_buf);
1674                     free(table);
1675                                         jsonIteratorFree(search_itr);
1676                                         return NULL;
1677                 }
1678
1679                 char* subpred = searchPredicate( class, field, node );
1680                 buffer_add( sql_buf, subpred );
1681                 free(subpred);
1682             }
1683         }
1684             jsonIteratorFree(search_itr);
1685
1686     } else {
1687         // ERROR ... only hash and array allowed at this level
1688         char* predicate_string = jsonObjectToJSON( search_hash );
1689         osrfLogError(
1690             OSRF_LOG_MARK,
1691             "%s: Invalid predicate structure: %s",
1692             MODULENAME,
1693             predicate_string
1694         );
1695         buffer_free(sql_buf);
1696         free(predicate_string);
1697         return NULL;
1698     }
1699
1700
1701         return buffer_release(sql_buf);
1702 }
1703
1704 static char* SELECT (
1705                 /* method context */ osrfMethodContext* ctx,
1706                 
1707                 /* SELECT   */ jsonObject* selhash,
1708                 /* FROM     */ jsonObject* join_hash,
1709                 /* WHERE    */ jsonObject* search_hash,
1710                 /* HAVING   */ jsonObject* having_hash,
1711                 /* ORDER BY */ jsonObject* order_hash,
1712                 /* LIMIT    */ jsonObject* limit,
1713                 /* OFFSET   */ jsonObject* offset,
1714                 /* flags    */ int flags
1715 ) {
1716         const char* locale = osrf_message_get_last_locale();
1717
1718         // in case we don't get a select list
1719         jsonObject* defaultselhash = NULL;
1720
1721         // general tmp objects
1722         const jsonObject* tmp_const;
1723         jsonObject* _tmp = NULL;
1724         jsonObject* selclass = NULL;
1725         jsonObject* selfield = NULL;
1726         jsonObject* snode = NULL;
1727         jsonObject* onode = NULL;
1728         jsonObject* found = NULL;
1729
1730         char* string = NULL;
1731         int from_function = 0;
1732         int first = 1;
1733         int gfirst = 1;
1734         //int hfirst = 1;
1735
1736         // the core search class
1737         char* core_class = NULL;
1738
1739         // metadata about the core search class
1740         osrfHash* core_meta = NULL;
1741         osrfHash* core_fields = NULL;
1742         osrfHash* idlClass = NULL;
1743
1744         // punt if there's no core class
1745         if (!join_hash || ( join_hash->type == JSON_HASH && !join_hash->size ))
1746                 return NULL;
1747
1748         // get the core class -- the only key of the top level FROM clause, or a string
1749         if (join_hash->type == JSON_HASH) {
1750                 jsonIterator* tmp_itr = jsonNewIterator( join_hash );
1751                 snode = jsonIteratorNext( tmp_itr );
1752                 
1753                 core_class = strdup( tmp_itr->key );
1754                 join_hash = snode;
1755
1756                 jsonIteratorFree( tmp_itr );
1757                 snode = NULL;
1758
1759         } else if (join_hash->type == JSON_ARRAY) {
1760         from_function = 1;
1761         selhash = NULL;
1762
1763         } else if (join_hash->type == JSON_STRING) {
1764                 core_class = jsonObjectToSimpleString( join_hash );
1765                 join_hash = NULL;
1766         }
1767
1768         // punt if we don't know about the core class (and it's not a function)
1769         if (!from_function && !(core_meta = osrfHashGet( oilsIDL(), core_class ))) {
1770                 free(core_class);
1771                 return NULL;
1772         }
1773
1774         // if the select list is empty, or the core class field list is '*',
1775         // build the default select list ...
1776         if (!selhash) {
1777                 selhash = defaultselhash = jsonNewObjectType(JSON_HASH);
1778                 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
1779         } else if ( (tmp_const = jsonObjectGetKeyConst( selhash, core_class )) && tmp_const->type == JSON_STRING ) {
1780                 char* _x = jsonObjectToSimpleString( tmp_const );
1781                 if (!strncmp( "*", _x, 1 )) {
1782                         jsonObjectRemoveKey( selhash, core_class );
1783                         jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
1784                 }
1785                 free(_x);
1786         }
1787
1788         // the query buffer
1789         growing_buffer* sql_buf = buffer_init(128);
1790
1791         // temp buffer for the SELECT list
1792         growing_buffer* select_buf = buffer_init(128);
1793         growing_buffer* order_buf = buffer_init(128);
1794         growing_buffer* group_buf = buffer_init(128);
1795         growing_buffer* having_buf = buffer_init(128);
1796
1797         if (!from_function) 
1798         core_fields = osrfHashGet(core_meta, "fields");
1799
1800         // ... and if we /are/ building the default list, do that
1801         if ( (_tmp = jsonObjectGetKey(selhash,core_class)) && !_tmp->size ) {
1802                 
1803                 int i = 0;
1804                 char* field;
1805
1806         if (!from_function) {
1807                 osrfStringArray* keys = osrfHashKeys( core_fields );
1808                 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
1809                         if ( strncasecmp( "true", osrfHashGet( osrfHashGet( core_fields, field ), "virtual" ), 4 ) )
1810                                 jsonObjectPush( _tmp, jsonNewObject( field ) );
1811                 }
1812                 osrfStringArrayFree(keys);
1813         }
1814         }
1815
1816         // Now we build the actual select list
1817         if (!from_function) {
1818             int sel_pos = 1;
1819             jsonObject* is_agg = jsonObjectFindPath(selhash, "//aggregate");
1820             first = 1;
1821             gfirst = 1;
1822             jsonIterator* selclass_itr = jsonNewIterator( selhash );
1823             while ( (selclass = jsonIteratorNext( selclass_itr )) ) {
1824
1825                     // round trip through the idl, just to be safe
1826                     idlClass = osrfHashGet( oilsIDL(), selclass_itr->key );
1827                     if (!idlClass) continue;
1828                     char* cname = osrfHashGet(idlClass, "classname");
1829
1830                     // make sure the target relation is in the join tree
1831                     if (strcmp(core_class,cname)) {
1832                             if (!join_hash) continue;
1833
1834                             if (join_hash->type == JSON_STRING) {
1835                                     string = jsonObjectToSimpleString(join_hash);
1836                                     found = strcmp(string,cname) ? NULL : jsonParseString("{\"1\":\"1\"}");
1837                                     free(string);
1838                             } else {
1839                                     found = jsonObjectFindPath(join_hash, "//%s", cname);
1840                             }
1841
1842                             if (!found->size) {
1843                                     jsonObjectFree(found);
1844                                     continue;
1845                             }
1846
1847                             jsonObjectFree(found);
1848                     }
1849
1850                     // stitch together the column list ...
1851                     jsonIterator* select_itr = jsonNewIterator( selclass );
1852                     while ( (selfield = jsonIteratorNext( select_itr )) ) {
1853
1854                             char* __column = NULL;
1855                             char* __alias = NULL;
1856
1857                             // ... if it's a sstring, just toss it on the pile
1858                             if (selfield->type == JSON_STRING) {
1859
1860                                     // again, just to be safe
1861                                     char* _requested_col = jsonObjectToSimpleString(selfield);
1862                                     osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), _requested_col );
1863                                     free(_requested_col);
1864
1865                                     if (!field) continue;
1866                                     __column = strdup(osrfHashGet(field, "name"));
1867
1868                                     if (first) {
1869                                             first = 0;
1870                                     } else {
1871                                             buffer_add(select_buf, ",");
1872                                     }
1873
1874                     if (locale) {
1875                             char* i18n = osrfHashGet(field, "i18n");
1876                                     if (flags & DISABLE_I18N)
1877                             i18n = NULL;
1878
1879                             if ( i18n && !strncasecmp("true", i18n, 4)) {
1880                                 char* pkey = osrfHashGet(idlClass, "primarykey");
1881                                 char* tname = osrfHashGet(idlClass, "tablename");
1882
1883                             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);
1884                         } else {
1885                                             buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, __column, __column);
1886                         }
1887                     } else {
1888                                         buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, __column, __column);
1889                     }
1890
1891                             // ... but it could be an object, in which case we check for a Field Transform
1892                             } else {
1893
1894                                     __column = jsonObjectToSimpleString( jsonObjectGetKeyConst( selfield, "column" ) );
1895
1896                                     // again, just to be safe
1897                                     osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), __column );
1898                                     if (!field) continue;
1899                                     const char* fname = osrfHashGet(field, "name");
1900
1901                                     if (first) {
1902                                             first = 0;
1903                                     } else {
1904                                             buffer_add(select_buf, ",");
1905                                     }
1906
1907                                     if ((tmp_const = jsonObjectGetKeyConst( selfield, "alias" ))) {
1908                                             __alias = jsonObjectToSimpleString( tmp_const );
1909                                     } else {
1910                                             __alias = strdup(__column);
1911                                     }
1912
1913                                     if (jsonObjectGetKeyConst( selfield, "transform" )) {
1914                                             free(__column);
1915                                             __column = searchFieldTransform(cname, field, selfield);
1916                                             buffer_fadd(select_buf, " %s AS \"%s\"", __column, __alias);
1917                                     } else {
1918                         if (locale) {
1919                                     char* i18n = osrfHashGet(field, "i18n");
1920                                         if (flags & DISABLE_I18N)
1921                                 i18n = NULL;
1922     
1923                                     if ( i18n && !strncasecmp("true", i18n, 4)) {
1924                                     char* pkey = osrfHashGet(idlClass, "primarykey");
1925                                     char* tname = osrfHashGet(idlClass, "tablename");
1926
1927                                 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);
1928                             } else {
1929                                                     buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, fname, __alias);
1930                             }
1931                         } else {
1932                                                 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, fname, __alias);
1933                         }
1934                                     }
1935                             }
1936
1937                             if (is_agg->size || (flags & SELECT_DISTINCT)) {
1938
1939                                     if (!jsonBoolIsTrue( jsonObjectGetKey( selfield, "aggregate" ) )) {
1940                                             if (gfirst) {
1941                                                     gfirst = 0;
1942                                             } else {
1943                                                     buffer_add(group_buf, ",");
1944                                             }
1945
1946                                             buffer_fadd(group_buf, " %d", sel_pos);
1947                                     /*
1948                                     } else if (is_agg = jsonObjectGetKey( selfield, "having" )) {
1949                                             if (gfirst) {
1950                                                     gfirst = 0;
1951                                             } else {
1952                                                     buffer_add(group_buf, ",");
1953                                             }
1954
1955                                             __column = searchFieldTransform(cname, field, selfield);
1956                                             buffer_fadd(group_buf, " %s", __column);
1957                                             __column = searchFieldTransform(cname, field, selfield);
1958                                     */
1959                                     }
1960                             }
1961
1962                             if (__column) free(__column);
1963                             if (__alias) free(__alias);
1964
1965                             sel_pos++;
1966                     }
1967
1968             // jsonIteratorFree(select_itr);
1969             }
1970
1971         // jsonIteratorFree(selclass_itr);
1972
1973             if (is_agg) jsonObjectFree(is_agg);
1974     } else {
1975         buffer_add(select_buf, "*");
1976     }
1977
1978
1979         char* col_list = buffer_release(select_buf);
1980         char* table = NULL;
1981     if (!from_function) table = getSourceDefinition(core_meta);
1982     else table = searchValueTransform(join_hash);
1983
1984         // Put it all together
1985         buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\" ", col_list, table, core_class );
1986         free(col_list);
1987         free(table);
1988
1989     if (!from_function) {
1990             // Now, walk the join tree and add that clause
1991             if ( join_hash ) {
1992                     char* join_clause = searchJOIN( join_hash, core_meta );
1993                     buffer_add(sql_buf, join_clause);
1994                     free(join_clause);
1995             }
1996
1997             if ( search_hash ) {
1998                     buffer_add(sql_buf, " WHERE ");
1999
2000                     // and it's on the the WHERE clause
2001                     char* pred = searchWHERE( search_hash, core_meta, AND_OP_JOIN );
2002
2003                     if (!pred) {
2004                             osrfAppSessionStatus(
2005                                     ctx->session,
2006                                     OSRF_STATUS_INTERNALSERVERERROR,
2007                                     "osrfMethodException",
2008                                     ctx->request,
2009                                     "Severe query error in WHERE predicate -- see error log for more details"
2010                             );
2011                             free(core_class);
2012                             buffer_free(having_buf);
2013                             buffer_free(group_buf);
2014                             buffer_free(order_buf);
2015                             buffer_free(sql_buf);
2016                             if (defaultselhash) jsonObjectFree(defaultselhash);
2017                             return NULL;
2018                     } else {
2019                             buffer_add(sql_buf, pred);
2020                             free(pred);
2021                     }
2022         }
2023
2024             if ( having_hash ) {
2025                     buffer_add(sql_buf, " HAVING ");
2026
2027                     // and it's on the the WHERE clause
2028                     char* pred = searchWHERE( having_hash, core_meta, AND_OP_JOIN );
2029
2030                     if (!pred) {
2031                             osrfAppSessionStatus(
2032                                     ctx->session,
2033                                     OSRF_STATUS_INTERNALSERVERERROR,
2034                                     "osrfMethodException",
2035                                     ctx->request,
2036                                     "Severe query error in HAVING predicate -- see error log for more details"
2037                             );
2038                             free(core_class);
2039                             buffer_free(having_buf);
2040                             buffer_free(group_buf);
2041                             buffer_free(order_buf);
2042                             buffer_free(sql_buf);
2043                             if (defaultselhash) jsonObjectFree(defaultselhash);
2044                             return NULL;
2045                     } else {
2046                             buffer_add(sql_buf, pred);
2047                             free(pred);
2048                     }
2049             }
2050
2051             first = 1;
2052             jsonIterator* class_itr = jsonNewIterator( order_hash );
2053             while ( (snode = jsonIteratorNext( class_itr )) ) {
2054
2055                     if (!jsonObjectGetKeyConst(selhash,class_itr->key))
2056                             continue;
2057
2058                     if ( snode->type == JSON_HASH ) {
2059
2060                         jsonIterator* order_itr = jsonNewIterator( snode );
2061                             while ( (onode = jsonIteratorNext( order_itr )) ) {
2062
2063                                     if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
2064                                             continue;
2065
2066                                     char* direction = NULL;
2067                                     if ( onode->type == JSON_HASH ) {
2068                                             if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
2069                                                     string = searchFieldTransform(
2070                                                             class_itr->key,
2071                                                             oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
2072                                                             onode
2073                                                     );
2074                                             } else {
2075                                                     growing_buffer* field_buf = buffer_init(16);
2076                                                     buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
2077                                                     string = buffer_release(field_buf);
2078                                             }
2079
2080                                             if ( (tmp_const = jsonObjectGetKeyConst( onode, "direction" )) ) {
2081                                                     direction = jsonObjectToSimpleString(tmp_const);
2082                                                     if (!strncasecmp(direction, "d", 1)) {
2083                                                             free(direction);
2084                                                             direction = " DESC";
2085                                                     } else {
2086                                                             free(direction);
2087                                                             direction = " ASC";
2088                                                     }
2089                                             }
2090
2091                                     } else {
2092                                             string = strdup(order_itr->key);
2093                                             direction = jsonObjectToSimpleString(onode);
2094                                             if (!strncasecmp(direction, "d", 1)) {
2095                                                     free(direction);
2096                                                     direction = " DESC";
2097                                             } else {
2098                                                     free(direction);
2099                                                     direction = " ASC";
2100                                             }
2101                                     }
2102
2103                                     if (first) {
2104                                             first = 0;
2105                                     } else {
2106                                             buffer_add(order_buf, ", ");
2107                                     }
2108
2109                                     buffer_add(order_buf, string);
2110                                     free(string);
2111
2112                                     if (direction) {
2113                                             buffer_add(order_buf, direction);
2114                                     }
2115
2116                             }
2117                 // jsonIteratorFree(order_itr);
2118
2119                     } else if ( snode->type == JSON_ARRAY ) {
2120
2121                         jsonIterator* order_itr = jsonNewIterator( snode );
2122                             while ( (onode = jsonIteratorNext( order_itr )) ) {
2123
2124                                     char* _f = jsonObjectToSimpleString( onode );
2125
2126                                     if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, _f))
2127                                             continue;
2128
2129                                     if (first) {
2130                                             first = 0;
2131                                     } else {
2132                                             buffer_add(order_buf, ", ");
2133                                     }
2134
2135                                     buffer_add(order_buf, _f);
2136                                     free(_f);
2137
2138                             }
2139                 // jsonIteratorFree(order_itr);
2140
2141
2142                     // IT'S THE OOOOOOOOOOOLD STYLE!
2143                     } else {
2144                             osrfLogError(OSRF_LOG_MARK, "%s: Possible SQL injection attempt; direct order by is not allowed", MODULENAME);
2145                             osrfAppSessionStatus(
2146                                     ctx->session,
2147                                     OSRF_STATUS_INTERNALSERVERERROR,
2148                                     "osrfMethodException",
2149                                     ctx->request,
2150                                     "Severe query error -- see error log for more details"
2151                             );
2152
2153                             free(core_class);
2154                             buffer_free(having_buf);
2155                             buffer_free(group_buf);
2156                             buffer_free(order_buf);
2157                             buffer_free(sql_buf);
2158                             if (defaultselhash) jsonObjectFree(defaultselhash);
2159                             jsonIteratorFree(class_itr);
2160                             return NULL;
2161                     }
2162
2163             }
2164     }
2165
2166     // jsonIteratorFree(class_itr);
2167
2168         string = buffer_release(group_buf);
2169
2170         if (strlen(string)) {
2171                 buffer_fadd(
2172                         sql_buf,
2173                         " GROUP BY %s",
2174                         string
2175                 );
2176         }
2177
2178         free(string);
2179
2180         string = buffer_release(having_buf);
2181  
2182         if (strlen(string)) {
2183                 buffer_fadd(
2184                         sql_buf,
2185                         " HAVING %s",
2186                         string
2187                 );
2188         }
2189
2190         free(string);
2191
2192         string = buffer_release(order_buf);
2193
2194         if (strlen(string)) {
2195                 buffer_fadd(
2196                         sql_buf,
2197                         " ORDER BY %s",
2198                         string
2199                 );
2200         }
2201
2202         free(string);
2203
2204         if ( limit ){
2205                 string = jsonObjectToSimpleString(limit);
2206                 buffer_fadd( sql_buf, " LIMIT %d", atoi(string) );
2207                 free(string);
2208         }
2209
2210         if (offset) {
2211                 string = jsonObjectToSimpleString(offset);
2212                 buffer_fadd( sql_buf, " OFFSET %d", atoi(string) );
2213                 free(string);
2214         }
2215
2216         buffer_add(sql_buf, ";");
2217
2218         free(core_class);
2219         if (defaultselhash) jsonObjectFree(defaultselhash);
2220
2221         return buffer_release(sql_buf);
2222
2223 }
2224
2225 static char* buildSELECT ( jsonObject* search_hash, jsonObject* order_hash, osrfHash* meta, osrfMethodContext* ctx ) {
2226
2227         const char* locale = osrf_message_get_last_locale();
2228
2229         osrfHash* fields = osrfHashGet(meta, "fields");
2230         char* core_class = osrfHashGet(meta, "classname");
2231
2232         const jsonObject* join_hash = jsonObjectGetKeyConst( order_hash, "join" );
2233
2234         jsonObject* node = NULL;
2235         jsonObject* snode = NULL;
2236         jsonObject* onode = NULL;
2237         const jsonObject* _tmp = NULL;
2238         jsonObject* selhash = NULL;
2239         jsonObject* defaultselhash = NULL;
2240
2241         growing_buffer* sql_buf = buffer_init(128);
2242         growing_buffer* select_buf = buffer_init(128);
2243
2244         if ( !(selhash = jsonObjectGetKey( order_hash, "select" )) ) {
2245                 defaultselhash = jsonNewObjectType(JSON_HASH);
2246                 selhash = defaultselhash;
2247         }
2248         
2249         if ( !jsonObjectGetKeyConst(selhash,core_class) ) {
2250                 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2251                 jsonObject* flist = jsonObjectGetKey( selhash, core_class );
2252                 
2253                 int i = 0;
2254                 char* field;
2255
2256                 osrfStringArray* keys = osrfHashKeys( fields );
2257                 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
2258                         if ( strcasecmp( "true", osrfHashGet( osrfHashGet( fields, field ), "virtual" ) ) )
2259                                 jsonObjectPush( flist, jsonNewObject( field ) );
2260                 }
2261                 osrfStringArrayFree(keys);
2262         }
2263
2264         int first = 1;
2265         jsonIterator* class_itr = jsonNewIterator( selhash );
2266         while ( (snode = jsonIteratorNext( class_itr )) ) {
2267
2268                 osrfHash* idlClass = osrfHashGet( oilsIDL(), class_itr->key );
2269                 if (!idlClass) continue;
2270                 char* cname = osrfHashGet(idlClass, "classname");
2271
2272                 if (strcmp(core_class,class_itr->key)) {
2273                         if (!join_hash) continue;
2274
2275                         jsonObject* found =  jsonObjectFindPath(join_hash, "//%s", class_itr->key);
2276                         if (!found->size) {
2277                                 jsonObjectFree(found);
2278                                 continue;
2279                         }
2280
2281                         jsonObjectFree(found);
2282                 }
2283
2284                 jsonIterator* select_itr = jsonNewIterator( snode );
2285                 while ( (node = jsonIteratorNext( select_itr )) ) {
2286                         char* item_str = jsonObjectToSimpleString(node);
2287                         osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), item_str );
2288                         free(item_str);
2289                         char* fname = osrfHashGet(field, "name");
2290
2291                         if (!field) continue;
2292
2293                         if (first) {
2294                                 first = 0;
2295                         } else {
2296                                 buffer_add(select_buf, ",");
2297                         }
2298
2299             if (locale) {
2300                         char* i18n = osrfHashGet(field, "i18n");
2301                     if (jsonBoolIsTrue(jsonObjectGetKey( order_hash, "no_i18n" )))
2302                     i18n = NULL;
2303
2304                         if ( i18n && !strncasecmp("true", i18n, 4)) {
2305                         char* pkey = osrfHashGet(idlClass, "primarykey");
2306                         char* tname = osrfHashGet(idlClass, "tablename");
2307
2308                     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);
2309                 } else {
2310                                 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
2311                 }
2312             } else {
2313                             buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
2314             }
2315                 }
2316
2317         jsonIteratorFree(select_itr);
2318         }
2319
2320     jsonIteratorFree(class_itr);
2321
2322         char* col_list = buffer_release(select_buf);
2323         char* table = getSourceDefinition(meta);
2324
2325         buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\"", col_list, table, core_class );
2326         free(col_list);
2327         free(table);
2328
2329         if ( join_hash ) {
2330                 char* join_clause = searchJOIN( join_hash, meta );
2331                 buffer_fadd(sql_buf, " %s", join_clause);
2332                 free(join_clause);
2333         }
2334
2335         char* tmpsql = buffer_data(sql_buf);
2336         osrfLogDebug(OSRF_LOG_MARK, "%s pre-predicate SQL =  %s", MODULENAME, tmpsql);
2337         free(tmpsql);
2338
2339         buffer_add(sql_buf, " WHERE ");
2340
2341         char* pred = searchWHERE( search_hash, meta, AND_OP_JOIN );
2342         if (!pred) {
2343                 osrfAppSessionStatus(
2344                         ctx->session,
2345                         OSRF_STATUS_INTERNALSERVERERROR,
2346                                 "osrfMethodException",
2347                                 ctx->request,
2348                                 "Severe query error -- see error log for more details"
2349                         );
2350                 buffer_free(sql_buf);
2351                 if(defaultselhash) jsonObjectFree(defaultselhash);
2352                 return NULL;
2353         } else {
2354                 buffer_add(sql_buf, pred);
2355                 free(pred);
2356         }
2357
2358         if (order_hash) {
2359                 char* string = NULL;
2360                 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "order_by" )) ){
2361
2362                         growing_buffer* order_buf = buffer_init(128);
2363
2364                         first = 1;
2365                         jsonIterator* class_itr = jsonNewIterator( _tmp );
2366                         while ( (snode = jsonIteratorNext( class_itr )) ) {
2367
2368                                 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
2369                                         continue;
2370
2371                                 if ( snode->type == JSON_HASH ) {
2372
2373                                         jsonIterator* order_itr = jsonNewIterator( snode );
2374                                         while ( (onode = jsonIteratorNext( order_itr )) ) {
2375
2376                                                 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
2377                                                         continue;
2378
2379                                                 char* direction = NULL;
2380                                                 if ( onode->type == JSON_HASH ) {
2381                                                         if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
2382                                                                 string = searchFieldTransform(
2383                                                                         class_itr->key,
2384                                                                         oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
2385                                                                         onode
2386                                                                 );
2387                                                         } else {
2388                                                                 growing_buffer* field_buf = buffer_init(16);
2389                                                                 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
2390                                                                 string = buffer_release(field_buf);
2391                                                         }
2392
2393                                                         if ( (_tmp = jsonObjectGetKeyConst( onode, "direction" )) ) {
2394                                                                 direction = jsonObjectToSimpleString(_tmp);
2395                                                                 if (!strncasecmp(direction, "d", 1)) {
2396                                                                         free(direction);
2397                                                                         direction = " DESC";
2398                                                                 } else {
2399                                                                         free(direction);
2400                                                                         direction = " ASC";
2401                                                                 }
2402                                                         }
2403
2404                                                 } else {
2405                                                         string = strdup(order_itr->key);
2406                                                         direction = jsonObjectToSimpleString(onode);
2407                                                         if (!strncasecmp(direction, "d", 1)) {
2408                                                                 free(direction);
2409                                                                 direction = " DESC";
2410                                                         } else {
2411                                                                 free(direction);
2412                                                                 direction = " ASC";
2413                                                         }
2414                                                 }
2415
2416                                                 if (first) {
2417                                                         first = 0;
2418                                                 } else {
2419                                                         buffer_add(order_buf, ", ");
2420                                                 }
2421
2422                                                 buffer_add(order_buf, string);
2423                                                 free(string);
2424
2425                                                 if (direction) {
2426                                                         buffer_add(order_buf, direction);
2427                                                 }
2428
2429                                         }
2430
2431                     jsonIteratorFree(order_itr);
2432
2433                                 } else {
2434                                         string = jsonObjectToSimpleString(snode);
2435                                         buffer_add(order_buf, string);
2436                                         free(string);
2437                                         break;
2438                                 }
2439
2440                         }
2441
2442             jsonIteratorFree(class_itr);
2443
2444                         string = buffer_release(order_buf);
2445
2446                         if (strlen(string)) {
2447                                 buffer_fadd(
2448                                         sql_buf,
2449                                         " ORDER BY %s",
2450                                         string
2451                                 );
2452                         }
2453
2454                         free(string);
2455                 }
2456
2457                 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "limit" )) ){
2458                         string = jsonObjectToSimpleString(_tmp);
2459                         buffer_fadd(
2460                                 sql_buf,
2461                                 " LIMIT %d",
2462                                 atoi(string)
2463                         );
2464                         free(string);
2465                 }
2466
2467                 _tmp = jsonObjectGetKeyConst( order_hash, "offset" );
2468                 if (_tmp) {
2469                         string = jsonObjectToSimpleString(_tmp);
2470                         buffer_fadd(
2471                                 sql_buf,
2472                                 " OFFSET %d",
2473                                 atoi(string)
2474                         );
2475                         free(string);
2476                 }
2477         }
2478
2479         if (defaultselhash) jsonObjectFree(defaultselhash);
2480
2481         buffer_add(sql_buf, ";");
2482         return buffer_release(sql_buf);
2483 }
2484
2485 int doJSONSearch ( osrfMethodContext* ctx ) {
2486         OSRF_METHOD_VERIFY_CONTEXT(ctx);
2487         osrfLogDebug(OSRF_LOG_MARK, "Recieved query request");
2488
2489         int err = 0;
2490
2491         // XXX for now...
2492         dbhandle = writehandle;
2493
2494         jsonObject* hash = jsonObjectGetIndex(ctx->params, 0);
2495
2496     int flags = 0;
2497
2498         if (jsonBoolIsTrue(jsonObjectGetKey( hash, "distinct" )))
2499          flags |= SELECT_DISTINCT;
2500
2501         if ( ((int)jsonObjectGetNumber(jsonObjectGetKey( hash, "distinct" ))) == 1 ) // support 1/0 for perl's sake
2502          flags |= SELECT_DISTINCT;
2503
2504         if (jsonBoolIsTrue(jsonObjectGetKey( hash, "no_i18n" )))
2505          flags |= DISABLE_I18N;
2506
2507         if ( ((int)jsonObjectGetNumber(jsonObjectGetKey( hash, "no_i18n" ))) == 1 ) // support 1/0 for perl's sake
2508          flags |= DISABLE_I18N;
2509
2510         osrfLogDebug(OSRF_LOG_MARK, "Building SQL ...");
2511         char* sql = SELECT(
2512                         ctx,
2513                         jsonObjectGetKey( hash, "select" ),
2514                         jsonObjectGetKey( hash, "from" ),
2515                         jsonObjectGetKey( hash, "where" ),
2516                         jsonObjectGetKey( hash, "having" ),
2517                         jsonObjectGetKey( hash, "order_by" ),
2518                         jsonObjectGetKey( hash, "limit" ),
2519                         jsonObjectGetKey( hash, "offset" ),
2520                         flags
2521         );
2522
2523         if (!sql) {
2524                 err = -1;
2525                 return err;
2526         }
2527         
2528         osrfLogDebug(OSRF_LOG_MARK, "%s SQL =  %s", MODULENAME, sql);
2529         dbi_result result = dbi_conn_query(dbhandle, sql);
2530
2531         if(result) {
2532                 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
2533
2534                 if (dbi_result_first_row(result)) {
2535                         /* JSONify the result */
2536                         osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
2537
2538                         do {
2539                                 jsonObject* return_val = oilsMakeJSONFromResult( result );
2540                                 osrfAppRespond( ctx, return_val );
2541                 jsonObjectFree( return_val );
2542                         } while (dbi_result_next_row(result));
2543
2544                 } else {
2545                         osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
2546                 }
2547
2548                 osrfAppRespondComplete( ctx, NULL );
2549
2550                 /* clean up the query */
2551                 dbi_result_free(result); 
2552
2553         } else {
2554                 err = -1;
2555                 osrfLogError(OSRF_LOG_MARK, "%s: Error with query [%s]", MODULENAME, sql);
2556                 osrfAppSessionStatus(
2557                         ctx->session,
2558                         OSRF_STATUS_INTERNALSERVERERROR,
2559                         "osrfMethodException",
2560                         ctx->request,
2561                         "Severe query error -- see error log for more details"
2562                 );
2563         }
2564
2565         free(sql);
2566         return err;
2567 }
2568
2569 static jsonObject* doFieldmapperSearch ( osrfMethodContext* ctx, osrfHash* meta,
2570                 const jsonObject* params, int* err ) {
2571
2572         // XXX for now...
2573         dbhandle = writehandle;
2574
2575         osrfHash* links = osrfHashGet(meta, "links");
2576         osrfHash* fields = osrfHashGet(meta, "fields");
2577         char* core_class = osrfHashGet(meta, "classname");
2578         char* pkey = osrfHashGet(meta, "primarykey");
2579
2580         const jsonObject* _tmp;
2581         jsonObject* obj;
2582         jsonObject* search_hash = jsonObjectGetIndex(params, 0);
2583         jsonObject* order_hash = jsonObjectGetIndex(params, 1);
2584
2585         char* sql = buildSELECT( search_hash, order_hash, meta, ctx );
2586         if (!sql) {
2587                 *err = -1;
2588                 return NULL;
2589         }
2590         
2591         osrfLogDebug(OSRF_LOG_MARK, "%s SQL =  %s", MODULENAME, sql);
2592         dbi_result result = dbi_conn_query(dbhandle, sql);
2593
2594         jsonObject* res_list = jsonNewObjectType(JSON_ARRAY);
2595         if(result) {
2596                 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
2597                 osrfHash* dedup = osrfNewHash();
2598
2599                 if (dbi_result_first_row(result)) {
2600                         /* JSONify the result */
2601                         osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
2602                         do {
2603                                 obj = oilsMakeFieldmapperFromResult( result, meta );
2604                                 int pkey_pos = atoi( osrfHashGet( osrfHashGet( fields, pkey ), "array_position" ) );
2605                                 char* pkey_val = jsonObjectToSimpleString( jsonObjectGetIndex( obj, pkey_pos ) );
2606                                 if ( osrfHashGet( dedup, pkey_val ) ) {
2607                                         jsonObjectFree(obj);
2608                                         free(pkey_val);
2609                                 } else {
2610                                         osrfHashSet( dedup, pkey_val, pkey_val );
2611                                         jsonObjectPush(res_list, obj);
2612                                 }
2613                         } while (dbi_result_next_row(result));
2614                 } else {
2615                         osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
2616                 }
2617
2618                 osrfHashFree(dedup);
2619
2620                 /* clean up the query */
2621                 dbi_result_free(result); 
2622
2623         } else {
2624                 osrfLogError(OSRF_LOG_MARK, "%s: Error retrieving %s with query [%s]", MODULENAME, osrfHashGet(meta, "fieldmapper"), sql);
2625                 osrfAppSessionStatus(
2626                         ctx->session,
2627                         OSRF_STATUS_INTERNALSERVERERROR,
2628                         "osrfMethodException",
2629                         ctx->request,
2630                         "Severe query error -- see error log for more details"
2631                 );
2632                 *err = -1;
2633                 free(sql);
2634                 jsonObjectFree(res_list);
2635                 return jsonNULL;
2636
2637         }
2638
2639         free(sql);
2640
2641         if (res_list->size && order_hash) {
2642                 _tmp = jsonObjectGetKeyConst( order_hash, "flesh" );
2643                 if (_tmp) {
2644                         int x = (int)jsonObjectGetNumber(_tmp);
2645                         if (x == -1 || x > max_flesh_depth) x = max_flesh_depth;
2646
2647                         const jsonObject* temp_blob;
2648                         if ((temp_blob = jsonObjectGetKeyConst( order_hash, "flesh_fields" )) && x > 0) {
2649
2650                                 jsonObject* flesh_blob = jsonObjectClone( temp_blob );
2651                                 const jsonObject* flesh_fields = jsonObjectGetKeyConst( flesh_blob, core_class );
2652
2653                                 osrfStringArray* link_fields = NULL;
2654
2655                                 if (flesh_fields) {
2656                                         if (flesh_fields->size == 1) {
2657                                                 char* _t = jsonObjectToSimpleString( jsonObjectGetIndex( flesh_fields, 0 ) );
2658                                                 if (!strcmp(_t,"*")) link_fields = osrfHashKeys( links );
2659                                                 free(_t);
2660                                         }
2661
2662                                         if (!link_fields) {
2663                                                 jsonObject* _f;
2664                                                 link_fields = osrfNewStringArray(1);
2665                                                 jsonIterator* _i = jsonNewIterator( flesh_fields );
2666                                                 while ((_f = jsonIteratorNext( _i ))) {
2667                                                         osrfStringArrayAdd( link_fields, jsonObjectToSimpleString( _f ) );
2668                                                 }
2669                         jsonIteratorFree(_i);
2670                                         }
2671                                 }
2672
2673                                 jsonObject* cur;
2674                                 jsonIterator* itr = jsonNewIterator( res_list );
2675                                 while ((cur = jsonIteratorNext( itr ))) {
2676
2677                                         int i = 0;
2678                                         char* link_field;
2679                                         
2680                                         while ( (link_field = osrfStringArrayGetString(link_fields, i++)) ) {
2681
2682                                                 osrfLogDebug(OSRF_LOG_MARK, "Starting to flesh %s", link_field);
2683
2684                                                 osrfHash* kid_link = osrfHashGet(links, link_field);
2685                                                 if (!kid_link) continue;
2686
2687                                                 osrfHash* field = osrfHashGet(fields, link_field);
2688                                                 if (!field) continue;
2689
2690                                                 osrfHash* value_field = field;
2691
2692                                                 osrfHash* kid_idl = osrfHashGet(oilsIDL(), osrfHashGet(kid_link, "class"));
2693                                                 if (!kid_idl) continue;
2694
2695                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
2696                                                         value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
2697                                                 }
2698                                                         
2699                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) { // might_have
2700                                                         value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
2701                                                 }
2702
2703                                                 osrfStringArray* link_map = osrfHashGet( kid_link, "map" );
2704
2705                                                 if (link_map->size > 0) {
2706                                                         jsonObject* _kid_key = jsonNewObjectType(JSON_ARRAY);
2707                                                         jsonObjectPush(
2708                                                                 _kid_key,
2709                                                                 jsonNewObject( osrfStringArrayGetString( link_map, 0 ) )
2710                                                         );
2711
2712                                                         jsonObjectSetKey(
2713                                                                 flesh_blob,
2714                                                                 osrfHashGet(kid_link, "class"),
2715                                                                 _kid_key
2716                                                         );
2717                                                 };
2718
2719                                                 osrfLogDebug(
2720                                                         OSRF_LOG_MARK,
2721                                                         "Link field: %s, remote class: %s, fkey: %s, reltype: %s",
2722                                                         osrfHashGet(kid_link, "field"),
2723                                                         osrfHashGet(kid_link, "class"),
2724                                                         osrfHashGet(kid_link, "key"),
2725                                                         osrfHashGet(kid_link, "reltype")
2726                                                 );
2727
2728                                                 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
2729                                                 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // search hash
2730                                                 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // order/flesh hash
2731
2732                                                 osrfLogDebug(OSRF_LOG_MARK, "Creating dummy params object...");
2733
2734                                                 char* search_key =
2735                                                 jsonObjectToSimpleString(
2736                                                         jsonObjectGetIndex(
2737                                                                 cur,
2738                                                                 atoi( osrfHashGet(value_field, "array_position") )
2739                                                         )
2740                                                 );
2741
2742                                                 if (!search_key) {
2743                                                         osrfLogDebug(OSRF_LOG_MARK, "Nothing to search for!");
2744                                                         continue;
2745                                                 }
2746                                                         
2747                                                 jsonObjectSetKey(
2748                                                         jsonObjectGetIndex(fake_params, 0),
2749                                                         osrfHashGet(kid_link, "key"),
2750                                                         jsonNewObject( search_key )
2751                                                 );
2752
2753                                                 free(search_key);
2754
2755
2756                                                 jsonObjectSetKey(
2757                                                         jsonObjectGetIndex(fake_params, 1),
2758                                                         "flesh",
2759                                                         jsonNewNumberObject( (double)(x - 1 + link_map->size) )
2760                                                 );
2761
2762                                                 if (flesh_blob)
2763                                                         jsonObjectSetKey( jsonObjectGetIndex(fake_params, 1), "flesh_fields", jsonObjectClone(flesh_blob) );
2764
2765                                                 if (jsonObjectGetKeyConst(order_hash, "order_by")) {
2766                                                         jsonObjectSetKey(
2767                                                                 jsonObjectGetIndex(fake_params, 1),
2768                                                                 "order_by",
2769                                                                 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "order_by"))
2770                                                         );
2771                                                 }
2772
2773                                                 if (jsonObjectGetKeyConst(order_hash, "select")) {
2774                                                         jsonObjectSetKey(
2775                                                                 jsonObjectGetIndex(fake_params, 1),
2776                                                                 "select",
2777                                                                 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "select"))
2778                                                         );
2779                                                 }
2780
2781                                                 jsonObject* kids = doFieldmapperSearch(ctx, kid_idl, fake_params, err);
2782
2783                                                 if(*err) {
2784                                                         jsonObjectFree( fake_params );
2785                                                         osrfStringArrayFree(link_fields);
2786                                                         jsonIteratorFree(itr);
2787                                                         jsonObjectFree(res_list);
2788                                                         jsonObjectFree(flesh_blob);
2789                                                         return jsonNULL;
2790                                                 }
2791
2792                                                 osrfLogDebug(OSRF_LOG_MARK, "Search for %s return %d linked objects", osrfHashGet(kid_link, "class"), kids->size);
2793
2794                                                 jsonObject* X = NULL;
2795                                                 if ( link_map->size > 0 && kids->size > 0 ) {
2796                                                         X = kids;
2797                                                         kids = jsonNewObjectType(JSON_ARRAY);
2798
2799                                                         jsonObject* _k_node;
2800                                                         jsonIterator* _k = jsonNewIterator( X );
2801                                                         while ((_k_node = jsonIteratorNext( _k ))) {
2802                                                                 jsonObjectPush(
2803                                                                         kids,
2804                                                                         jsonObjectClone(
2805                                                                                 jsonObjectGetIndex(
2806                                                                                         _k_node,
2807                                                                                         (unsigned long)atoi(
2808                                                                                                 osrfHashGet(
2809                                                                                                         osrfHashGet(
2810                                                                                                                 osrfHashGet(
2811                                                                                                                         osrfHashGet(
2812                                                                                                                                 oilsIDL(),
2813                                                                                                                                 osrfHashGet(kid_link, "class")
2814                                                                                                                         ),
2815                                                                                                                         "fields"
2816                                                                                                                 ),
2817                                                                                                                 osrfStringArrayGetString( link_map, 0 )
2818                                                                                                         ),
2819                                                                                                         "array_position"
2820                                                                                                 )
2821                                                                                         )
2822                                                                                 )
2823                                                                         )
2824                                                                 );
2825                                                         }
2826                                                         jsonIteratorFree(_k);
2827                                                 }
2828
2829                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_a" )) || !(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) {
2830                                                         osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
2831                                                         jsonObjectSetIndex(
2832                                                                 cur,
2833                                                                 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
2834                                                                 jsonObjectClone( jsonObjectGetIndex(kids, 0) )
2835                                                         );
2836                                                 }
2837