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