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