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