]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/c-apps/oils_cstore.c
more debug logging
[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
922                 growing_buffer* msg = buffer_init(128);
923                 buffer_fadd(
924                     msg,
925                     "%s: no object found with primary key %s of %s",
926                     MODULENAME,
927                     pkey,
928                     pkey_value
929                 );
930         
931                 char* m = buffer_release(msg);
932                 osrfAppSessionStatus( ctx->session, OSRF_STATUS_BADREQUEST, "osrfMethodException", ctx->request, m );
933         
934                 free(m);
935                 free(pkey_value);
936
937                 return 0;
938             }
939
940             free(pkey_value);
941             jsonObjectFree(_tmp_params);
942             jsonObjectFree(_list);
943
944         }
945
946         if (local_context->size > 0) {
947                 osrfLogDebug( OSRF_LOG_MARK, "%d class-local context field(s) specified", local_context->size);
948             int i = 0;
949             char* lcontext = NULL;
950             while ( (lcontext = osrfStringArrayGetString(local_context, i++)) ) {
951                 osrfStringArrayAdd( context_org_array, oilsFMGetString( param, lcontext ) );
952                     osrfLogDebug( OSRF_LOG_MARK, "adding class-local field %s to the context org list", osrfStringArrayGetString(context_org_array, context_org_array->size - 1) );
953             }
954         }
955
956         osrfStringArray* class_list;
957
958         if (foreign_context) {
959             class_list = osrfHashKeys( foreign_context );
960                 osrfLogDebug( OSRF_LOG_MARK, "%d foreign context classes(s) specified", class_list->size);
961
962             if (class_list->size > 0) {
963     
964                 int i = 0;
965                 char* class_name = NULL;
966                 while ( (class_name = osrfStringArrayGetString(class_list, i++)) ) {
967                     osrfHash* fcontext = osrfHashGet(foreign_context, class_name);
968
969                         osrfLogDebug( OSRF_LOG_MARK, "%d foreign context fields(s) specified for class", ((osrfStringArray*)osrfHashGet(fcontext,"context"))->size, class_name);
970     
971                     jsonObject* _tmp_params = jsonParseStringFmt(
972                         "[{\"%s\":\"%s\"}]",
973                         osrfHashGet(fcontext, "field"),
974                         oilsFMGetString(param, osrfHashGet(fcontext, "fkey"))
975                     );
976     
977                         jsonObject* _list = doFieldmapperSearch(
978                         ctx,
979                         class,
980                         _tmp_params,
981                         &err
982                     );
983             
984        
985                     jsonObject* _fparam = jsonObjectGetIndex(_list, 0);
986             
987                     if (!_fparam) {
988                         jsonObjectFree(_tmp_params);
989                         jsonObjectFree(_list);
990                         return 0;
991                     }
992         
993                     jsonObjectFree(_tmp_params);
994                     jsonObjectFree(_list);
995     
996                     char* foreign_field = NULL;
997                     while ( (foreign_field = osrfStringArrayGetString(osrfHashGet(fcontext,"context"), i++)) ) {
998                         osrfStringArrayAdd( context_org_array, oilsFMGetString( _fparam, foreign_field ) );
999                     }
1000        
1001                     jsonObjectFree(_fparam);
1002                 }
1003     
1004                 osrfStringArrayFree(class_list);
1005             }
1006         }
1007
1008         jsonObjectFree(param);
1009     }
1010
1011     char* context_org = NULL;
1012     char* perm = NULL;
1013     int OK = 0;
1014
1015     if (permission->size == 0) {
1016             osrfLogDebug( OSRF_LOG_MARK, "No permission specified for this action, passing through" );
1017         OK = 1;
1018     }
1019     
1020     int i = 0;
1021     while ( (perm = osrfStringArrayGetString(permission, i++)) ) {
1022         int j = 0;
1023         while ( (context_org = osrfStringArrayGetString(context_org_array, j++)) ) {
1024             dbi_result result;
1025
1026             if (pkey_value) {
1027                     osrfLogDebug(
1028                     OSRF_LOG_MARK,
1029                     "Checking object permission [%s] for user %d on object %s (class %s) at org %d",
1030                     perm,
1031                     userid,
1032                     pkey_value,
1033                     osrfHashGet(class, "classname"),
1034                     atoi(context_org)
1035                 );
1036
1037                 result = dbi_conn_queryf(
1038                     writehandle,
1039                     "SELECT permission.usr_has_object_perm(%d, '%s', '%s', '%s', %d) AS has_perm;",
1040                     userid,
1041                     perm,
1042                     osrfHashGet(class, "classname"),
1043                     pkey_value,
1044                     atoi(context_org)
1045                 );
1046
1047                 if (result) {
1048                     jsonObject* return_val = oilsMakeJSONFromResult( result );
1049                     char* has_perm = jsonObjectToSimpleString( jsonObjectGetKeyConst(return_val, "has_perm") );
1050                     if ( *has_perm == 't' ) OK = 1;
1051                     free(has_perm); 
1052                     jsonObjectFree(return_val);
1053                     dbi_result_free(result); 
1054                     break;
1055                 }
1056             }
1057
1058                 osrfLogDebug( OSRF_LOG_MARK, "Checking non-object permission [%s] for user %d at org %d", perm, userid, atoi(context_org) );
1059             result = dbi_conn_queryf(
1060                 writehandle,
1061                 "SELECT permission.usr_has_perm(%d, '%s', %d) AS has_perm;",
1062                 userid,
1063                 perm,
1064                 atoi(context_org)
1065             );
1066
1067             if (result) {
1068                     osrfLogDebug( OSRF_LOG_MARK, "Recieved a result for perm [%s] for user %d at org %d", perm, userid, atoi(context_org) );
1069                 jsonObject* return_val = oilsMakeJSONFromResult( result );
1070                 char* has_perm = jsonObjectToSimpleString( jsonObjectGetKeyConst(return_val, "has_perm") );
1071                 if ( *has_perm == 't' ) OK = 1;
1072                     osrfLogDebug( OSRF_LOG_MARK, "Result for perm [%s] for user %d at org %d is [%s]", perm, userid, atoi(context_org), has_perm );
1073                 free(has_perm); 
1074                 jsonObjectFree(return_val);
1075                 dbi_result_free(result); 
1076                 break;
1077             }
1078
1079         }
1080         if (OK) break;
1081     }
1082
1083     if (pkey_value) free(pkey_value);
1084     osrfStringArrayFree(context_org_array);
1085
1086     return OK;
1087 }
1088 #endif
1089
1090
1091 static jsonObject* doCreate(osrfMethodContext* ctx, int* err ) {
1092
1093         osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1094 #ifdef PCRUD
1095         jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
1096         jsonObject* options = jsonObjectGetIndex( ctx->params, 2 );
1097 #else
1098         jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
1099         jsonObject* options = jsonObjectGetIndex( ctx->params, 1 );
1100 #endif
1101
1102         if (!verifyObjectClass(ctx, target)) {
1103                 *err = -1;
1104                 return jsonNULL;
1105         }
1106
1107         osrfLogDebug( OSRF_LOG_MARK, "Object seems to be of the correct type" );
1108
1109         if (!ctx->session || !ctx->session->userData || !osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
1110                 osrfLogError( OSRF_LOG_MARK, "No active transaction -- required for CREATE" );
1111
1112                 osrfAppSessionStatus(
1113                         ctx->session,
1114                         OSRF_STATUS_BADREQUEST,
1115                         "osrfMethodException",
1116                         ctx->request,
1117                         "No active transaction -- required for CREATE"
1118                 );
1119                 *err = -1;
1120                 return jsonNULL;
1121         }
1122
1123         if (osrfHashGet( meta, "readonly" ) && strncasecmp("true", osrfHashGet( meta, "readonly" ), 4)) {
1124                 osrfAppSessionStatus(
1125                         ctx->session,
1126                         OSRF_STATUS_BADREQUEST,
1127                         "osrfMethodException",
1128                         ctx->request,
1129                         "Cannot INSERT readonly class"
1130                 );
1131                 *err = -1;
1132                 return jsonNULL;
1133         }
1134
1135
1136         char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
1137
1138         // Set the last_xact_id
1139         int index = oilsIDL_ntop( target->classname, "last_xact_id" );
1140         if (index > -1) {
1141                 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
1142                 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
1143         }       
1144
1145         osrfLogDebug( OSRF_LOG_MARK, "There is a transaction running..." );
1146
1147         dbhandle = writehandle;
1148
1149         osrfHash* fields = osrfHashGet(meta, "fields");
1150         char* pkey = osrfHashGet(meta, "primarykey");
1151         char* seq = osrfHashGet(meta, "sequence");
1152
1153         growing_buffer* table_buf = buffer_init(128);
1154         growing_buffer* col_buf = buffer_init(128);
1155         growing_buffer* val_buf = buffer_init(128);
1156
1157         buffer_fadd(table_buf,"INSERT INTO %s", osrfHashGet(meta, "tablename"));
1158         buffer_add(col_buf,"(");
1159         buffer_add(val_buf,"VALUES (");
1160
1161
1162         int i = 0;
1163         int first = 1;
1164         char* field_name;
1165         osrfStringArray* field_list = osrfHashKeys( fields );
1166         while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
1167
1168                 osrfHash* field = osrfHashGet( fields, field_name );
1169
1170                 if(!( strcmp( osrfHashGet(osrfHashGet(fields,field_name), "virtual"), "true" ) )) continue;
1171
1172                 const jsonObject* field_object = oilsFMGetObject( target, field_name );
1173
1174                 char* value;
1175                 if (field_object && field_object->classname) {
1176                         value = oilsFMGetString(
1177                                 field_object,
1178                                 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
1179                         );
1180                 } else {
1181                         value = jsonObjectToSimpleString( field_object );
1182                 }
1183
1184
1185                 if (first) {
1186                         first = 0;
1187                 } else {
1188                         buffer_add(col_buf, ",");
1189                         buffer_add(val_buf, ",");
1190                 }
1191
1192                 buffer_add(col_buf, field_name);
1193
1194                 if (!field_object || field_object->type == JSON_NULL) {
1195                         buffer_add( val_buf, "DEFAULT" );
1196                         
1197                 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1198                         if ( !strcmp(osrfHashGet(field, "datatype"), "INT8") ) {
1199                                 buffer_fadd( val_buf, "%lld", atoll(value) );
1200                                 
1201                         } else if ( !strcmp(osrfHashGet(field, "datatype"), "INT") ) {
1202                                 buffer_fadd( val_buf, "%d", atoi(value) );
1203                                 
1204                         } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
1205                                 buffer_fadd( val_buf, "%f", atof(value) );
1206                         }
1207                 } else {
1208                         if ( dbi_conn_quote_string(writehandle, &value) ) {
1209                                 buffer_fadd( val_buf, "%s", value );
1210
1211                         } else {
1212                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
1213                                 osrfAppSessionStatus(
1214                                         ctx->session,
1215                                         OSRF_STATUS_INTERNALSERVERERROR,
1216                                         "osrfMethodException",
1217                                         ctx->request,
1218                                         "Error quoting string -- please see the error log for more details"
1219                                 );
1220                                 free(value);
1221                                 buffer_free(table_buf);
1222                                 buffer_free(col_buf);
1223                                 buffer_free(val_buf);
1224                                 *err = -1;
1225                                 return jsonNULL;
1226                         }
1227                 }
1228
1229                 free(value);
1230                 
1231         }
1232
1233
1234         buffer_add(col_buf,")");
1235         buffer_add(val_buf,")");
1236
1237         char* table_str = buffer_release(table_buf);
1238         char* col_str   = buffer_release(col_buf);
1239         char* val_str   = buffer_release(val_buf);
1240         growing_buffer* sql = buffer_init(128);
1241         buffer_fadd( sql, "%s %s %s;", table_str, col_str, val_str );
1242         free(table_str);
1243         free(col_str);
1244         free(val_str);
1245
1246         char* query = buffer_release(sql);
1247
1248         osrfLogDebug(OSRF_LOG_MARK, "%s: Insert SQL [%s]", MODULENAME, query);
1249
1250         
1251         dbi_result result = dbi_conn_query(writehandle, query);
1252
1253         jsonObject* obj = NULL;
1254
1255         if (!result) {
1256                 obj = jsonNewObject(NULL);
1257                 osrfLogError(
1258                         OSRF_LOG_MARK,
1259                         "%s ERROR inserting %s object using query [%s]",
1260                         MODULENAME,
1261                         osrfHashGet(meta, "fieldmapper"),
1262                         query
1263                 );
1264                 osrfAppSessionStatus(
1265                         ctx->session,
1266                         OSRF_STATUS_INTERNALSERVERERROR,
1267                         "osrfMethodException",
1268                         ctx->request,
1269                         "INSERT error -- please see the error log for more details"
1270                 );
1271                 *err = -1;
1272         } else {
1273
1274                 char* id = oilsFMGetString(target, pkey);
1275                 if (!id) {
1276                         unsigned long long new_id = dbi_conn_sequence_last(writehandle, seq);
1277                         growing_buffer* _id = buffer_init(10);
1278                         buffer_fadd(_id, "%lld", new_id);
1279                         id = buffer_release(_id);
1280                 }
1281
1282                 // Find quietness specification, if present
1283                 char* quiet_str = NULL;
1284                 if ( options ) {
1285                         const jsonObject* quiet_obj = jsonObjectGetKeyConst( options, "quiet" );
1286                         if( quiet_obj )
1287                                 quiet_str = jsonObjectToSimpleString( quiet_obj );
1288                 }
1289
1290                 if( quiet_str && !strcmp( quiet_str, "true" )) {  // if quietness is specified
1291                         obj = jsonNewObject(id);
1292                 }
1293                 else {
1294
1295                         jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
1296                         jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH));
1297
1298                         jsonObjectSetKey(
1299                                 jsonObjectGetIndex(fake_params, 0),
1300                                 pkey,
1301                                 jsonNewObject(id)
1302                         );
1303
1304                         jsonObject* list = doFieldmapperSearch( ctx,meta, fake_params, err);
1305
1306                         if(*err) {
1307                                 jsonObjectFree( fake_params );
1308                                 obj = jsonNULL;
1309                         } else {
1310                                 obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
1311                         }
1312
1313                         jsonObjectFree( list );
1314                         jsonObjectFree( fake_params );
1315                 }
1316
1317                 if(quiet_str) free(quiet_str);
1318                 free(id);
1319         }
1320
1321         free(query);
1322
1323         return obj;
1324
1325 }
1326
1327
1328 static jsonObject* doRetrieve(osrfMethodContext* ctx, int* err ) {
1329
1330     int id_pos = 0;
1331     int order_pos = 1;
1332
1333 #ifdef PCRUD
1334     id_pos = 1;
1335     order_pos = 2;
1336 #endif
1337
1338         osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1339
1340         jsonObject* obj;
1341
1342         char* id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, id_pos));
1343         jsonObject* order_hash = jsonObjectGetIndex(ctx->params, order_pos);
1344
1345         osrfLogDebug(
1346                 OSRF_LOG_MARK,
1347                 "%s retrieving %s object with primary key value of %s",
1348                 MODULENAME,
1349                 osrfHashGet(meta, "fieldmapper"),
1350                 id
1351         );
1352
1353         jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
1354         jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH));
1355
1356         jsonObjectSetKey(
1357                 jsonObjectGetIndex(fake_params, 0),
1358                 osrfHashGet(meta, "primarykey"),
1359                 jsonParseString(id)
1360         );
1361
1362         free(id);
1363
1364         if (order_hash) jsonObjectPush(fake_params, jsonObjectClone(order_hash) );
1365
1366         jsonObject* list = doFieldmapperSearch( ctx,meta, fake_params, err);
1367
1368         if(*err) {
1369                 jsonObjectFree( fake_params );
1370                 return jsonNULL;
1371         }
1372
1373         obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
1374
1375         jsonObjectFree( list );
1376         jsonObjectFree( fake_params );
1377
1378 #ifdef PCRUD
1379         if(!verifyObjectPCRUD(ctx, obj)) {
1380         jsonObjectFree(obj);
1381         *err = -1;
1382                 return jsonNULL;
1383         }
1384 #endif
1385
1386         return obj;
1387 }
1388
1389 static char* jsonNumberToDBString ( osrfHash* field, const jsonObject* value ) {
1390         growing_buffer* val_buf = buffer_init(32);
1391
1392         if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
1393                 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%ld", (long)jsonObjectGetNumber(value) );
1394                 else {
1395                         char* val_str = jsonObjectToSimpleString(value);
1396                         buffer_fadd( val_buf, "%ld", atol(val_str) );
1397                         free(val_str);
1398                 }
1399
1400         } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
1401                 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%f",  jsonObjectGetNumber(value) );
1402                 else {
1403                         char* val_str = jsonObjectToSimpleString(value);
1404                         buffer_fadd( val_buf, "%f", atof(val_str) );
1405                         free(val_str);
1406                 }
1407         }
1408
1409         return buffer_release(val_buf);
1410 }
1411
1412 static char* searchINPredicate (const char* class, osrfHash* field,
1413                 const jsonObject* node, const char* op) {
1414         growing_buffer* sql_buf = buffer_init(32);
1415         
1416         buffer_fadd(
1417                 sql_buf,
1418                 "\"%s\".%s ",
1419                 class,
1420                 osrfHashGet(field, "name")
1421         );
1422
1423         if (!op) {
1424                 buffer_add(sql_buf, "IN (");
1425         } else if (!(strcasecmp(op,"not in"))) {
1426                 buffer_add(sql_buf, "NOT IN (");
1427         } else {
1428                 buffer_add(sql_buf, "IN (");
1429         }
1430
1431         int in_item_index = 0;
1432         int in_item_first = 1;
1433         jsonObject* in_item;
1434         while ( (in_item = jsonObjectGetIndex(node, in_item_index++)) ) {
1435
1436                 if (in_item_first)
1437                         in_item_first = 0;
1438                 else
1439                         buffer_add(sql_buf, ", ");
1440
1441                 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1442                         char* val = jsonNumberToDBString( field, in_item );
1443                         buffer_fadd( sql_buf, "%s", val );
1444                         free(val);
1445
1446                 } else {
1447                         char* key_string = jsonObjectToSimpleString(in_item);
1448                         if ( dbi_conn_quote_string(dbhandle, &key_string) ) {
1449                                 buffer_fadd( sql_buf, "%s", key_string );
1450                                 free(key_string);
1451                         } else {
1452                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, key_string);
1453                                 free(key_string);
1454                                 buffer_free(sql_buf);
1455                                 return NULL;
1456                         }
1457                 }
1458         }
1459
1460         buffer_add(
1461                 sql_buf,
1462                 ")"
1463         );
1464
1465         return buffer_release(sql_buf);
1466 }
1467
1468 static char* searchValueTransform( const jsonObject* array ) {
1469         growing_buffer* sql_buf = buffer_init(32);
1470
1471         char* val = NULL;
1472         int func_item_index = 0;
1473         int func_item_first = 2;
1474         jsonObject* func_item;
1475         while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1476
1477                 val = jsonObjectToSimpleString(func_item);
1478
1479                 if (func_item_first == 2) {
1480                         buffer_fadd(sql_buf, "%s( ", val);
1481                         free(val);
1482                         func_item_first--;
1483                         continue;
1484                 }
1485
1486                 if (func_item_first)
1487                         func_item_first--;
1488                 else
1489                         buffer_add(sql_buf, ", ");
1490
1491                 if (func_item->type == JSON_NULL) {
1492                         buffer_add( sql_buf, "NULL" );
1493                 } else if ( dbi_conn_quote_string(dbhandle, &val) ) {
1494                         buffer_fadd( sql_buf, "%s", val );
1495                 } else {
1496                         osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1497                         free(val);
1498                         buffer_free(sql_buf);
1499                         return NULL;
1500                 }
1501
1502                 free(val);
1503         }
1504
1505         buffer_add(
1506                 sql_buf,
1507                 " )"
1508         );
1509
1510         return buffer_release(sql_buf);
1511 }
1512
1513 static char* searchFunctionPredicate (const char* class, osrfHash* field,
1514                 const jsonObject* node, const char* node_key) {
1515         growing_buffer* sql_buf = buffer_init(32);
1516
1517         char* val = searchValueTransform(node);
1518         
1519         buffer_fadd(
1520                 sql_buf,
1521                 "\"%s\".%s %s %s",
1522                 class,
1523                 osrfHashGet(field, "name"),
1524                 node_key,
1525                 val
1526         );
1527
1528         free(val);
1529
1530         return buffer_release(sql_buf);
1531 }
1532
1533 static char* searchFieldTransform (const char* class, osrfHash* field, const jsonObject* node) {
1534         growing_buffer* sql_buf = buffer_init(32);
1535         
1536         char* field_transform = jsonObjectToSimpleString( jsonObjectGetKeyConst( node, "transform" ) );
1537         char* transform_subcolumn = jsonObjectToSimpleString( jsonObjectGetKeyConst( node, "result_field" ) );
1538
1539         if (field_transform) {
1540                 buffer_fadd( sql_buf, "%s(\"%s\".%s", field_transform, class, osrfHashGet(field, "name"));
1541             const jsonObject* array = jsonObjectGetKeyConst( node, "params" );
1542
1543         if (array) {
1544                 int func_item_index = 0;
1545                 jsonObject* func_item;
1546                 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1547
1548                         char* val = jsonObjectToSimpleString(func_item);
1549
1550                     if ( !val ) {
1551                             buffer_add( sql_buf, ",NULL" );
1552                     } else if ( dbi_conn_quote_string(dbhandle, &val) ) {
1553                             buffer_fadd( sql_buf, ",%s", val );
1554                         } else {
1555                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1556                             free(field_transform);
1557                                         free(val);
1558                                 buffer_free(sql_buf);
1559                                 return NULL;
1560                 }
1561                                 free(val);
1562                         }
1563
1564         }
1565
1566         buffer_add(
1567                 sql_buf,
1568                 " )"
1569         );
1570
1571         } else {
1572                 buffer_fadd( sql_buf, "\"%s\".%s", class, osrfHashGet(field, "name"));
1573         }
1574
1575     if (transform_subcolumn) {
1576         char * tmp = buffer_release(sql_buf);
1577         sql_buf = buffer_init(32);
1578         buffer_fadd(
1579             sql_buf,
1580             "(%s).\"%s\"",
1581             tmp,
1582             transform_subcolumn
1583         );
1584         free(tmp);
1585     }
1586  
1587         if (field_transform) free(field_transform);
1588         if (transform_subcolumn) free(transform_subcolumn);
1589
1590         return buffer_release(sql_buf);
1591 }
1592
1593 static char* searchFieldTransformPredicate (const char* class, osrfHash* field, jsonObject* node, const char* node_key) {
1594         char* field_transform = searchFieldTransform( class, field, node );
1595         char* value = NULL;
1596
1597         if (!jsonObjectGetKeyConst( node, "value" )) {
1598                 value = searchWHERE( node, osrfHashGet( oilsIDL(), class ), AND_OP_JOIN, NULL );
1599         } else if (jsonObjectGetKeyConst( node, "value" )->type == JSON_ARRAY) {
1600                 value = searchValueTransform(jsonObjectGetKeyConst( node, "value" ));
1601         } else if (jsonObjectGetKeyConst( node, "value" )->type == JSON_HASH) {
1602                 value = searchWHERE( jsonObjectGetKeyConst( node, "value" ), osrfHashGet( oilsIDL(), class ), AND_OP_JOIN, NULL );
1603         } else if (jsonObjectGetKeyConst( node, "value" )->type != JSON_NULL) {
1604                 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1605                         value = jsonNumberToDBString( field, jsonObjectGetKeyConst( node, "value" ) );
1606                 } else {
1607                         value = jsonObjectToSimpleString(jsonObjectGetKeyConst( node, "value" ));
1608                         if ( !dbi_conn_quote_string(dbhandle, &value) ) {
1609                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, value);
1610                                 free(value);
1611                                 free(field_transform);
1612                                 return NULL;
1613                         }
1614                 }
1615         }
1616
1617         growing_buffer* sql_buf = buffer_init(32);
1618         
1619         buffer_fadd(
1620                 sql_buf,
1621                 "%s %s %s",
1622                 field_transform,
1623                 node_key,
1624                 value
1625         );
1626
1627         free(value);
1628         free(field_transform);
1629
1630         return buffer_release(sql_buf);
1631 }
1632
1633 static char* searchSimplePredicate (const char* orig_op, const char* class,
1634                 osrfHash* field, const jsonObject* node) {
1635
1636         char* val = NULL;
1637
1638         if (node->type != JSON_NULL) {
1639                 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1640                         val = jsonNumberToDBString( field, node );
1641                 } else {
1642                         val = jsonObjectToSimpleString(node);
1643                 }
1644         }
1645
1646         char* pred = searchWriteSimplePredicate( class, field, osrfHashGet(field, "name"), orig_op, val );
1647
1648         if (val) free(val);
1649
1650         return pred;
1651 }
1652
1653 static char* searchWriteSimplePredicate ( const char* class, osrfHash* field,
1654         const char* left, const char* orig_op, const char* right ) {
1655
1656         char* val = NULL;
1657         char* op = NULL;
1658         if (right == NULL) {
1659                 val = strdup("NULL");
1660
1661                 if (strcmp( orig_op, "=" ))
1662                         op = strdup("IS NOT");
1663                 else
1664                         op = strdup("IS");
1665
1666         } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1667                 val = strdup(right);
1668                 op = strdup(orig_op);
1669
1670         } else {
1671                 val = strdup(right);
1672                 if ( !dbi_conn_quote_string(dbhandle, &val) ) {
1673                         osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1674                         free(val);
1675                         return NULL;
1676                 }
1677                 op = strdup(orig_op);
1678         }
1679
1680         growing_buffer* sql_buf = buffer_init(16);
1681         buffer_fadd( sql_buf, "\"%s\".%s %s %s", class, left, op, val );
1682         free(val);
1683         free(op);
1684
1685         return buffer_release(sql_buf);
1686 }
1687
1688 static char* searchBETWEENPredicate (const char* class, osrfHash* field, jsonObject* node) {
1689
1690         char* x_string;
1691         char* y_string;
1692
1693         if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1694                 x_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,0));
1695                 y_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,1));
1696
1697         } else {
1698                 x_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,0));
1699                 y_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,1));
1700                 if ( !(dbi_conn_quote_string(dbhandle, &x_string) && dbi_conn_quote_string(dbhandle, &y_string)) ) {
1701                         osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key strings [%s] and [%s]", MODULENAME, x_string, y_string);
1702                         free(x_string);
1703                         free(y_string);
1704                         return NULL;
1705                 }
1706         }
1707
1708         growing_buffer* sql_buf = buffer_init(32);
1709         buffer_fadd( sql_buf, "%s BETWEEN %s AND %s", osrfHashGet(field, "name"), x_string, y_string );
1710         free(x_string);
1711         free(y_string);
1712
1713         return buffer_release(sql_buf);
1714 }
1715
1716 static char* searchPredicate ( const char* class, osrfHash* field, jsonObject* node ) {
1717
1718         char* pred = NULL;
1719         if (node->type == JSON_ARRAY) { // equality IN search
1720                 pred = searchINPredicate( class, field, node, NULL );
1721         } else if (node->type == JSON_HASH) { // non-equality search
1722                 jsonObject* pred_node;
1723                 jsonIterator* pred_itr = jsonNewIterator( node );
1724                 while ( (pred_node = jsonIteratorNext( pred_itr )) ) {
1725                         if ( !(strcasecmp( pred_itr->key,"between" )) )
1726                                 pred = searchBETWEENPredicate( class, field, pred_node );
1727                         else if ( !(strcasecmp( pred_itr->key,"in" )) || !(strcasecmp( pred_itr->key,"not in" )) )
1728                                 pred = searchINPredicate( class, field, pred_node, pred_itr->key );
1729                         else if ( pred_node->type == JSON_ARRAY )
1730                                 pred = searchFunctionPredicate( class, field, pred_node, pred_itr->key );
1731                         else if ( pred_node->type == JSON_HASH )
1732                                 pred = searchFieldTransformPredicate( class, field, pred_node, pred_itr->key );
1733                         else 
1734                                 pred = searchSimplePredicate( pred_itr->key, class, field, pred_node );
1735
1736                         break;
1737                 }
1738         jsonIteratorFree(pred_itr);
1739         } else if (node->type == JSON_NULL) { // IS NULL search
1740                 growing_buffer* _p = buffer_init(64);
1741                 buffer_fadd(
1742                         _p,
1743                         "\"%s\".%s IS NULL",
1744                         class,
1745                         osrfHashGet(field, "name")
1746                 );
1747                 pred = buffer_release(_p);
1748         } else { // equality search
1749                 pred = searchSimplePredicate( "=", class, field, node );
1750         }
1751
1752         return pred;
1753
1754 }
1755
1756
1757 /*
1758
1759 join : {
1760         acn : {
1761                 field : record,
1762                 fkey : id
1763                 type : left
1764                 filter_op : or
1765                 filter : { ... },
1766                 join : {
1767                         acp : {
1768                                 field : call_number,
1769                                 fkey : id,
1770                                 filter : { ... },
1771                         },
1772                 },
1773         },
1774         mrd : {
1775                 field : record,
1776                 type : inner
1777                 fkey : id,
1778                 filter : { ... },
1779         }
1780 }
1781
1782 */
1783
1784 static char* searchJOIN ( const jsonObject* join_hash, osrfHash* leftmeta ) {
1785
1786         const jsonObject* working_hash;
1787         jsonObject* freeable_hash = NULL;
1788
1789         if (join_hash->type == JSON_STRING) {
1790                 // create a wrapper around a copy of the original
1791                 char* _tmp = jsonObjectToSimpleString( join_hash );
1792                 freeable_hash = jsonNewObjectType(JSON_HASH);
1793                 jsonObjectSetKey(freeable_hash, _tmp, NULL);
1794                 free(_tmp);
1795                 working_hash = freeable_hash;
1796         }
1797         else
1798                 working_hash = join_hash;
1799
1800         growing_buffer* join_buf = buffer_init(128);
1801         char* leftclass = osrfHashGet(leftmeta, "classname");
1802
1803         jsonObject* snode = NULL;
1804         jsonIterator* search_itr = jsonNewIterator( working_hash );
1805         if(freeable_hash)
1806                 jsonObjectFree(freeable_hash);
1807         
1808         while ( (snode = jsonIteratorNext( search_itr )) ) {
1809                 osrfHash* idlClass = osrfHashGet( oilsIDL(), search_itr->key );
1810
1811                 char* class = osrfHashGet(idlClass, "classname");
1812
1813                 char* fkey = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "fkey" ) );
1814                 char* field = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "field" ) );
1815
1816                 if (field && !fkey) {
1817                         fkey = (char*)oilsIDLFindPath("/%s/links/%s/key", class, field);
1818                         if (!fkey) {
1819                                 osrfLogError(
1820                                         OSRF_LOG_MARK,
1821                                         "%s: JOIN failed.  No link defined from %s.%s to %s",
1822                                         MODULENAME,
1823                                         class,
1824                                         field,
1825                                         leftclass
1826                                 );
1827                                 buffer_free(join_buf);
1828                                 free(field);
1829                                 jsonIteratorFree(search_itr);
1830                                 return NULL;
1831                         }
1832                         fkey = strdup( fkey );
1833
1834                 } else if (!field && fkey) {
1835                         field = (char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, fkey );
1836                         if (!field) {
1837                                 osrfLogError(
1838                                         OSRF_LOG_MARK,
1839                                         "%s: JOIN failed.  No link defined from %s.%s to %s",
1840                                         MODULENAME,
1841                                         leftclass,
1842                                         fkey,
1843                                         class
1844                                 );
1845                                 buffer_free(join_buf);
1846                                 free(fkey);
1847                                 jsonIteratorFree(search_itr);
1848                                 return NULL;
1849                         }
1850                         field = strdup( field );
1851
1852                 } else if (!field && !fkey) {
1853                         osrfHash* _links = oilsIDLFindPath("/%s/links", leftclass);
1854
1855                         int i = 0;
1856                         osrfStringArray* keys = osrfHashKeys( _links );
1857                         while ( (fkey = osrfStringArrayGetString(keys, i++)) ) {
1858                                 fkey = strdup(osrfStringArrayGetString(keys, i++));
1859                                 if ( !strcmp( (char*)oilsIDLFindPath("/%s/links/%s/class", leftclass, fkey), class) ) {
1860                                         field = strdup( (char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, fkey) );
1861                                         break;
1862                                 } else {
1863                                         free(fkey);
1864                                 }
1865                         }
1866                         osrfStringArrayFree(keys);
1867
1868                         if (!field && !fkey) {
1869                                 _links = oilsIDLFindPath("/%s/links", class);
1870
1871                                 i = 0;
1872                                 keys = osrfHashKeys( _links );
1873                                 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
1874                                         field = strdup(osrfStringArrayGetString(keys, i++));
1875                                         if ( !strcmp( (char*)oilsIDLFindPath("/%s/links/%s/class", class, field), class) ) {
1876                                                 fkey = strdup( (char*)oilsIDLFindPath("/%s/links/%s/key", class, field) );
1877                                                 break;
1878                                         } else {
1879                                                 free(field);
1880                                         }
1881                                 }
1882                                 osrfStringArrayFree(keys);
1883                         }
1884
1885                         if (!field && !fkey) {
1886                                 osrfLogError(
1887                                         OSRF_LOG_MARK,
1888                                         "%s: JOIN failed.  No link defined between %s and %s",
1889                                         MODULENAME,
1890                                         leftclass,
1891                                         class
1892                                 );
1893                                 buffer_free(join_buf);
1894                                 jsonIteratorFree(search_itr);
1895                                 return NULL;
1896                         }
1897
1898                 }
1899
1900                 char* type = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "type" ) );
1901                 if (type) {
1902                         if ( !strcasecmp(type,"left") ) {
1903                                 buffer_add(join_buf, " LEFT JOIN");
1904                         } else if ( !strcasecmp(type,"right") ) {
1905                                 buffer_add(join_buf, " RIGHT JOIN");
1906                         } else if ( !strcasecmp(type,"full") ) {
1907                                 buffer_add(join_buf, " FULL JOIN");
1908                         } else {
1909                                 buffer_add(join_buf, " INNER JOIN");
1910                         }
1911                 } else {
1912                         buffer_add(join_buf, " INNER JOIN");
1913                 }
1914                 free(type);
1915
1916                 char* table = getSourceDefinition(idlClass);
1917                 buffer_fadd(join_buf, " %s AS \"%s\" ON ( \"%s\".%s = \"%s\".%s", table, class, class, field, leftclass, fkey);
1918                 free(table);
1919
1920                 const jsonObject* filter = jsonObjectGetKeyConst( snode, "filter" );
1921                 if (filter) {
1922                         char* filter_op = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "filter_op" ) );
1923                         if (filter_op) {
1924                                 if (!strcasecmp("or",filter_op)) {
1925                                         buffer_add( join_buf, " OR " );
1926                                 } else {
1927                                         buffer_add( join_buf, " AND " );
1928                                 }
1929                         } else {
1930                                 buffer_add( join_buf, " AND " );
1931                         }
1932
1933                         char* jpred = searchWHERE( filter, idlClass, AND_OP_JOIN, NULL );
1934                         buffer_fadd( join_buf, " %s", jpred );
1935                         free(jpred);
1936                         free(filter_op);
1937                 }
1938
1939                 buffer_add(join_buf, " ) ");
1940                 
1941                 const jsonObject* join_filter = jsonObjectGetKeyConst( snode, "join" );
1942                 if (join_filter) {
1943                         char* jpred = searchJOIN( join_filter, idlClass );
1944                         buffer_fadd( join_buf, " %s", jpred );
1945                         free(jpred);
1946                 }
1947
1948                 free(fkey);
1949                 free(field);
1950         }
1951
1952     jsonIteratorFree(search_itr);
1953
1954         return buffer_release(join_buf);
1955 }
1956
1957 /*
1958
1959 { +class : { -or|-and : { field : { op : value }, ... } ... }, ... }
1960 { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }
1961 [ { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }, ... ]
1962
1963 */
1964
1965 static char* searchWHERE ( const jsonObject* search_hash, osrfHash* meta, int opjoin_type, osrfMethodContext* ctx ) {
1966
1967         growing_buffer* sql_buf = buffer_init(128);
1968
1969         jsonObject* node = NULL;
1970
1971     int first = 1;
1972     if ( search_hash->type == JSON_ARRAY ) {
1973         jsonIterator* search_itr = jsonNewIterator( search_hash );
1974         while ( (node = jsonIteratorNext( search_itr )) ) {
1975             if (first) {
1976                 first = 0;
1977             } else {
1978                 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
1979                 else buffer_add(sql_buf, " AND ");
1980             }
1981
1982             char* subpred = searchWHERE( node, meta, opjoin_type, ctx );
1983             buffer_fadd(sql_buf, "( %s )", subpred);
1984             free(subpred);
1985         }
1986         jsonIteratorFree(search_itr);
1987
1988     } else if ( search_hash->type == JSON_HASH ) {
1989         jsonIterator* search_itr = jsonNewIterator( search_hash );
1990         while ( (node = jsonIteratorNext( search_itr )) ) {
1991
1992             if (first) {
1993                 first = 0;
1994             } else {
1995                 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
1996                 else buffer_add(sql_buf, " AND ");
1997             }
1998
1999             if ( !strncmp("+",search_itr->key,1) ) {
2000                 if ( node->type == JSON_STRING ) {
2001                     char* subpred = jsonObjectToSimpleString( node );
2002                     buffer_fadd(sql_buf, " \"%s\".%s ", search_itr->key + 1, subpred);
2003                     free(subpred);
2004                 } else {
2005                     char* subpred = searchWHERE( node, osrfHashGet( oilsIDL(), search_itr->key + 1 ), AND_OP_JOIN, ctx );
2006                     buffer_fadd(sql_buf, "( %s )", subpred);
2007                     free(subpred);
2008                 }
2009             } else if ( !strcasecmp("-or",search_itr->key) ) {
2010                 char* subpred = searchWHERE( node, meta, OR_OP_JOIN, ctx );
2011                 buffer_fadd(sql_buf, "( %s )", subpred);
2012                 free(subpred);
2013             } else if ( !strcasecmp("-and",search_itr->key) ) {
2014                 char* subpred = searchWHERE( node, meta, AND_OP_JOIN, ctx );
2015                 buffer_fadd(sql_buf, "( %s )", subpred);
2016                 free(subpred);
2017             } else if ( !strcasecmp("-exists",search_itr->key) ) {
2018                 char* subpred = SELECT(
2019                     ctx,
2020                     jsonObjectGetKey( node, "select" ),
2021                     jsonObjectGetKey( node, "from" ),
2022                     jsonObjectGetKey( node, "where" ),
2023                     jsonObjectGetKey( node, "having" ),
2024                     jsonObjectGetKey( node, "order_by" ),
2025                     jsonObjectGetKey( node, "limit" ),
2026                     jsonObjectGetKey( node, "offset" ),
2027                     SUBSELECT
2028                 );
2029
2030                 buffer_fadd(sql_buf, "EXISTS ( %s )", subpred);
2031                 free(subpred);
2032             } else if ( !strcasecmp("-not-exists",search_itr->key) ) {
2033                 char* subpred = SELECT(
2034                     ctx,
2035                     jsonObjectGetKey( node, "select" ),
2036                     jsonObjectGetKey( node, "from" ),
2037                     jsonObjectGetKey( node, "where" ),
2038                     jsonObjectGetKey( node, "having" ),
2039                     jsonObjectGetKey( node, "order_by" ),
2040                     jsonObjectGetKey( node, "limit" ),
2041                     jsonObjectGetKey( node, "offset" ),
2042                     SUBSELECT
2043                 );
2044
2045                 buffer_fadd(sql_buf, "NOT EXISTS ( %s )", subpred);
2046                 free(subpred);
2047             } else {
2048
2049                 char* class = osrfHashGet(meta, "classname");
2050                 osrfHash* fields = osrfHashGet(meta, "fields");
2051                 osrfHash* field = osrfHashGet( fields, search_itr->key );
2052
2053
2054                 if (!field) {
2055                     char* table = getSourceDefinition(meta);
2056                     osrfLogError(
2057                         OSRF_LOG_MARK,
2058                         "%s: Attempt to reference non-existant column %s on %s (%s)",
2059                         MODULENAME,
2060                         search_itr->key,
2061                         table,
2062                         class
2063                     );
2064                     buffer_free(sql_buf);
2065                     free(table);
2066                                         jsonIteratorFree(search_itr);
2067                                         return NULL;
2068                 }
2069
2070                 char* subpred = searchPredicate( class, field, node );
2071                 buffer_add( sql_buf, subpred );
2072                 free(subpred);
2073             }
2074         }
2075             jsonIteratorFree(search_itr);
2076
2077     } else {
2078         // ERROR ... only hash and array allowed at this level
2079         char* predicate_string = jsonObjectToJSON( search_hash );
2080         osrfLogError(
2081             OSRF_LOG_MARK,
2082             "%s: Invalid predicate structure: %s",
2083             MODULENAME,
2084             predicate_string
2085         );
2086         buffer_free(sql_buf);
2087         free(predicate_string);
2088         return NULL;
2089     }
2090
2091
2092         return buffer_release(sql_buf);
2093 }
2094
2095 static char* SELECT (
2096                 /* method context */ osrfMethodContext* ctx,
2097                 
2098                 /* SELECT   */ jsonObject* selhash,
2099                 /* FROM     */ jsonObject* join_hash,
2100                 /* WHERE    */ jsonObject* search_hash,
2101                 /* HAVING   */ jsonObject* having_hash,
2102                 /* ORDER BY */ jsonObject* order_hash,
2103                 /* LIMIT    */ jsonObject* limit,
2104                 /* OFFSET   */ jsonObject* offset,
2105                 /* flags    */ int flags
2106 ) {
2107         const char* locale = osrf_message_get_last_locale();
2108
2109         // in case we don't get a select list
2110         jsonObject* defaultselhash = NULL;
2111
2112         // general tmp objects
2113         const jsonObject* tmp_const;
2114         jsonObject* _tmp = NULL;
2115         jsonObject* selclass = NULL;
2116         jsonObject* selfield = NULL;
2117         jsonObject* snode = NULL;
2118         jsonObject* onode = NULL;
2119         jsonObject* found = NULL;
2120
2121         char* string = NULL;
2122         int from_function = 0;
2123         int first = 1;
2124         int gfirst = 1;
2125         //int hfirst = 1;
2126
2127         // the core search class
2128         char* core_class = NULL;
2129
2130         // metadata about the core search class
2131         osrfHash* core_meta = NULL;
2132         osrfHash* core_fields = NULL;
2133         osrfHash* idlClass = NULL;
2134
2135         // punt if there's no core class
2136         if (!join_hash || ( join_hash->type == JSON_HASH && !join_hash->size ))
2137                 return NULL;
2138
2139         // get the core class -- the only key of the top level FROM clause, or a string
2140         if (join_hash->type == JSON_HASH) {
2141                 jsonIterator* tmp_itr = jsonNewIterator( join_hash );
2142                 snode = jsonIteratorNext( tmp_itr );
2143                 
2144                 core_class = strdup( tmp_itr->key );
2145                 join_hash = snode;
2146
2147                 jsonIteratorFree( tmp_itr );
2148                 snode = NULL;
2149
2150         } else if (join_hash->type == JSON_ARRAY) {
2151         from_function = 1;
2152         selhash = NULL;
2153
2154         } else if (join_hash->type == JSON_STRING) {
2155                 core_class = jsonObjectToSimpleString( join_hash );
2156                 join_hash = NULL;
2157         }
2158
2159         // punt if we don't know about the core class (and it's not a function)
2160         if (!from_function && !(core_meta = osrfHashGet( oilsIDL(), core_class ))) {
2161                 free(core_class);
2162                 return NULL;
2163         }
2164
2165         // if the select list is empty, or the core class field list is '*',
2166         // build the default select list ...
2167         if (!selhash) {
2168                 selhash = defaultselhash = jsonNewObjectType(JSON_HASH);
2169                 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2170         } else if ( (tmp_const = jsonObjectGetKeyConst( selhash, core_class )) && tmp_const->type == JSON_STRING ) {
2171                 char* _x = jsonObjectToSimpleString( tmp_const );
2172                 if (!strncmp( "*", _x, 1 )) {
2173                         jsonObjectRemoveKey( selhash, core_class );
2174                         jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2175                 }
2176                 free(_x);
2177         }
2178
2179         // the query buffer
2180         growing_buffer* sql_buf = buffer_init(128);
2181
2182         // temp buffer for the SELECT list
2183         growing_buffer* select_buf = buffer_init(128);
2184         growing_buffer* order_buf = buffer_init(128);
2185         growing_buffer* group_buf = buffer_init(128);
2186         growing_buffer* having_buf = buffer_init(128);
2187
2188         if (!from_function) 
2189         core_fields = osrfHashGet(core_meta, "fields");
2190
2191         // ... and if we /are/ building the default list, do that
2192         if ( (_tmp = jsonObjectGetKey(selhash,core_class)) && !_tmp->size ) {
2193                 
2194                 int i = 0;
2195                 char* field;
2196
2197         if (!from_function) {
2198                 osrfStringArray* keys = osrfHashKeys( core_fields );
2199                 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
2200                         if ( strncasecmp( "true", osrfHashGet( osrfHashGet( core_fields, field ), "virtual" ), 4 ) )
2201                                 jsonObjectPush( _tmp, jsonNewObject( field ) );
2202                 }
2203                 osrfStringArrayFree(keys);
2204         }
2205         }
2206
2207         // Now we build the actual select list
2208         if (!from_function) {
2209             int sel_pos = 1;
2210             jsonObject* is_agg = jsonObjectFindPath(selhash, "//aggregate");
2211             first = 1;
2212             gfirst = 1;
2213             jsonIterator* selclass_itr = jsonNewIterator( selhash );
2214             while ( (selclass = jsonIteratorNext( selclass_itr )) ) {
2215
2216                     // round trip through the idl, just to be safe
2217                     idlClass = osrfHashGet( oilsIDL(), selclass_itr->key );
2218                     if (!idlClass) continue;
2219                     char* cname = osrfHashGet(idlClass, "classname");
2220
2221                     // make sure the target relation is in the join tree
2222                     if (strcmp(core_class,cname)) {
2223                             if (!join_hash) continue;
2224
2225                             if (join_hash->type == JSON_STRING) {
2226                                     string = jsonObjectToSimpleString(join_hash);
2227                                     found = strcmp(string,cname) ? NULL : jsonParseString("{\"1\":\"1\"}");
2228                                     free(string);
2229                             } else {
2230                                     found = jsonObjectFindPath(join_hash, "//%s", cname);
2231                             }
2232
2233                             if (!found->size) {
2234                                     jsonObjectFree(found);
2235                                     continue;
2236                             }
2237
2238                             jsonObjectFree(found);
2239                     }
2240
2241                     // stitch together the column list ...
2242                     jsonIterator* select_itr = jsonNewIterator( selclass );
2243                     while ( (selfield = jsonIteratorNext( select_itr )) ) {
2244
2245                             char* __column = NULL;
2246                             char* __alias = NULL;
2247
2248                             // ... if it's a sstring, just toss it on the pile
2249                             if (selfield->type == JSON_STRING) {
2250
2251                                     // again, just to be safe
2252                                     char* _requested_col = jsonObjectToSimpleString(selfield);
2253                                     osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), _requested_col );
2254                                     free(_requested_col);
2255
2256                                     if (!field) continue;
2257                                     __column = strdup(osrfHashGet(field, "name"));
2258
2259                                     if (first) {
2260                                             first = 0;
2261                                     } else {
2262                                             buffer_add(select_buf, ",");
2263                                     }
2264
2265                     if (locale) {
2266                             char* i18n = osrfHashGet(field, "i18n");
2267                                     if (flags & DISABLE_I18N)
2268                             i18n = NULL;
2269
2270                             if ( i18n && !strncasecmp("true", i18n, 4)) {
2271                                 char* pkey = osrfHashGet(idlClass, "primarykey");
2272                                 char* tname = osrfHashGet(idlClass, "tablename");
2273
2274                             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);
2275                         } else {
2276                                             buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, __column, __column);
2277                         }
2278                     } else {
2279                                         buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, __column, __column);
2280                     }
2281
2282                             // ... but it could be an object, in which case we check for a Field Transform
2283                             } else {
2284
2285                                     __column = jsonObjectToSimpleString( jsonObjectGetKeyConst( selfield, "column" ) );
2286
2287                                     // again, just to be safe
2288                                     osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), __column );
2289                                     if (!field) continue;
2290                                     const char* fname = osrfHashGet(field, "name");
2291
2292                                     if (first) {
2293                                             first = 0;
2294                                     } else {
2295                                             buffer_add(select_buf, ",");
2296                                     }
2297
2298                                     if ((tmp_const = jsonObjectGetKeyConst( selfield, "alias" ))) {
2299                                             __alias = jsonObjectToSimpleString( tmp_const );
2300                                     } else {
2301                                             __alias = strdup(__column);
2302                                     }
2303
2304                                     if (jsonObjectGetKeyConst( selfield, "transform" )) {
2305                                             free(__column);
2306                                             __column = searchFieldTransform(cname, field, selfield);
2307                                             buffer_fadd(select_buf, " %s AS \"%s\"", __column, __alias);
2308                                     } else {
2309                         if (locale) {
2310                                     char* i18n = osrfHashGet(field, "i18n");
2311                                         if (flags & DISABLE_I18N)
2312                                 i18n = NULL;
2313     
2314                                     if ( i18n && !strncasecmp("true", i18n, 4)) {
2315                                     char* pkey = osrfHashGet(idlClass, "primarykey");
2316                                     char* tname = osrfHashGet(idlClass, "tablename");
2317
2318                                 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);
2319                             } else {
2320                                                     buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, fname, __alias);
2321                             }
2322                         } else {
2323                                                 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, fname, __alias);
2324                         }
2325                                     }
2326                             }
2327
2328                             if (is_agg->size || (flags & SELECT_DISTINCT)) {
2329
2330                                     if ( !(
2331                             jsonBoolIsTrue( jsonObjectGetKey( selfield, "aggregate" ) ) ||
2332                                 ((int)jsonObjectGetNumber(jsonObjectGetKey( selfield, "aggregate" ))) == 1 // support 1/0 for perl's sake
2333                          )
2334                     ) {
2335                                             if (gfirst) {
2336                                                     gfirst = 0;
2337                                             } else {
2338                                                     buffer_add(group_buf, ",");
2339                                             }
2340
2341                                             buffer_fadd(group_buf, " %d", sel_pos);
2342                                     /*
2343                                     } else if (is_agg = jsonObjectGetKey( selfield, "having" )) {
2344                                             if (gfirst) {
2345                                                     gfirst = 0;
2346                                             } else {
2347                                                     buffer_add(group_buf, ",");
2348                                             }
2349
2350                                             __column = searchFieldTransform(cname, field, selfield);
2351                                             buffer_fadd(group_buf, " %s", __column);
2352                                             __column = searchFieldTransform(cname, field, selfield);
2353                                     */
2354                                     }
2355                             }
2356
2357                             if (__column) free(__column);
2358                             if (__alias) free(__alias);
2359
2360                             sel_pos++;
2361                     }
2362
2363             // jsonIteratorFree(select_itr);
2364             }
2365
2366         // jsonIteratorFree(selclass_itr);
2367
2368             if (is_agg) jsonObjectFree(is_agg);
2369     } else {
2370         buffer_add(select_buf, "*");
2371     }
2372
2373
2374         char* col_list = buffer_release(select_buf);
2375         char* table = NULL;
2376     if (!from_function) table = getSourceDefinition(core_meta);
2377     else table = searchValueTransform(join_hash);
2378
2379         // Put it all together
2380         buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\" ", col_list, table, core_class );
2381         free(col_list);
2382         free(table);
2383
2384     if (!from_function) {
2385             // Now, walk the join tree and add that clause
2386             if ( join_hash ) {
2387                     char* join_clause = searchJOIN( join_hash, core_meta );
2388                     buffer_add(sql_buf, join_clause);
2389                     free(join_clause);
2390             }
2391
2392             if ( search_hash ) {
2393                     buffer_add(sql_buf, " WHERE ");
2394
2395                     // and it's on the the WHERE clause
2396                     char* pred = searchWHERE( search_hash, core_meta, AND_OP_JOIN, ctx );
2397
2398                     if (!pred) {
2399                             if (ctx) {
2400                                 osrfAppSessionStatus(
2401                                         ctx->session,
2402                                         OSRF_STATUS_INTERNALSERVERERROR,
2403                                         "osrfMethodException",
2404                                         ctx->request,
2405                                         "Severe query error in WHERE predicate -- see error log for more details"
2406                                 );
2407                             }
2408                             free(core_class);
2409                             buffer_free(having_buf);
2410                             buffer_free(group_buf);
2411                             buffer_free(order_buf);
2412                             buffer_free(sql_buf);
2413                             if (defaultselhash) jsonObjectFree(defaultselhash);
2414                             return NULL;
2415                     } else {
2416                             buffer_add(sql_buf, pred);
2417                             free(pred);
2418                     }
2419         }
2420
2421             if ( having_hash ) {
2422                     buffer_add(sql_buf, " HAVING ");
2423
2424                     // and it's on the the WHERE clause
2425                     char* pred = searchWHERE( having_hash, core_meta, AND_OP_JOIN, ctx );
2426
2427                     if (!pred) {
2428                             if (ctx) {
2429                                 osrfAppSessionStatus(
2430                                         ctx->session,
2431                                         OSRF_STATUS_INTERNALSERVERERROR,
2432                                         "osrfMethodException",
2433                                         ctx->request,
2434                                         "Severe query error in HAVING predicate -- see error log for more details"
2435                                 );
2436                             }
2437                             free(core_class);
2438                             buffer_free(having_buf);
2439                             buffer_free(group_buf);
2440                             buffer_free(order_buf);
2441                             buffer_free(sql_buf);
2442                             if (defaultselhash) jsonObjectFree(defaultselhash);
2443                             return NULL;
2444                     } else {
2445                             buffer_add(sql_buf, pred);
2446                             free(pred);
2447                     }
2448             }
2449
2450             first = 1;
2451             jsonIterator* class_itr = jsonNewIterator( order_hash );
2452             while ( (snode = jsonIteratorNext( class_itr )) ) {
2453
2454                     if (!jsonObjectGetKeyConst(selhash,class_itr->key))
2455                             continue;
2456
2457                     if ( snode->type == JSON_HASH ) {
2458
2459                         jsonIterator* order_itr = jsonNewIterator( snode );
2460                             while ( (onode = jsonIteratorNext( order_itr )) ) {
2461
2462                                     if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
2463                                             continue;
2464
2465                                     char* direction = NULL;
2466                                     if ( onode->type == JSON_HASH ) {
2467                                             if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
2468                                                     string = searchFieldTransform(
2469                                                             class_itr->key,
2470                                                             oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
2471                                                             onode
2472                                                     );
2473                                             } else {
2474                                                     growing_buffer* field_buf = buffer_init(16);
2475                                                     buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
2476                                                     string = buffer_release(field_buf);
2477                                             }
2478
2479                                             if ( (tmp_const = jsonObjectGetKeyConst( onode, "direction" )) ) {
2480                                                     direction = jsonObjectToSimpleString(tmp_const);
2481                                                     if (!strncasecmp(direction, "d", 1)) {
2482                                                             free(direction);
2483                                                             direction = " DESC";
2484                                                     } else {
2485                                                             free(direction);
2486                                                             direction = " ASC";
2487                                                     }
2488                                             }
2489
2490                                     } else {
2491                                             string = strdup(order_itr->key);
2492                                             direction = jsonObjectToSimpleString(onode);
2493                                             if (!strncasecmp(direction, "d", 1)) {
2494                                                     free(direction);
2495                                                     direction = " DESC";
2496                                             } else {
2497                                                     free(direction);
2498                                                     direction = " ASC";
2499                                             }
2500                                     }
2501
2502                                     if (first) {
2503                                             first = 0;
2504                                     } else {
2505                                             buffer_add(order_buf, ", ");
2506                                     }
2507
2508                                     buffer_add(order_buf, string);
2509                                     free(string);
2510
2511                                     if (direction) {
2512                                             buffer_add(order_buf, direction);
2513                                     }
2514
2515                             }
2516                 // jsonIteratorFree(order_itr);
2517
2518                     } else if ( snode->type == JSON_ARRAY ) {
2519
2520                         jsonIterator* order_itr = jsonNewIterator( snode );
2521                             while ( (onode = jsonIteratorNext( order_itr )) ) {
2522
2523                                     char* _f = jsonObjectToSimpleString( onode );
2524
2525                                     if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, _f))
2526                                             continue;
2527
2528                                     if (first) {
2529                                             first = 0;
2530                                     } else {
2531                                             buffer_add(order_buf, ", ");
2532                                     }
2533
2534                                     buffer_add(order_buf, _f);
2535                                     free(_f);
2536
2537                             }
2538                 // jsonIteratorFree(order_itr);
2539
2540
2541                     // IT'S THE OOOOOOOOOOOLD STYLE!
2542                     } else {
2543                             osrfLogError(OSRF_LOG_MARK, "%s: Possible SQL injection attempt; direct order by is not allowed", MODULENAME);
2544                             if (ctx) {
2545                                 osrfAppSessionStatus(
2546                                         ctx->session,
2547                                         OSRF_STATUS_INTERNALSERVERERROR,
2548                                         "osrfMethodException",
2549                                         ctx->request,
2550                                         "Severe query error -- see error log for more details"
2551                                 );
2552                             }
2553
2554                             free(core_class);
2555                             buffer_free(having_buf);
2556                             buffer_free(group_buf);
2557                             buffer_free(order_buf);
2558                             buffer_free(sql_buf);
2559                             if (defaultselhash) jsonObjectFree(defaultselhash);
2560                             jsonIteratorFree(class_itr);
2561                             return NULL;
2562                     }
2563
2564             }
2565     }
2566
2567     // jsonIteratorFree(class_itr);
2568
2569         string = buffer_release(group_buf);
2570
2571         if (strlen(string)) {
2572                 buffer_fadd(
2573                         sql_buf,
2574                         " GROUP BY %s",
2575                         string
2576                 );
2577         }
2578
2579         free(string);
2580
2581         string = buffer_release(having_buf);
2582  
2583         if (strlen(string)) {
2584                 buffer_fadd(
2585                         sql_buf,
2586                         " HAVING %s",
2587                         string
2588                 );
2589         }
2590
2591         free(string);
2592
2593         string = buffer_release(order_buf);
2594
2595         if (strlen(string)) {
2596                 buffer_fadd(
2597                         sql_buf,
2598                         " ORDER BY %s",
2599                         string
2600                 );
2601         }
2602
2603         free(string);
2604
2605         if ( limit ){
2606                 string = jsonObjectToSimpleString(limit);
2607                 buffer_fadd( sql_buf, " LIMIT %d", atoi(string) );
2608                 free(string);
2609         }
2610
2611         if (offset) {
2612                 string = jsonObjectToSimpleString(offset);
2613                 buffer_fadd( sql_buf, " OFFSET %d", atoi(string) );
2614                 free(string);
2615         }
2616
2617         if (!(flags & SUBSELECT)) buffer_add(sql_buf, ";");
2618
2619         free(core_class);
2620         if (defaultselhash) jsonObjectFree(defaultselhash);
2621
2622         return buffer_release(sql_buf);
2623
2624 }
2625
2626 static char* buildSELECT ( jsonObject* search_hash, jsonObject* order_hash, osrfHash* meta, osrfMethodContext* ctx ) {
2627
2628         const char* locale = osrf_message_get_last_locale();
2629
2630         osrfHash* fields = osrfHashGet(meta, "fields");
2631         char* core_class = osrfHashGet(meta, "classname");
2632
2633         const jsonObject* join_hash = jsonObjectGetKeyConst( order_hash, "join" );
2634
2635         jsonObject* node = NULL;
2636         jsonObject* snode = NULL;
2637         jsonObject* onode = NULL;
2638         const jsonObject* _tmp = NULL;
2639         jsonObject* selhash = NULL;
2640         jsonObject* defaultselhash = NULL;
2641
2642         growing_buffer* sql_buf = buffer_init(128);
2643         growing_buffer* select_buf = buffer_init(128);
2644
2645         if ( !(selhash = jsonObjectGetKey( order_hash, "select" )) ) {
2646                 defaultselhash = jsonNewObjectType(JSON_HASH);
2647                 selhash = defaultselhash;
2648         }
2649         
2650         if ( !jsonObjectGetKeyConst(selhash,core_class) ) {
2651                 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2652                 jsonObject* flist = jsonObjectGetKey( selhash, core_class );
2653                 
2654                 int i = 0;
2655                 char* field;
2656
2657                 osrfStringArray* keys = osrfHashKeys( fields );
2658                 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
2659                         if ( strcasecmp( "true", osrfHashGet( osrfHashGet( fields, field ), "virtual" ) ) )
2660                                 jsonObjectPush( flist, jsonNewObject( field ) );
2661                 }
2662                 osrfStringArrayFree(keys);
2663         }
2664
2665         int first = 1;
2666         jsonIterator* class_itr = jsonNewIterator( selhash );
2667         while ( (snode = jsonIteratorNext( class_itr )) ) {
2668
2669                 osrfHash* idlClass = osrfHashGet( oilsIDL(), class_itr->key );
2670                 if (!idlClass) continue;
2671                 char* cname = osrfHashGet(idlClass, "classname");
2672
2673                 if (strcmp(core_class,class_itr->key)) {
2674                         if (!join_hash) continue;
2675
2676                         jsonObject* found =  jsonObjectFindPath(join_hash, "//%s", class_itr->key);
2677                         if (!found->size) {
2678                                 jsonObjectFree(found);
2679                                 continue;
2680                         }
2681
2682                         jsonObjectFree(found);
2683                 }
2684
2685                 jsonIterator* select_itr = jsonNewIterator( snode );
2686                 while ( (node = jsonIteratorNext( select_itr )) ) {
2687                         char* item_str = jsonObjectToSimpleString(node);
2688                         osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), item_str );
2689                         free(item_str);
2690                         char* fname = osrfHashGet(field, "name");
2691
2692                         if (!field) continue;
2693
2694                         if (first) {
2695                                 first = 0;
2696                         } else {
2697                                 buffer_add(select_buf, ",");
2698                         }
2699
2700             if (locale) {
2701                         char* i18n = osrfHashGet(field, "i18n");
2702                             if ( !(
2703                         jsonBoolIsTrue( jsonObjectGetKey( order_hash, "no_i18n" ) ) ||
2704                         ((int)jsonObjectGetNumber(jsonObjectGetKey( order_hash, "no_i18n" ))) == 1 // support 1/0 for perl's sake
2705                      )
2706                 ) i18n = NULL;
2707
2708                         if ( i18n && !strncasecmp("true", i18n, 4)) {
2709                         char* pkey = osrfHashGet(idlClass, "primarykey");
2710                         char* tname = osrfHashGet(idlClass, "tablename");
2711
2712                     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);
2713                 } else {
2714                                 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
2715                 }
2716             } else {
2717                             buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
2718             }
2719                 }
2720
2721         jsonIteratorFree(select_itr);
2722         }
2723
2724     jsonIteratorFree(class_itr);
2725
2726         char* col_list = buffer_release(select_buf);
2727         char* table = getSourceDefinition(meta);
2728
2729         buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\"", col_list, table, core_class );
2730         free(col_list);
2731         free(table);
2732
2733         if ( join_hash ) {
2734                 char* join_clause = searchJOIN( join_hash, meta );
2735                 buffer_fadd(sql_buf, " %s", join_clause);
2736                 free(join_clause);
2737         }
2738
2739         char* tmpsql = buffer_data(sql_buf);
2740         osrfLogDebug(OSRF_LOG_MARK, "%s pre-predicate SQL =  %s", MODULENAME, tmpsql);
2741         free(tmpsql);
2742
2743         buffer_add(sql_buf, " WHERE ");
2744
2745         char* pred = searchWHERE( search_hash, meta, AND_OP_JOIN, ctx );
2746         if (!pred) {
2747                 osrfAppSessionStatus(
2748                         ctx->session,
2749                         OSRF_STATUS_INTERNALSERVERERROR,
2750                                 "osrfMethodException",
2751                                 ctx->request,
2752                                 "Severe query error -- see error log for more details"
2753                         );
2754                 buffer_free(sql_buf);
2755                 if(defaultselhash) jsonObjectFree(defaultselhash);
2756                 return NULL;
2757         } else {
2758                 buffer_add(sql_buf, pred);
2759                 free(pred);
2760         }
2761
2762         if (order_hash) {
2763                 char* string = NULL;
2764                 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "order_by" )) ){
2765
2766                         growing_buffer* order_buf = buffer_init(128);
2767
2768                         first = 1;
2769                         jsonIterator* class_itr = jsonNewIterator( _tmp );
2770                         while ( (snode = jsonIteratorNext( class_itr )) ) {
2771
2772                                 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
2773                                         continue;
2774
2775                                 if ( snode->type == JSON_HASH ) {
2776
2777                                         jsonIterator* order_itr = jsonNewIterator( snode );
2778                                         while ( (onode = jsonIteratorNext( order_itr )) ) {
2779
2780                                                 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
2781                                                         continue;
2782
2783                                                 char* direction = NULL;
2784                                                 if ( onode->type == JSON_HASH ) {
2785                                                         if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
2786                                                                 string = searchFieldTransform(
2787                                                                         class_itr->key,
2788                                                                         oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
2789                                                                         onode
2790                                                                 );
2791                                                         } else {
2792                                                                 growing_buffer* field_buf = buffer_init(16);
2793                                                                 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
2794                                                                 string = buffer_release(field_buf);
2795                                                         }
2796
2797                                                         if ( (_tmp = jsonObjectGetKeyConst( onode, "direction" )) ) {
2798                                                                 direction = jsonObjectToSimpleString(_tmp);
2799                                                                 if (!strncasecmp(direction, "d", 1)) {
2800                                                                         free(direction);
2801                                                                         direction = " DESC";
2802                                                                 } else {
2803                                                                         free(direction);
2804                                                                         direction = " ASC";
2805                                                                 }
2806                                                         }
2807
2808                                                 } else {
2809                                                         string = strdup(order_itr->key);
2810                                                         direction = jsonObjectToSimpleString(onode);
2811                                                         if (!strncasecmp(direction, "d", 1)) {
2812                                                                 free(direction);
2813                                                                 direction = " DESC";
2814                                                         } else {
2815                                                                 free(direction);
2816                                                                 direction = " ASC";
2817                                                         }
2818                                                 }
2819
2820                                                 if (first) {
2821                                                         first = 0;
2822                                                 } else {
2823                                                         buffer_add(order_buf, ", ");
2824                                                 }
2825
2826                                                 buffer_add(order_buf, string);
2827                                                 free(string);
2828
2829                                                 if (direction) {
2830                                                         buffer_add(order_buf, direction);
2831                                                 }
2832
2833                                         }
2834
2835                     jsonIteratorFree(order_itr);
2836
2837                                 } else {
2838                                         string = jsonObjectToSimpleString(snode);
2839                                         buffer_add(order_buf, string);
2840                                         free(string);
2841                                         break;
2842                                 }
2843
2844                         }
2845
2846             jsonIteratorFree(class_itr);
2847
2848                         string = buffer_release(order_buf);
2849
2850                         if (strlen(string)) {
2851                                 buffer_fadd(
2852                                         sql_buf,
2853                                         " ORDER BY %s",
2854                                         string
2855                                 );
2856                         }
2857
2858                         free(string);
2859                 }
2860
2861                 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "limit" )) ){
2862                         string = jsonObjectToSimpleString(_tmp);
2863                         buffer_fadd(
2864                                 sql_buf,
2865                                 " LIMIT %d",
2866                                 atoi(string)
2867                         );
2868                         free(string);
2869                 }
2870
2871                 _tmp = jsonObjectGetKeyConst( order_hash, "offset" );
2872                 if (_tmp) {
2873                         string = jsonObjectToSimpleString(_tmp);
2874                         buffer_fadd(
2875                                 sql_buf,
2876                                 " OFFSET %d",
2877                                 atoi(string)
2878                         );
2879                         free(string);
2880                 }
2881         }
2882
2883         if (defaultselhash) jsonObjectFree(defaultselhash);
2884
2885         buffer_add(sql_buf, ";");
2886         return buffer_release(sql_buf);
2887 }
2888
2889 int doJSONSearch ( osrfMethodContext* ctx ) {
2890         OSRF_METHOD_VERIFY_CONTEXT(ctx);
2891         osrfLogDebug(OSRF_LOG_MARK, "Recieved query request");
2892
2893         int err = 0;
2894
2895         // XXX for now...
2896         dbhandle = writehandle;
2897
2898         jsonObject* hash = jsonObjectGetIndex(ctx->params, 0);
2899
2900     int flags = 0;
2901
2902         if (jsonBoolIsTrue(jsonObjectGetKey( hash, "distinct" )))
2903          flags |= SELECT_DISTINCT;
2904
2905         if ( ((int)jsonObjectGetNumber(jsonObjectGetKey( hash, "distinct" ))) == 1 ) // support 1/0 for perl's sake
2906          flags |= SELECT_DISTINCT;
2907
2908         if (jsonBoolIsTrue(jsonObjectGetKey( hash, "no_i18n" )))
2909          flags |= DISABLE_I18N;
2910
2911         if ( ((int)jsonObjectGetNumber(jsonObjectGetKey( hash, "no_i18n" ))) == 1 ) // support 1/0 for perl's sake
2912          flags |= DISABLE_I18N;
2913
2914         osrfLogDebug(OSRF_LOG_MARK, "Building SQL ...");
2915         char* sql = SELECT(
2916                         ctx,
2917                         jsonObjectGetKey( hash, "select" ),
2918                         jsonObjectGetKey( hash, "from" ),
2919                         jsonObjectGetKey( hash, "where" ),
2920                         jsonObjectGetKey( hash, "having" ),
2921                         jsonObjectGetKey( hash, "order_by" ),
2922                         jsonObjectGetKey( hash, "limit" ),
2923                         jsonObjectGetKey( hash, "offset" ),
2924                         flags
2925         );
2926
2927         if (!sql) {
2928                 err = -1;
2929                 return err;
2930         }
2931         
2932         osrfLogDebug(OSRF_LOG_MARK, "%s SQL =  %s", MODULENAME, sql);
2933         dbi_result result = dbi_conn_query(dbhandle, sql);
2934
2935         if(result) {
2936                 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
2937
2938                 if (dbi_result_first_row(result)) {
2939                         /* JSONify the result */
2940                         osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
2941
2942                         do {
2943                                 jsonObject* return_val = oilsMakeJSONFromResult( result );
2944                                 osrfAppRespond( ctx, return_val );
2945                 jsonObjectFree( return_val );
2946                         } while (dbi_result_next_row(result));
2947
2948                 } else {
2949                         osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
2950                 }
2951
2952                 osrfAppRespondComplete( ctx, NULL );
2953
2954                 /* clean up the query */
2955                 dbi_result_free(result); 
2956
2957         } else {
2958                 err = -1;
2959                 osrfLogError(OSRF_LOG_MARK, "%s: Error with query [%s]", MODULENAME, sql);
2960                 osrfAppSessionStatus(
2961                         ctx->session,
2962                         OSRF_STATUS_INTERNALSERVERERROR,
2963                         "osrfMethodException",
2964                         ctx->request,
2965                         "Severe query error -- see error log for more details"
2966                 );
2967         }
2968
2969         free(sql);
2970         return err;
2971 }
2972
2973 static jsonObject* doFieldmapperSearch ( osrfMethodContext* ctx, osrfHash* meta,
2974                 const jsonObject* params, int* err ) {
2975
2976         // XXX for now...
2977         dbhandle = writehandle;
2978
2979         osrfHash* links = osrfHashGet(meta, "links");
2980         osrfHash* fields = osrfHashGet(meta, "fields");
2981         char* core_class = osrfHashGet(meta, "classname");
2982         char* pkey = osrfHashGet(meta, "primarykey");
2983
2984         const jsonObject* _tmp;
2985         jsonObject* obj;
2986         jsonObject* search_hash = jsonObjectGetIndex(params, 0);
2987         jsonObject* order_hash = jsonObjectGetIndex(params, 1);
2988
2989         char* sql = buildSELECT( search_hash, order_hash, meta, ctx );
2990         if (!sql) {
2991                 *err = -1;
2992                 return NULL;
2993         }
2994         
2995         osrfLogDebug(OSRF_LOG_MARK, "%s SQL =  %s", MODULENAME, sql);
2996         dbi_result result = dbi_conn_query(dbhandle, sql);
2997
2998         jsonObject* res_list = jsonNewObjectType(JSON_ARRAY);
2999         if(result) {
3000                 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3001                 osrfHash* dedup = osrfNewHash();
3002
3003                 if (dbi_result_first_row(result)) {
3004                         /* JSONify the result */
3005                         osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3006                         do {
3007                                 obj = oilsMakeFieldmapperFromResult( result, meta );
3008                                 char* pkey_val = oilsFMGetString( obj, pkey );
3009                                 if ( osrfHashGet( dedup, pkey_val ) ) {
3010                                         jsonObjectFree(obj);
3011                                         free(pkey_val);
3012                                 } else {
3013                                         osrfHashSet( dedup, pkey_val, pkey_val );
3014                                         jsonObjectPush(res_list, obj);
3015                                 }
3016                         } while (dbi_result_next_row(result));
3017                 } else {
3018                         osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
3019                 }
3020
3021                 osrfHashFree(dedup);
3022
3023                 /* clean up the query */
3024                 dbi_result_free(result); 
3025
3026         } else {
3027                 osrfLogError(OSRF_LOG_MARK, "%s: Error retrieving %s with query [%s]", MODULENAME, osrfHashGet(meta, "fieldmapper"), sql);
3028                 osrfAppSessionStatus(
3029                         ctx->session,
3030                         OSRF_STATUS_INTERNALSERVERERROR,
3031                         "osrfMethodException",
3032                         ctx->request,
3033                         "Severe query error -- see error log for more details"
3034                 );
3035                 *err = -1;
3036                 free(sql);
3037                 jsonObjectFree(res_list);
3038                 return jsonNULL;
3039
3040         }
3041
3042         free(sql);
3043
3044         if (res_list->size && order_hash) {
3045                 _tmp = jsonObjectGetKeyConst( order_hash, "flesh" );
3046                 if (_tmp) {
3047                         int x = (int)jsonObjectGetNumber(_tmp);
3048                         if (x == -1 || x > max_flesh_depth) x = max_flesh_depth;
3049
3050                         const jsonObject* temp_blob;
3051                         if ((temp_blob = jsonObjectGetKeyConst( order_hash, "flesh_fields" )) && x > 0) {
3052
3053                                 jsonObject* flesh_blob = jsonObjectClone( temp_blob );
3054                                 const jsonObject* flesh_fields = jsonObjectGetKeyConst( flesh_blob, core_class );
3055
3056                                 osrfStringArray* link_fields = NULL;
3057
3058                                 if (flesh_fields) {
3059                                         if (flesh_fields->size == 1) {
3060                                                 char* _t = jsonObjectToSimpleString( jsonObjectGetIndex( flesh_fields, 0 ) );
3061                                                 if (!strcmp(_t,"*")) link_fields = osrfHashKeys( links );
3062                                                 free(_t);
3063                                         }
3064
3065                                         if (!link_fields) {
3066                                                 jsonObject* _f;
3067                                                 link_fields = osrfNewStringArray(1);
3068                                                 jsonIterator* _i = jsonNewIterator( flesh_fields );
3069                                                 while ((_f = jsonIteratorNext( _i ))) {
3070                                                         osrfStringArrayAdd( link_fields, jsonObjectToSimpleString( _f ) );
3071                                                 }
3072                         jsonIteratorFree(_i);
3073                                         }
3074                                 }
3075
3076                                 jsonObject* cur;
3077                                 jsonIterator* itr = jsonNewIterator( res_list );
3078                                 while ((cur = jsonIteratorNext( itr ))) {
3079
3080                                         int i = 0;
3081                                         char* link_field;
3082                                         
3083                                         while ( (link_field = osrfStringArrayGetString(link_fields, i++)) ) {
3084
3085                                                 osrfLogDebug(OSRF_LOG_MARK, "Starting to flesh %s", link_field);
3086
3087                                                 osrfHash* kid_link = osrfHashGet(links, link_field);
3088                                                 if (!kid_link) continue;
3089
3090                                                 osrfHash* field = osrfHashGet(fields, link_field);
3091                                                 if (!field) continue;
3092
3093                                                 osrfHash* value_field = field;
3094
3095                                                 osrfHash* kid_idl = osrfHashGet(oilsIDL(), osrfHashGet(kid_link, "class"));
3096                                                 if (!kid_idl) continue;
3097
3098                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3099                                                         value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3100                                                 }
3101                                                         
3102                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) { // might_have
3103                                                         value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3104                                                 }
3105
3106                                                 osrfStringArray* link_map = osrfHashGet( kid_link, "map" );
3107
3108                                                 if (link_map->size > 0) {
3109                                                         jsonObject* _kid_key = jsonNewObjectType(JSON_ARRAY);
3110                                                         jsonObjectPush(
3111                                                                 _kid_key,
3112                                                                 jsonNewObject( osrfStringArrayGetString( link_map, 0 ) )
3113                                                         );
3114
3115                                                         jsonObjectSetKey(
3116                                                                 flesh_blob,
3117                                                                 osrfHashGet(kid_link, "class"),
3118                                                                 _kid_key
3119                                                         );
3120                                                 };
3121
3122                                                 osrfLogDebug(
3123                                                         OSRF_LOG_MARK,
3124                                                         "Link field: %s, remote class: %s, fkey: %s, reltype: %s",
3125                                                         osrfHashGet(kid_link, "field"),
3126                                                         osrfHashGet(kid_link, "class"),
3127                                                         osrfHashGet(kid_link, "key"),
3128                                                         osrfHashGet(kid_link, "reltype")
3129                                                 );
3130
3131                                                 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
3132                                                 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // search hash
3133                                                 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // order/flesh hash
3134
3135                                                 osrfLogDebug(OSRF_LOG_MARK, "Creating dummy params object...");
3136
3137                                                 char* search_key =
3138                                                 jsonObjectToSimpleString(
3139                                                         jsonObjectGetIndex(
3140                                                                 cur,
3141                                                                 atoi( osrfHashGet(value_field, "array_position") )
3142                                                         )
3143                                                 );
3144
3145                                                 if (!search_key) {
3146                                                         osrfLogDebug(OSRF_LOG_MARK, "Nothing to search for!");
3147                                                         continue;
3148                                                 }
3149                                                         
3150                                                 jsonObjectSetKey(
3151                                                         jsonObjectGetIndex(fake_params, 0),
3152                                                         osrfHashGet(kid_link, "key"),
3153                                                         jsonNewObject( search_key )
3154                                                 );
3155
3156                                                 free(search_key);
3157
3158
3159                                                 jsonObjectSetKey(
3160                                                         jsonObjectGetIndex(fake_params, 1),
3161                                                         "flesh",
3162                                                         jsonNewNumberObject( (double)(x - 1 + link_map->size) )
3163                                                 );
3164
3165                                                 if (flesh_blob)
3166                                                         jsonObjectSetKey( jsonObjectGetIndex(fake_params, 1), "flesh_fields", jsonObjectClone(flesh_blob) );
3167
3168                                                 if (jsonObjectGetKeyConst(order_hash, "order_by")) {
3169                                                         jsonObjectSetKey(
3170                                                                 jsonObjectGetIndex(fake_params, 1),
3171                                                                 "order_by",
3172                                                                 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "order_by"))
3173                                                         );
3174                                                 }
3175
3176                                                 if (jsonObjectGetKeyConst(order_hash, "select")) {
3177                                                         jsonObjectSetKey(
3178                                                                 jsonObjectGetIndex(fake_params, 1),
3179                                                                 "select",
3180                                                                 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "select"))
3181                                                         );
3182                                                 }
3183
3184                                                 jsonObject* kids = doFieldmapperSearch(ctx, kid_idl, fake_params, err);
3185
3186                                                 if(*err) {
3187                                                         jsonObjectFree( fake_params );
3188                                                         osrfStringArrayFree(link_fields);
3189                                                         jsonIteratorFree(itr);
3190                                                         jsonObjectFree(res_list);
3191                                                         jsonObjectFree(flesh_blob);
3192                                                         return jsonNULL;
3193                                                 }
3194
3195                                                 osrfLogDebug(OSRF_LOG_MARK, "Search for %s return %d linked objects", osrfHashGet(kid_link, "class"), kids->size);
3196
3197                                                 jsonObject* X = NULL;
3198                                                 if ( link_map->size > 0 && kids->size > 0 ) {
3199                                                         X = kids;
3200                                                         kids = jsonNewObjectType(JSON_ARRAY);
3201
3202                                                         jsonObject* _k_node;
3203                                                         jsonIterator* _k = jsonNewIterator( X );
3204                                                         while ((_k_node = jsonIteratorNext( _k ))) {
3205                                                                 jsonObjectPush(
3206                                                                         kids,
3207                                                                         jsonObjectClone(
3208                                                                                 jsonObjectGetIndex(
3209                                                                                         _k_node,
3210                                                                                         (unsigned long)atoi(
3211                                                                                                 osrfHashGet(
3212                                                                                                         osrfHashGet(
3213                                                                                                                 osrfHashGet(
3214                                                                                                                         osrfHashGet(
3215                                                                                                                                 oilsIDL(),
3216                                                                                                                                 osrfHashGet(kid_link, "class")
3217                                                                                                                         ),
3218                                                                                                                         "fields"
3219                                                                                                                 ),
3220                                                                                                                 osrfStringArrayGetString( link_map, 0 )
3221                                                                                                         ),
3222                                                                                                         "array_position"
3223                                                                                                 )
3224                                                                                         )
3225                                                                                 )
3226                                                                         )
3227                                                                 );
3228                                                         }
3229                                                         jsonIteratorFree(_k);
3230                                                 }
3231
3232                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_a" )) || !(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) {
3233                                                         osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3234                                                         jsonObjectSetIndex(
3235                                                                 cur,
3236                                                                 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3237                                                                 jsonObjectClone( jsonObjectGetIndex(kids, 0) )
3238                                                         );
3239                                                 }
3240
3241                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3242                                                         osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3243                                                         jsonObjectSetIndex(
3244                                                                 cur,
3245                                                                 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3246                                                                 jsonObjectClone( kids )
3247                                                         );
3248                                                 }
3249
3250                                                 if (X) {
3251                                                         jsonObjectFree(kids);
3252                                                         kids = X;
3253                                                 }
3254
3255                                                 jsonObjectFree( kids );
3256                                                 jsonObjectFree( fake_params );
3257
3258                                                 osrfLogDebug(OSRF_LOG_MARK, "Fleshing of %s complete", osrfHashGet(kid_link, "field"));
3259                                                 osrfLogDebug(OSRF_LOG_MARK, "%s", jsonObjectToJSON(cur));
3260
3261                                         }
3262                                 }
3263                                 jsonObjectFree( flesh_blob );
3264                                 osrfStringArrayFree(link_fields);
3265                                 jsonIteratorFree(itr);
3266                         }
3267                 }
3268         }
3269
3270         return res_list;
3271 }
3272
3273
3274 static jsonObject* doUpdate(osrfMethodContext* ctx, int* err ) {
3275
3276         osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3277 #ifdef PCRUD
3278         jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
3279 #else
3280         jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
3281 #endif
3282
3283         if (!verifyObjectClass(ctx, target)) {
3284                 *err = -1;
3285                 return jsonNULL;
3286         }
3287
3288         if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3289                 osrfAppSessionStatus(
3290                         ctx->session,
3291                         OSRF_STATUS_BADREQUEST,
3292                         "osrfMethodException",
3293                         ctx->request,
3294                         "No active transaction -- required for UPDATE"
3295                 );
3296                 *err = -1;
3297                 return jsonNULL;
3298         }
3299
3300         if (osrfHashGet( meta, "readonly" ) && strncasecmp("true", osrfHashGet( meta, "readonly" ), 4)) {
3301                 osrfAppSessionStatus(
3302                         ctx->session,
3303                         OSRF_STATUS_BADREQUEST,
3304                         "osrfMethodException",
3305                         ctx->request,
3306                         "Cannot UPDATE readonly class"
3307                 );
3308                 *err = -1;
3309                 return jsonNULL;
3310         }
3311
3312         dbhandle = writehandle;
3313
3314         char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
3315
3316         // Set the last_xact_id
3317         int index = oilsIDL_ntop( target->classname, "last_xact_id" );
3318         if (index > -1) {
3319                 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
3320                 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
3321         }       
3322
3323         char* pkey = osrfHashGet(meta, "primarykey");
3324         osrfHash* fields = osrfHashGet(meta, "fields");
3325
3326         char* id = oilsFMGetString( target, pkey );
3327
3328         osrfLogDebug(
3329                 OSRF_LOG_MARK,
3330                 "%s updating %s object with %s = %s",
3331                 MODULENAME,
3332                 osrfHashGet(meta, "fieldmapper"),
3333                 pkey,
3334                 id
3335         );
3336
3337         growing_buffer* sql = buffer_init(128);
3338         buffer_fadd(sql,"UPDATE %s SET", osrfHashGet(meta, "tablename"));
3339
3340         int i = 0;
3341         int first = 1;
3342         char* field_name;
3343         osrfStringArray* field_list = osrfHashKeys( fields );
3344         while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
3345
3346                 osrfHash* field = osrfHashGet( fields, field_name );
3347
3348                 if(!( strcmp( field_name, pkey ) )) continue;
3349                 if(!( strcmp( osrfHashGet(osrfHashGet(fields,field_name), "virtual"), "true" ) )) continue;
3350
3351                 const jsonObject* field_object = oilsFMGetObject( target, field_name );
3352
3353                 char* value;
3354                 if (field_object && field_object->classname) {
3355                         value = oilsFMGetString(
3356                                 field_object,
3357                                 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
3358             );
3359                 } else {
3360                         value = jsonObjectToSimpleString( field_object );
3361                 }
3362
3363                 osrfLogDebug( OSRF_LOG_MARK, "Updating %s object with %s = %s", osrfHashGet(meta, "fieldmapper"), field_name, value);
3364
3365                 if (!field_object || field_object->type == JSON_NULL) {
3366                         if ( !(!( strcmp( osrfHashGet(meta, "classname"), "au" ) ) && !( strcmp( field_name, "passwd" ) )) ) { // arg at the special case!
3367                                 if (first) first = 0;
3368                                 else buffer_add(sql, ",");
3369                                 buffer_fadd( sql, " %s = NULL", field_name );
3370                         }
3371                         
3372                 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
3373                         if (first) first = 0;
3374                         else buffer_add(sql, ",");
3375
3376                         if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
3377                                 buffer_fadd( sql, " %s = %ld", field_name, atol(value) );
3378                         } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
3379                                 buffer_fadd( sql, " %s = %f", field_name, atof(value) );
3380                         }
3381
3382                         osrfLogDebug( OSRF_LOG_MARK, "%s is of type %s", field_name, osrfHashGet(field, "datatype"));
3383
3384                 } else {
3385                         if ( dbi_conn_quote_string(dbhandle, &value) ) {
3386                                 if (first) first = 0;
3387                                 else buffer_add(sql, ",");
3388                                 buffer_fadd( sql, " %s = %s", field_name, value );
3389
3390                         } else {
3391                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
3392                                 osrfAppSessionStatus(
3393                                         ctx->session,
3394                                         OSRF_STATUS_INTERNALSERVERERROR,
3395                                         "osrfMethodException",
3396                                         ctx->request,
3397                                         "Error quoting string -- please see the error log for more details"
3398                                 );
3399                                 free(value);
3400                                 free(id);
3401                                 buffer_free(sql);
3402                                 *err = -1;
3403                                 return jsonNULL;
3404                         }
3405                 }
3406
3407                 free(value);
3408                 
3409         }
3410
3411         jsonObject* obj = jsonParseString(id);
3412
3413         if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
3414                 dbi_conn_quote_string(dbhandle, &id);
3415
3416         buffer_fadd( sql, " WHERE %s = %s;", pkey, id );
3417
3418         char* query = buffer_release(sql);
3419         osrfLogDebug(OSRF_LOG_MARK, "%s: Update SQL [%s]", MODULENAME, query);
3420
3421         dbi_result result = dbi_conn_query(dbhandle, query);
3422         free(query);
3423
3424         if (!result) {
3425                 jsonObjectFree(obj);
3426                 obj = jsonNewObject(NULL);
3427                 osrfLogError(
3428                         OSRF_LOG_MARK,
3429                         "%s ERROR updating %s object with %s = %s",
3430                         MODULENAME,
3431                         osrfHashGet(meta, "fieldmapper"),
3432                         pkey,
3433                         id
3434                 );
3435         }
3436
3437         free(id);
3438
3439         return obj;
3440 }
3441
3442 static jsonObject* doDelete(osrfMethodContext* ctx, int* err ) {
3443
3444         osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3445
3446         if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3447                 osrfAppSessionStatus(
3448                         ctx->session,
3449                         OSRF_STATUS_BADREQUEST,
3450                         "osrfMethodException",
3451                         ctx->request,
3452                         "No active transaction -- required for DELETE"
3453                 );
3454                 *err = -1;
3455                 return jsonNULL;
3456         }
3457
3458         if (osrfHashGet( meta, "readonly" ) && strncasecmp("true", osrfHashGet( meta, "readonly" ), 4)) {
3459                 osrfAppSessionStatus(
3460                         ctx->session,
3461                         OSRF_STATUS_BADREQUEST,
3462                         "osrfMethodException",
3463                         ctx->request,
3464                         "Cannot DELETE readonly class"
3465                 );
3466                 *err = -1;
3467                 return jsonNULL;
3468         }
3469
3470         dbhandle = writehandle;
3471
3472         jsonObject* obj;
3473
3474         char* pkey = osrfHashGet(meta, "primarykey");
3475
3476         int _obj_pos = 0;
3477 #ifdef PCRUD
3478                 _obj_pos = 1;
3479 #endif
3480
3481         char* id;
3482         if (jsonObjectGetIndex(ctx->params, _obj_pos)->classname) {
3483                 if (!verifyObjectClass(ctx, jsonObjectGetIndex( ctx->params, _obj_pos ))) {
3484                         *err = -1;
3485                         return jsonNULL;
3486                 }
3487
3488                 id = oilsFMGetString( jsonObjectGetIndex(ctx->params, _obj_pos), pkey );
3489         } else {
3490 #ifdef PCRUD
3491         if (!verifyObjectPCRUD( ctx, NULL )) {
3492                         *err = -1;
3493                         return jsonNULL;
3494         }
3495 #endif
3496                 id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, _obj_pos));
3497         }
3498
3499         osrfLogDebug(
3500                 OSRF_LOG_MARK,
3501                 "%s deleting %s object with %s = %s",
3502                 MODULENAME,
3503                 osrfHashGet(meta, "fieldmapper"),
3504                 pkey,
3505                 id
3506         );
3507
3508         obj = jsonParseString(id);
3509
3510         if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
3511                 dbi_conn_quote_string(writehandle, &id);
3512
3513         dbi_result result = dbi_conn_queryf(writehandle, "DELETE FROM %s WHERE %s = %s;", osrfHashGet(meta, "tablename"), pkey, id);
3514
3515         if (!result) {
3516                 jsonObjectFree(obj);
3517                 obj = jsonNewObject(NULL);
3518                 osrfLogError(
3519                         OSRF_LOG_MARK,
3520                         "%s ERROR deleting %s object with %s = %s",
3521                         MODULENAME,
3522                         osrfHashGet(meta, "fieldmapper"),
3523                         pkey,
3524                         id
3525                 );
3526         }
3527
3528         free(id);
3529
3530         return obj;
3531
3532 }
3533
3534
3535 static jsonObject* oilsMakeFieldmapperFromResult( dbi_result result, osrfHash* meta) {
3536         if(!(result && meta)) return jsonNULL;
3537
3538         jsonObject* object = jsonNewObject(NULL);
3539         jsonObjectSetClass(object, osrfHashGet(meta, "classname"));
3540
3541         osrfHash* fields = osrfHashGet(meta, "fields");
3542
3543         osrfLogInternal(OSRF_LOG_MARK, "Setting object class to %s ", object->classname);
3544
3545         osrfHash* _f;
3546         time_t _tmp_dt;
3547         char dt_string[256];
3548         struct tm gmdt;
3549
3550         int fmIndex;
3551         int columnIndex = 1;
3552         int attr;
3553         unsigned short type;
3554         const char* columnName;
3555
3556         /* cycle through the column list */
3557         while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
3558
3559                 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
3560
3561                 fmIndex = -1; // reset the position
3562                 
3563                 /* determine the field type and storage attributes */
3564                 type = dbi_result_get_field_type(result, columnName);
3565                 attr = dbi_result_get_field_attribs(result, columnName);
3566
3567                 /* fetch the fieldmapper index */
3568                 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
3569                         char* virt = (char*)osrfHashGet(_f, "virtual");
3570                         char* pos = (char*)osrfHashGet(_f, "array_position");
3571
3572                         if ( !virt || !pos || !(strcmp( virt, "true" )) ) continue;
3573
3574                         fmIndex = atoi( pos );
3575                         osrfLogInternal(OSRF_LOG_MARK, "... Found column at position [%s]...", pos);
3576                 } else {
3577                         continue;
3578                 }
3579
3580                 if (dbi_result_field_is_null(result, columnName)) {
3581                         jsonObjectSetIndex( object, fmIndex, jsonNewObject(NULL) );
3582                 } else {
3583
3584                         switch( type ) {
3585
3586                                 case DBI_TYPE_INTEGER :
3587
3588                                         if( attr & DBI_INTEGER_SIZE8 ) 
3589                                                 jsonObjectSetIndex( object, fmIndex, 
3590                                                         jsonNewNumberObject(dbi_result_get_longlong(result, columnName)));
3591                                         else 
3592                                                 jsonObjectSetIndex( object, fmIndex, 
3593                                                         jsonNewNumberObject(dbi_result_get_int(result, columnName)));
3594
3595                                         break;
3596
3597                                 case DBI_TYPE_DECIMAL :
3598                                         jsonObjectSetIndex( object, fmIndex, 
3599                                                         jsonNewNumberObject(dbi_result_get_double(result, columnName)));
3600                                         break;
3601
3602                                 case DBI_TYPE_STRING :
3603
3604
3605                                         jsonObjectSetIndex(
3606                                                 object,
3607                                                 fmIndex,
3608                                                 jsonNewObject( dbi_result_get_string(result, columnName) )
3609                                         );
3610
3611                                         break;
3612
3613                                 case DBI_TYPE_DATETIME :
3614
3615                                         memset(dt_string, '\0', sizeof(dt_string));
3616                                         memset(&gmdt, '\0', sizeof(gmdt));
3617
3618                                         _tmp_dt = dbi_result_get_datetime(result, columnName);
3619
3620
3621                                         if (!(attr & DBI_DATETIME_DATE)) {
3622                                                 gmtime_r( &_tmp_dt, &gmdt );
3623                                                 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
3624                                         } else if (!(attr & DBI_DATETIME_TIME)) {
3625                                                 localtime_r( &_tmp_dt, &gmdt );
3626                                                 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
3627                                         } else {
3628                                                 localtime_r( &_tmp_dt, &gmdt );
3629                                                 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
3630                                         }
3631
3632                                         jsonObjectSetIndex( object, fmIndex, jsonNewObject(dt_string) );
3633
3634                                         break;
3635
3636                                 case DBI_TYPE_BINARY :
3637                                         osrfLogError( OSRF_LOG_MARK, 
3638                                                 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
3639                         }
3640                 }
3641         }
3642
3643         return object;
3644 }
3645
3646 static jsonObject* oilsMakeJSONFromResult( dbi_result result ) {
3647         if(!result) return jsonNULL;
3648
3649         jsonObject* object = jsonNewObject(NULL);
3650
3651         time_t _tmp_dt;
3652         char dt_string[256];
3653         struct tm gmdt;
3654
3655         int fmIndex;
3656         int columnIndex = 1;
3657         int attr;
3658         unsigned short type;
3659         const char* columnName;
3660
3661         /* cycle through the column list */
3662         while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
3663
3664                 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
3665
3666                 fmIndex = -1; // reset the position
3667                 
3668                 /* determine the field type and storage attributes */
3669                 type = dbi_result_get_field_type(result, columnName);
3670                 attr = dbi_result_get_field_attribs(result, columnName);
3671
3672                 if (dbi_result_field_is_null(result, columnName)) {
3673                         jsonObjectSetKey( object, columnName, jsonNewObject(NULL) );
3674                 } else {
3675
3676                         switch( type ) {
3677
3678                                 case DBI_TYPE_INTEGER :
3679
3680                                         if( attr & DBI_INTEGER_SIZE8 ) 
3681                                                 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_longlong(result, columnName)) );
3682                                         else 
3683                                                 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_int(result, columnName)) );
3684                                         break;
3685
3686                                 case DBI_TYPE_DECIMAL :
3687                                         jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_double(result, columnName)) );
3688                                         break;
3689
3690                                 case DBI_TYPE_STRING :
3691                                         jsonObjectSetKey( object, columnName, jsonNewObject(dbi_result_get_string(result, columnName)) );
3692                                         break;
3693
3694                                 case DBI_TYPE_DATETIME :
3695
3696                                         memset(dt_string, '\0', sizeof(dt_string));
3697                                         memset(&gmdt, '\0', sizeof(gmdt));
3698
3699                                         _tmp_dt = dbi_result_get_datetime(result, columnName);
3700
3701
3702                                         if (!(attr & DBI_DATETIME_DATE)) {
3703                                                 gmtime_r( &_tmp_dt, &gmdt );
3704                                                 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
3705                                         } else if (!(attr & DBI_DATETIME_TIME)) {
3706                                                 localtime_r( &_tmp_dt, &gmdt );
3707                                                 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
3708                                         } else {
3709                                                 localtime_r( &_tmp_dt, &gmdt );
3710                                                 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
3711                                         }
3712
3713                                         jsonObjectSetKey( object, columnName, jsonNewObject(dt_string) );
3714                                         break;
3715
3716                                 case DBI_TYPE_BINARY :
3717                                         osrfLogError( OSRF_LOG_MARK, 
3718                                                 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
3719                         }
3720                 }
3721         }
3722
3723         return object;
3724 }
3725