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