]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/c-apps/oils_cstore.c
In oils_cstore.c: fix autojoin, i.e. the facility for constructing
[working/Evergreen.git] / Open-ILS / src / c-apps / oils_cstore.c
1 #include <ctype.h>
2 #include "opensrf/osrf_application.h"
3 #include "opensrf/osrf_settings.h"
4 #include "opensrf/osrf_message.h"
5 #include "opensrf/utils.h"
6 #include "opensrf/osrf_json.h"
7 #include "opensrf/log.h"
8 #include "openils/oils_utils.h"
9 #include <dbi/dbi.h>
10
11 #include <time.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <unistd.h>
15
16 #ifdef RSTORE
17 #  define MODULENAME "open-ils.reporter-store"
18 #else
19 #  ifdef PCRUD
20 #    define MODULENAME "open-ils.pcrud"
21 #  else
22 #    define MODULENAME "open-ils.cstore"
23 #  endif
24 #endif
25
26 #define SUBSELECT       4
27 #define DISABLE_I18N    2
28 #define SELECT_DISTINCT 1
29 #define AND_OP_JOIN     0
30 #define OR_OP_JOIN      1
31
32 int osrfAppChildInit();
33 int osrfAppInitialize();
34 void osrfAppChildExit();
35
36 static int verifyObjectClass ( osrfMethodContext*, const jsonObject* );
37
38 int beginTransaction ( osrfMethodContext* );
39 int commitTransaction ( osrfMethodContext* );
40 int rollbackTransaction ( osrfMethodContext* );
41
42 int setSavepoint ( osrfMethodContext* );
43 int releaseSavepoint ( osrfMethodContext* );
44 int rollbackSavepoint ( osrfMethodContext* );
45
46 int doJSONSearch ( osrfMethodContext* );
47
48 int dispatchCRUDMethod ( osrfMethodContext* );
49 static jsonObject* doCreate ( osrfMethodContext*, int* );
50 static jsonObject* doRetrieve ( osrfMethodContext*, int* );
51 static jsonObject* doUpdate ( osrfMethodContext*, int* );
52 static jsonObject* doDelete ( osrfMethodContext*, int* );
53 static jsonObject* doFieldmapperSearch ( osrfMethodContext*, osrfHash*,
54         const jsonObject*, int* );
55 static jsonObject* oilsMakeFieldmapperFromResult( dbi_result, osrfHash* );
56 static jsonObject* oilsMakeJSONFromResult( dbi_result );
57
58 static char* searchSimplePredicate ( const char* op, const char* class, 
59                                 osrfHash* field, const jsonObject* node );
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*, const jsonObject*, const char* );
63 static char* searchBETWEENPredicate ( const char*, osrfHash*, const jsonObject* );
64 static char* searchINPredicate ( const char*, osrfHash*,
65                                                                  jsonObject*, const char*, osrfMethodContext* );
66 static char* searchPredicate ( const char*, osrfHash*, jsonObject*, osrfMethodContext* );
67 static char* searchJOIN ( const jsonObject*, osrfHash* );
68 static char* searchWHERE ( const jsonObject*, osrfHash*, int, osrfMethodContext* );
69 static char* buildSELECT ( jsonObject*, jsonObject*, osrfHash*, osrfMethodContext* );
70
71 char* SELECT ( osrfMethodContext*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, int );
72
73 void userDataFree( void* );
74 static void sessionDataFree( char*, void* );
75 static char* getSourceDefinition( osrfHash* );
76 static int str_is_true( const char* str );
77 static int obj_is_true( const jsonObject* obj );
78 static const char* json_type( int code );
79 static const char* get_primitive( osrfHash* field );
80 static const char* get_datatype( osrfHash* field );
81 static int is_identifier( const char* s);
82 static int is_good_operator( const char* op );
83
84 #ifdef PCRUD
85 static jsonObject* verifyUserPCRUD( osrfMethodContext* );
86 static int verifyObjectPCRUD( osrfMethodContext*, const jsonObject* );
87 #endif
88
89 static int child_initialized = 0;   /* boolean */
90
91 static dbi_conn writehandle; /* our MASTER db connection */
92 static dbi_conn dbhandle; /* our CURRENT db connection */
93 //static osrfHash * readHandles;
94 static jsonObject* jsonNULL = NULL; // 
95 static int max_flesh_depth = 100;
96
97 /* called when this process is about to exit */
98 void osrfAppChildExit() {
99     osrfLogDebug(OSRF_LOG_MARK, "Child is exiting, disconnecting from database...");
100
101     int same = 0;
102     if (writehandle == dbhandle) same = 1;
103     if (writehandle) {
104         dbi_conn_query(writehandle, "ROLLBACK;");
105         dbi_conn_close(writehandle);
106         writehandle = NULL;
107     }
108     if (dbhandle && !same)
109         dbi_conn_close(dbhandle);
110
111     // XXX add cleanup of readHandles whenever that gets used
112
113     return;
114 }
115
116 int osrfAppInitialize() {
117
118     osrfLogInfo(OSRF_LOG_MARK, "Initializing the CStore Server...");
119     osrfLogInfo(OSRF_LOG_MARK, "Finding XML file...");
120
121     if (!oilsIDLInit( osrf_settings_host_value("/IDL") )) return 1; /* return non-zero to indicate error */
122
123     growing_buffer* method_name = buffer_init(64);
124 #ifndef PCRUD
125     // Generic search thingy
126     buffer_add(method_name, MODULENAME);
127         buffer_add(method_name, ".json_query");
128         osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
129                                                    "doJSONSearch", "", 1, OSRF_METHOD_STREAMING );
130 #endif
131
132     // first we register all the transaction and savepoint methods
133     buffer_reset(method_name);
134         OSRF_BUFFER_ADD(method_name, MODULENAME);
135         OSRF_BUFFER_ADD(method_name, ".transaction.begin");
136         osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
137                                                    "beginTransaction", "", 0, 0 );
138
139     buffer_reset(method_name);
140         OSRF_BUFFER_ADD(method_name, MODULENAME);
141         OSRF_BUFFER_ADD(method_name, ".transaction.commit");
142         osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
143                                                    "commitTransaction", "", 0, 0 );
144
145     buffer_reset(method_name);
146         OSRF_BUFFER_ADD(method_name, MODULENAME);
147         OSRF_BUFFER_ADD(method_name, ".transaction.rollback");
148         osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
149                                                    "rollbackTransaction", "", 0, 0 );
150
151     buffer_reset(method_name);
152         OSRF_BUFFER_ADD(method_name, MODULENAME);
153         OSRF_BUFFER_ADD(method_name, ".savepoint.set");
154         osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
155                                                    "setSavepoint", "", 1, 0 );
156
157     buffer_reset(method_name);
158         OSRF_BUFFER_ADD(method_name, MODULENAME);
159         OSRF_BUFFER_ADD(method_name, ".savepoint.release");
160         osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
161                                                    "releaseSavepoint", "", 1, 0 );
162
163     buffer_reset(method_name);
164         OSRF_BUFFER_ADD(method_name, MODULENAME);
165         OSRF_BUFFER_ADD(method_name, ".savepoint.rollback");
166         osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
167                                                    "rollbackSavepoint", "", 1, 0 );
168
169     buffer_free(method_name);
170
171         static const char* global_method[] = {
172                 "create",
173                 "retrieve",
174                 "update",
175                 "delete",
176                 "search",
177                 "id_list"
178         };
179         const int global_method_count
180                 = sizeof( global_method ) / sizeof ( global_method[0] );
181         
182     int c_index = 0; 
183     char* classname;
184     osrfStringArray* classes = osrfHashKeys( oilsIDL() );
185     osrfLogDebug(OSRF_LOG_MARK, "%d classes loaded", classes->size );
186     osrfLogDebug(OSRF_LOG_MARK,
187                 "At least %d methods will be generated", classes->size * global_method_count);
188
189     while ( (classname = osrfStringArrayGetString(classes, c_index++)) ) {
190         osrfLogInfo(OSRF_LOG_MARK, "Generating class methods for %s", classname);
191
192         osrfHash* idlClass = osrfHashGet(oilsIDL(), classname);
193
194         if (!osrfStringArrayContains( osrfHashGet(idlClass, "controller"), MODULENAME )) {
195             osrfLogInfo(OSRF_LOG_MARK, "%s is not listed as a controller for %s, moving on", MODULENAME, classname);
196             continue;
197         }
198
199                 if ( str_is_true( osrfHashGet(idlClass, "virtual") ) ) {
200                         osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
201                         continue;
202                 }
203
204         // Look up some other attributes of the current class
205         const char* idlClass_fieldmapper = osrfHashGet(idlClass, "fieldmapper");
206                 const char* readonly = osrfHashGet(idlClass, "readonly");
207 #ifdef PCRUD
208         osrfHash* idlClass_permacrud = osrfHashGet(idlClass, "permacrud");
209 #endif
210
211         int i;
212         for( i = 0; i < global_method_count; ++i ) {
213             const char* method_type = global_method[ i ];
214             osrfLogDebug(OSRF_LOG_MARK,
215                 "Using files to build %s class methods for %s", method_type, classname);
216
217             if (!idlClass_fieldmapper) continue;
218
219 #ifdef PCRUD
220             if (!idlClass_permacrud) continue;
221
222             const char* tmp_method = method_type;
223             if ( *tmp_method == 'i' || *tmp_method == 's') {
224                 tmp_method = "retrieve";
225             }
226             if (!osrfHashGet( idlClass_permacrud, tmp_method )) continue;
227 #endif
228
229             if (    str_is_true( readonly ) &&
230                     ( *method_type == 'c' || *method_type == 'u' || *method_type == 'd')
231                ) continue;
232
233             osrfHash* method_meta = osrfNewHash();
234             osrfHashSet(method_meta, idlClass, "class");
235
236             method_name =  buffer_init(64);
237 #ifdef PCRUD
238             buffer_fadd(method_name, "%s.%s.%s", MODULENAME, method_type, classname);
239 #else
240             char* st_tmp = NULL;
241             char* part = NULL;
242             char* _fm = strdup( idlClass_fieldmapper );
243             part = strtok_r(_fm, ":", &st_tmp);
244
245             buffer_fadd(method_name, "%s.direct.%s", MODULENAME, part);
246
247             while ((part = strtok_r(NULL, ":", &st_tmp))) {
248                                 OSRF_BUFFER_ADD_CHAR(method_name, '.');
249                                 OSRF_BUFFER_ADD(method_name, part);
250             }
251                         OSRF_BUFFER_ADD_CHAR(method_name, '.');
252                         OSRF_BUFFER_ADD(method_name, method_type);
253             free(_fm);
254 #endif
255
256             char* method = buffer_release(method_name);
257
258             osrfHashSet( method_meta, method, "methodname" );
259             osrfHashSet( method_meta, strdup(method_type), "methodtype" );
260
261             int flags = 0;
262             if (*method_type == 'i' || *method_type == 's') {
263                 flags = flags | OSRF_METHOD_STREAMING;
264             }
265
266             osrfAppRegisterExtendedMethod(
267                     MODULENAME,
268                     method,
269                     "dispatchCRUDMethod",
270                     "",
271                     1,
272                     flags,
273                     (void*)method_meta
274                     );
275
276             free(method);
277         }
278     }
279
280     return 0;
281 }
282
283 static char* getSourceDefinition( osrfHash* class ) {
284
285         char* tabledef = osrfHashGet(class, "tablename");
286
287         if (tabledef) {
288                 tabledef = strdup(tabledef);
289         } else {
290                 tabledef = osrfHashGet(class, "source_definition");
291                 if( tabledef ) {
292                         growing_buffer* tablebuf = buffer_init(128);
293                         buffer_fadd( tablebuf, "(%s)", tabledef );
294                         tabledef = buffer_release(tablebuf);
295                 } else {
296                         const char* classname = osrfHashGet( class, "classname" );
297                         if( !classname )
298                                 classname = "???";
299                         osrfLogError(
300                                 OSRF_LOG_MARK,
301                                 "%s ERROR No tablename or source_definition for class \"%s\"",
302                                 MODULENAME,
303                                 classname
304                         );
305                 }
306         }
307
308         return tabledef;
309 }
310
311 /**
312  * Connects to the database 
313  */
314 int osrfAppChildInit() {
315
316     osrfLogDebug(OSRF_LOG_MARK, "Attempting to initialize libdbi...");
317     dbi_initialize(NULL);
318     osrfLogDebug(OSRF_LOG_MARK, "... libdbi initialized.");
319
320     char* driver        = osrf_settings_host_value("/apps/%s/app_settings/driver", MODULENAME);
321     char* user  = osrf_settings_host_value("/apps/%s/app_settings/database/user", MODULENAME);
322     char* host  = osrf_settings_host_value("/apps/%s/app_settings/database/host", MODULENAME);
323     char* port  = osrf_settings_host_value("/apps/%s/app_settings/database/port", MODULENAME);
324     char* db    = osrf_settings_host_value("/apps/%s/app_settings/database/db", MODULENAME);
325     char* pw    = osrf_settings_host_value("/apps/%s/app_settings/database/pw", MODULENAME);
326     char* md    = osrf_settings_host_value("/apps/%s/app_settings/max_query_recursion", MODULENAME);
327
328     osrfLogDebug(OSRF_LOG_MARK, "Attempting to load the database driver [%s]...", driver);
329     writehandle = dbi_conn_new(driver);
330
331     if(!writehandle) {
332         osrfLogError(OSRF_LOG_MARK, "Error loading database driver [%s]", driver);
333         return -1;
334     }
335     osrfLogDebug(OSRF_LOG_MARK, "Database driver [%s] seems OK", driver);
336
337     osrfLogInfo(OSRF_LOG_MARK, "%s connecting to database.  host=%s, "
338             "port=%s, user=%s, pw=%s, db=%s", MODULENAME, host, port, user, pw, db );
339
340     if(host) dbi_conn_set_option(writehandle, "host", host );
341     if(port) dbi_conn_set_option_numeric( writehandle, "port", atoi(port) );
342     if(user) dbi_conn_set_option(writehandle, "username", user);
343     if(pw) dbi_conn_set_option(writehandle, "password", pw );
344     if(db) dbi_conn_set_option(writehandle, "dbname", db );
345
346     if(md) max_flesh_depth = atoi(md);
347     if(max_flesh_depth < 0) max_flesh_depth = 1;
348     if(max_flesh_depth > 1000) max_flesh_depth = 1000;
349
350     free(user);
351     free(host);
352     free(port);
353     free(db);
354     free(pw);
355
356     const char* err;
357     if (dbi_conn_connect(writehandle) < 0) {
358         sleep(1);
359         if (dbi_conn_connect(writehandle) < 0) {
360             dbi_conn_error(writehandle, &err);
361             osrfLogError( OSRF_LOG_MARK, "Error connecting to database: %s", err);
362             return -1;
363         }
364     }
365
366     osrfLogInfo(OSRF_LOG_MARK, "%s successfully connected to the database", MODULENAME);
367
368     unsigned short type;
369     int i = 0; 
370     char* classname;
371     osrfStringArray* classes = osrfHashKeys( oilsIDL() );
372
373     while ( (classname = osrfStringArrayGetString(classes, i++)) ) {
374         osrfHash* class = osrfHashGet( oilsIDL(), classname );
375         osrfHash* fields = osrfHashGet( class, "fields" );
376
377                 if( str_is_true( osrfHashGet(class, "virtual") ) ) {
378                         osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
379                         continue;
380                 }
381
382         char* tabledef = getSourceDefinition(class);
383                 if( !tabledef )
384                         tabledef = strdup( "(null)" );
385
386         growing_buffer* sql_buf = buffer_init(32);
387         buffer_fadd( sql_buf, "SELECT * FROM %s AS x WHERE 1=0;", tabledef );
388
389         free(tabledef);
390
391         char* sql = buffer_release(sql_buf);
392         osrfLogDebug(OSRF_LOG_MARK, "%s Investigatory SQL = %s", MODULENAME, sql);
393
394         dbi_result result = dbi_conn_query(writehandle, sql);
395         free(sql);
396
397         if (result) {
398
399             int columnIndex = 1;
400             const char* columnName;
401             osrfHash* _f;
402             while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
403
404                 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
405
406                 /* fetch the fieldmapper index */
407                 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
408
409                     osrfLogDebug(OSRF_LOG_MARK, "Found [%s] in IDL hash...", (char*)columnName);
410
411                     /* determine the field type and storage attributes */
412                     type = dbi_result_get_field_type(result, columnName);
413
414                     switch( type ) {
415
416                                                 case DBI_TYPE_INTEGER : {
417
418                                                         if ( !osrfHashGet(_f, "primitive") )
419                                                                 osrfHashSet(_f,"number", "primitive");
420
421                                                         int attr = dbi_result_get_field_attribs(result, columnName);
422                                                         if( attr & DBI_INTEGER_SIZE8 ) 
423                                                                 osrfHashSet(_f,"INT8", "datatype");
424                                                         else 
425                                                                 osrfHashSet(_f,"INT", "datatype");
426                                                         break;
427                                                 }
428                         case DBI_TYPE_DECIMAL :
429                             if ( !osrfHashGet(_f, "primitive") )
430                                 osrfHashSet(_f,"number", "primitive");
431
432                             osrfHashSet(_f,"NUMERIC", "datatype");
433                             break;
434
435                         case DBI_TYPE_STRING :
436                             if ( !osrfHashGet(_f, "primitive") )
437                                 osrfHashSet(_f,"string", "primitive");
438                             osrfHashSet(_f,"TEXT", "datatype");
439                             break;
440
441                         case DBI_TYPE_DATETIME :
442                             if ( !osrfHashGet(_f, "primitive") )
443                                 osrfHashSet(_f,"string", "primitive");
444
445                             osrfHashSet(_f,"TIMESTAMP", "datatype");
446                             break;
447
448                         case DBI_TYPE_BINARY :
449                             if ( !osrfHashGet(_f, "primitive") )
450                                 osrfHashSet(_f,"string", "primitive");
451
452                             osrfHashSet(_f,"BYTEA", "datatype");
453                     }
454
455                     osrfLogDebug(
456                             OSRF_LOG_MARK,
457                             "Setting [%s] to primitive [%s] and datatype [%s]...",
458                             (char*)columnName,
459                             osrfHashGet(_f, "primitive"),
460                             osrfHashGet(_f, "datatype")
461                             );
462                 }
463             }
464             dbi_result_free(result);
465         } else {
466             osrfLogDebug(OSRF_LOG_MARK, "No data found for class [%s]...", (char*)classname);
467         }
468     }
469
470     osrfStringArrayFree(classes);
471
472         child_initialized = 1;
473     return 0;
474 }
475
476 /*
477   This function is a sleazy hack intended *only* for testing and
478   debugging.  Any real server process should initialize the 
479   database connection by calling osrfAppChildInit().
480 */
481 void set_cstore_dbi_conn( dbi_conn conn ) {
482         dbhandle = writehandle = conn;
483 }
484
485 void userDataFree( void* blob ) {
486     osrfHashFree( (osrfHash*)blob );
487     return;
488 }
489
490 static void sessionDataFree( char* key, void* item ) {
491     if (!(strcmp(key,"xact_id"))) {
492         if (writehandle)
493             dbi_conn_query(writehandle, "ROLLBACK;");
494         free(item);
495     }
496
497     return;
498 }
499
500 int beginTransaction ( osrfMethodContext* ctx ) {
501         if(osrfMethodVerifyContext( ctx )) {
502                 osrfLogError( OSRF_LOG_MARK,  "Invalid method context" );
503                 return -1;
504         }
505
506 #ifdef PCRUD
507     jsonObject* user = verifyUserPCRUD( ctx );
508     if (!user) return -1;
509     jsonObjectFree(user);
510 #endif
511
512     dbi_result result = dbi_conn_query(writehandle, "START TRANSACTION;");
513     if (!result) {
514         osrfLogError(OSRF_LOG_MARK, "%s: Error starting transaction", MODULENAME );
515         osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error starting transaction" );
516         return -1;
517     } else {
518         jsonObject* ret = jsonNewObject(ctx->session->session_id);
519         osrfAppRespondComplete( ctx, ret );
520         jsonObjectFree(ret);
521
522         if (!ctx->session->userData) {
523             ctx->session->userData = osrfNewHash();
524             osrfHashSetCallback((osrfHash*)ctx->session->userData, &sessionDataFree);
525         }
526
527         osrfHashSet( (osrfHash*)ctx->session->userData, strdup( ctx->session->session_id ), "xact_id" );
528         ctx->session->userDataFree = &userDataFree;
529
530     }
531     return 0;
532 }
533
534 int setSavepoint ( osrfMethodContext* ctx ) {
535         if(osrfMethodVerifyContext( ctx )) {
536                 osrfLogError( OSRF_LOG_MARK,  "Invalid method context" );
537                 return -1;
538         }
539
540     int spNamePos = 0;
541 #ifdef PCRUD
542     spNamePos = 1;
543     jsonObject* user = verifyUserPCRUD( ctx );
544     if (!user) return -1;
545     jsonObjectFree(user);
546 #endif
547
548     if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
549         osrfAppSessionStatus(
550                 ctx->session,
551                 OSRF_STATUS_INTERNALSERVERERROR,
552                 "osrfMethodException",
553                 ctx->request,
554                 "No active transaction -- required for savepoints"
555                 );
556         return -1;
557     }
558
559         const char* spName = jsonObjectGetString(jsonObjectGetIndex(ctx->params, spNamePos));
560
561         dbi_result result = dbi_conn_queryf(writehandle, "SAVEPOINT \"%s\";", spName);
562         if (!result) {
563                 osrfLogError(
564                         OSRF_LOG_MARK,
565                         "%s: Error creating savepoint %s in transaction %s",
566                         MODULENAME,
567                         spName,
568                         osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
569                 );
570                 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, 
571                                 "osrfMethodException", ctx->request, "Error creating savepoint" );
572                 return -1;
573         } else {
574                 jsonObject* ret = jsonNewObject(spName);
575                 osrfAppRespondComplete( ctx, ret );
576                 jsonObjectFree(ret);
577         }
578         return 0;
579 }
580
581 int releaseSavepoint ( osrfMethodContext* ctx ) {
582         if(osrfMethodVerifyContext( ctx )) {
583                 osrfLogError( OSRF_LOG_MARK,  "Invalid method context" );
584                 return -1;
585         }
586
587         int spNamePos = 0;
588 #ifdef PCRUD
589     spNamePos = 1;
590     jsonObject* user = verifyUserPCRUD( ctx );
591     if (!user) return -1;
592     jsonObjectFree(user);
593 #endif
594
595     if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
596         osrfAppSessionStatus(
597                 ctx->session,
598                 OSRF_STATUS_INTERNALSERVERERROR,
599                 "osrfMethodException",
600                 ctx->request,
601                 "No active transaction -- required for savepoints"
602                 );
603         return -1;
604     }
605
606         const char* spName = jsonObjectGetString( jsonObjectGetIndex(ctx->params, spNamePos) );
607
608     dbi_result result = dbi_conn_queryf(writehandle, "RELEASE SAVEPOINT \"%s\";", spName);
609     if (!result) {
610         osrfLogError(
611                 OSRF_LOG_MARK,
612                 "%s: Error releasing savepoint %s in transaction %s",
613                 MODULENAME,
614                 spName,
615                 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
616                 );
617                 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR,
618                                 "osrfMethodException", ctx->request, "Error releasing savepoint" );
619         return -1;
620     } else {
621         jsonObject* ret = jsonNewObject(spName);
622         osrfAppRespondComplete( ctx, ret );
623         jsonObjectFree(ret);
624     }
625     return 0;
626 }
627
628 int rollbackSavepoint ( osrfMethodContext* ctx ) {
629         if(osrfMethodVerifyContext( ctx )) {
630                 osrfLogError( OSRF_LOG_MARK,  "Invalid method context" );
631                 return -1;
632         }
633
634         int spNamePos = 0;
635 #ifdef PCRUD
636     spNamePos = 1;
637     jsonObject* user = verifyUserPCRUD( ctx );
638     if (!user) return -1;
639     jsonObjectFree(user);
640 #endif
641
642     if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
643         osrfAppSessionStatus(
644                 ctx->session,
645                 OSRF_STATUS_INTERNALSERVERERROR,
646                 "osrfMethodException",
647                 ctx->request,
648                 "No active transaction -- required for savepoints"
649                 );
650         return -1;
651     }
652
653         const char* spName = jsonObjectGetString( jsonObjectGetIndex(ctx->params, spNamePos) );
654
655     dbi_result result = dbi_conn_queryf(writehandle, "ROLLBACK TO SAVEPOINT \"%s\";", spName);
656     if (!result) {
657         osrfLogError(
658                 OSRF_LOG_MARK,
659                 "%s: Error rolling back savepoint %s in transaction %s",
660                 MODULENAME,
661                 spName,
662                 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
663                 );
664                 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, 
665                                 "osrfMethodException", ctx->request, "Error rolling back savepoint" );
666         return -1;
667     } else {
668         jsonObject* ret = jsonNewObject(spName);
669         osrfAppRespondComplete( ctx, ret );
670         jsonObjectFree(ret);
671     }
672     return 0;
673 }
674
675 int commitTransaction ( osrfMethodContext* ctx ) {
676         if(osrfMethodVerifyContext( ctx )) {
677                 osrfLogError( OSRF_LOG_MARK,  "Invalid method context" );
678                 return -1;
679         }
680
681 #ifdef PCRUD
682     jsonObject* user = verifyUserPCRUD( ctx );
683     if (!user) return -1;
684     jsonObjectFree(user);
685 #endif
686
687     if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
688         osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to commit" );
689         return -1;
690     }
691
692     dbi_result result = dbi_conn_query(writehandle, "COMMIT;");
693     if (!result) {
694         osrfLogError(OSRF_LOG_MARK, "%s: Error committing transaction", MODULENAME );
695         osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error committing transaction" );
696         return -1;
697     } else {
698         osrfHashRemove(ctx->session->userData, "xact_id");
699         jsonObject* ret = jsonNewObject(ctx->session->session_id);
700         osrfAppRespondComplete( ctx, ret );
701         jsonObjectFree(ret);
702     }
703     return 0;
704 }
705
706 int rollbackTransaction ( osrfMethodContext* ctx ) {
707         if(osrfMethodVerifyContext( ctx )) {
708                 osrfLogError( OSRF_LOG_MARK,  "Invalid method context" );
709                 return -1;
710         }
711
712 #ifdef PCRUD
713     jsonObject* user = verifyUserPCRUD( ctx );
714     if (!user) return -1;
715     jsonObjectFree(user);
716 #endif
717
718     if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
719         osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to roll back" );
720         return -1;
721     }
722
723     dbi_result result = dbi_conn_query(writehandle, "ROLLBACK;");
724     if (!result) {
725         osrfLogError(OSRF_LOG_MARK, "%s: Error rolling back transaction", MODULENAME );
726         osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back transaction" );
727         return -1;
728     } else {
729         osrfHashRemove(ctx->session->userData, "xact_id");
730         jsonObject* ret = jsonNewObject(ctx->session->session_id);
731         osrfAppRespondComplete( ctx, ret );
732         jsonObjectFree(ret);
733     }
734     return 0;
735 }
736
737 int dispatchCRUDMethod ( osrfMethodContext* ctx ) {
738         if(osrfMethodVerifyContext( ctx )) {
739                 osrfLogError( OSRF_LOG_MARK,  "Invalid method context" );
740                 return -1;
741         }
742
743         osrfHash* meta = (osrfHash*) ctx->method->userData;
744     osrfHash* class_obj = osrfHashGet( meta, "class" );
745
746     int err = 0;
747
748     const char* methodtype = osrfHashGet(meta, "methodtype");
749     jsonObject * obj = NULL;
750
751     if (!strcmp(methodtype, "create")) {
752         obj = doCreate(ctx, &err);
753         osrfAppRespondComplete( ctx, obj );
754     }
755     else if (!strcmp(methodtype, "retrieve")) {
756         obj = doRetrieve(ctx, &err);
757         osrfAppRespondComplete( ctx, obj );
758     }
759     else if (!strcmp(methodtype, "update")) {
760         obj = doUpdate(ctx, &err);
761         osrfAppRespondComplete( ctx, obj );
762     }
763     else if (!strcmp(methodtype, "delete")) {
764         obj = doDelete(ctx, &err);
765         osrfAppRespondComplete( ctx, obj );
766     }
767     else if (!strcmp(methodtype, "search")) {
768
769         jsonObject* _p = jsonObjectClone( ctx->params );
770 #ifdef PCRUD
771         jsonObjectFree(_p);
772         _p = jsonParseString("[]");
773         jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 1)));
774         jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 2)));
775 #endif
776
777         obj = doFieldmapperSearch(ctx, class_obj, _p, &err);
778
779         jsonObjectFree(_p);
780         if(err) return err;
781
782         jsonObject* cur;
783         jsonIterator* itr = jsonNewIterator( obj );
784         while ((cur = jsonIteratorNext( itr ))) {
785 #ifdef PCRUD
786             if(!verifyObjectPCRUD(ctx, cur)) continue;
787 #endif
788             osrfAppRespond( ctx, cur );
789         }
790         jsonIteratorFree(itr);
791         osrfAppRespondComplete( ctx, NULL );
792
793     } else if (!strcmp(methodtype, "id_list")) {
794
795         jsonObject* _p = jsonObjectClone( ctx->params );
796 #ifdef PCRUD
797         jsonObjectFree(_p);
798         _p = jsonParseString("[]");
799         jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 1)));
800         jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 2)));
801 #endif
802
803         if (jsonObjectGetIndex( _p, 1 )) {
804             jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "select" );
805             jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "no_i18n" );
806             jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh" );
807             jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh_columns" );
808         } else {
809             jsonObjectSetIndex( _p, 1, jsonNewObjectType(JSON_HASH) );
810         }
811
812                 jsonObjectSetKey( jsonObjectGetIndex( _p, 1 ), "no_i18n", jsonNewBoolObject( 1 ) );
813
814         jsonObjectSetKey(
815             jsonObjectGetIndex( _p, 1 ),
816             "select",
817             jsonParseStringFmt(
818                 "{ \"%s\":[\"%s\"] }",
819                 osrfHashGet( class_obj, "classname" ),
820                 osrfHashGet( class_obj, "primarykey" )
821             )
822         );
823
824         obj = doFieldmapperSearch(ctx, class_obj, _p, &err);
825
826         jsonObjectFree(_p);
827         if(err) return err;
828
829         jsonObject* cur;
830         jsonIterator* itr = jsonNewIterator( obj );
831         while ((cur = jsonIteratorNext( itr ))) {
832 #ifdef PCRUD
833             if(!verifyObjectPCRUD(ctx, cur)) continue;
834 #endif
835             osrfAppRespond(
836                     ctx,
837                     oilsFMGetObject( cur, osrfHashGet( class_obj, "primarykey" ) )
838                     );
839         }
840         jsonIteratorFree(itr);
841         osrfAppRespondComplete( ctx, NULL );
842
843     } else {
844         osrfAppRespondComplete( ctx, obj );
845     }
846
847     jsonObjectFree(obj);
848
849     return err;
850 }
851
852 static int verifyObjectClass ( osrfMethodContext* ctx, const jsonObject* param ) {
853
854     int ret = 1;
855     osrfHash* meta = (osrfHash*) ctx->method->userData;
856     osrfHash* class = osrfHashGet( meta, "class" );
857
858     if (!param->classname || (strcmp( osrfHashGet(class, "classname"), param->classname ))) {
859
860         growing_buffer* msg = buffer_init(128);
861         buffer_fadd(
862                 msg,
863                 "%s: %s method for type %s was passed a %s",
864                 MODULENAME,
865                 osrfHashGet(meta, "methodtype"),
866                 osrfHashGet(class, "classname"),
867                 param->classname
868                 );
869
870         char* m = buffer_release(msg);
871         osrfAppSessionStatus( ctx->session, OSRF_STATUS_BADREQUEST, "osrfMethodException", ctx->request, m );
872
873         free(m);
874
875         return 0;
876     }
877
878 #ifdef PCRUD
879     ret = verifyObjectPCRUD( ctx, param );
880 #endif
881
882     return ret;
883 }
884
885 #ifdef PCRUD
886
887 static jsonObject* verifyUserPCRUD( osrfMethodContext* ctx ) {
888         const char* auth = jsonObjectGetString( jsonObjectGetIndex( ctx->params, 0 ) );
889     jsonObject* auth_object = jsonNewObject(auth);
890     jsonObject* user = oilsUtilsQuickReq("open-ils.auth","open-ils.auth.session.retrieve", auth_object);
891     jsonObjectFree(auth_object);
892
893     if (!user->classname || strcmp(user->classname, "au")) {
894
895         growing_buffer* msg = buffer_init(128);
896         buffer_fadd(
897             msg,
898             "%s: permacrud received a bad auth token: %s",
899             MODULENAME,
900             auth
901         );
902
903         char* m = buffer_release(msg);
904         osrfAppSessionStatus( ctx->session, OSRF_STATUS_UNAUTHORIZED, "osrfMethodException", ctx->request, m );
905
906         free(m);
907         jsonObjectFree(user);
908         user = jsonNULL;
909     }
910
911     return user;
912
913 }
914
915 static int verifyObjectPCRUD (  osrfMethodContext* ctx, const jsonObject* obj ) {
916
917     dbhandle = writehandle;
918
919     osrfHash* meta = (osrfHash*) ctx->method->userData;
920     osrfHash* class = osrfHashGet( meta, "class" );
921     char* method_type = strdup( osrfHashGet(meta, "methodtype") );
922     int fetch = 0;
923
924     if ( ( *method_type == 's' || *method_type == 'i' ) ) {
925         free(method_type);
926         method_type = strdup("retrieve"); // search and id_list are equivelant to retrieve for this
927     } else if ( *method_type == 'u' || *method_type == 'd' ) {
928         fetch = 1; // MUST go to the db for the object for update and delete
929     }
930
931     osrfHash* pcrud = osrfHashGet( osrfHashGet(class, "permacrud"), method_type );
932     free(method_type);
933
934     if (!pcrud) {
935         // No permacrud for this method type on this class
936
937         growing_buffer* msg = buffer_init(128);
938         buffer_fadd(
939             msg,
940             "%s: %s on class %s has no permacrud IDL entry",
941             MODULENAME,
942             osrfHashGet(meta, "methodtype"),
943             osrfHashGet(class, "classname")
944         );
945
946         char* m = buffer_release(msg);
947         osrfAppSessionStatus( ctx->session, OSRF_STATUS_FORBIDDEN, "osrfMethodException", ctx->request, m );
948
949         free(m);
950
951         return 0;
952     }
953
954     jsonObject* user = verifyUserPCRUD( ctx );
955     if (!user) return 0;
956
957     int userid = atoi( oilsFMGetString( user, "id" ) );
958     jsonObjectFree(user);
959
960     osrfStringArray* permission = osrfHashGet(pcrud, "permission");
961     osrfStringArray* local_context = osrfHashGet(pcrud, "local_context");
962     osrfHash* foreign_context = osrfHashGet(pcrud, "foreign_context");
963
964     osrfStringArray* context_org_array = osrfNewStringArray(1);
965
966     int err = 0;
967     char* pkey_value = NULL;
968         if ( str_is_true( osrfHashGet(pcrud, "global_required") ) ) {
969             osrfLogDebug( OSRF_LOG_MARK, "global-level permissions required, fetching top of the org tree" );
970
971         // check for perm at top of org tree
972         jsonObject* _tmp_params = jsonParseString("[{\"parent_ou\":null}]");
973                 jsonObject* _list = doFieldmapperSearch(ctx, osrfHashGet( oilsIDL(), "aou" ), _tmp_params, &err);
974
975         jsonObject* _tree_top = jsonObjectGetIndex(_list, 0);
976
977         if (!_tree_top) {
978             jsonObjectFree(_tmp_params);
979             jsonObjectFree(_list);
980     
981             growing_buffer* msg = buffer_init(128);
982                         OSRF_BUFFER_ADD( msg, MODULENAME );
983                         OSRF_BUFFER_ADD( msg,
984                                 ": Internal error, could not find the top of the org tree (parent_ou = NULL)" );
985     
986             char* m = buffer_release(msg);
987             osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, m );
988             free(m);
989
990             return 0;
991         }
992
993         osrfStringArrayAdd( context_org_array, oilsFMGetString( _tree_top, "id" ) );
994             osrfLogDebug( OSRF_LOG_MARK, "top of the org tree is %s", osrfStringArrayGetString(context_org_array, 0) );
995
996         jsonObjectFree(_tmp_params);
997         jsonObjectFree(_list);
998
999     } else {
1000             osrfLogDebug( OSRF_LOG_MARK, "global-level permissions not required, fetching context org ids" );
1001             char* pkey = osrfHashGet(class, "primarykey");
1002         jsonObject *param = NULL;
1003
1004         if (obj->classname) {
1005             pkey_value = oilsFMGetString( obj, pkey );
1006             if (!fetch) param = jsonObjectClone(obj);
1007                 osrfLogDebug( OSRF_LOG_MARK, "Object supplied, using primary key value of %s", pkey_value );
1008         } else {
1009             pkey_value = jsonObjectToSimpleString( obj );
1010             fetch = 1;
1011                 osrfLogDebug( OSRF_LOG_MARK, "Object not supplied, using primary key value of %s and retrieving from the database", pkey_value );
1012         }
1013
1014         if (fetch) {
1015             jsonObject* _tmp_params = jsonParseStringFmt("[{\"%s\":\"%s\"}]", pkey, pkey_value);
1016                 jsonObject* _list = doFieldmapperSearch(
1017                 ctx,
1018                 class,
1019                 _tmp_params,
1020                 &err
1021             );
1022     
1023             param = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1024     
1025             jsonObjectFree(_tmp_params);
1026             jsonObjectFree(_list);
1027         }
1028
1029         if (!param) {
1030             osrfLogDebug( OSRF_LOG_MARK, "Object not found in the database with primary key %s of %s", pkey, pkey_value );
1031
1032             growing_buffer* msg = buffer_init(128);
1033             buffer_fadd(
1034                 msg,
1035                 "%s: no object found with primary key %s of %s",
1036                 MODULENAME,
1037                 pkey,
1038                 pkey_value
1039             );
1040         
1041             char* m = buffer_release(msg);
1042             osrfAppSessionStatus(
1043                 ctx->session,
1044                 OSRF_STATUS_INTERNALSERVERERROR,
1045                 "osrfMethodException",
1046                 ctx->request,
1047                 m
1048             );
1049         
1050             free(m);
1051             if (pkey_value) free(pkey_value);
1052
1053             return 0;
1054         }
1055
1056         if (local_context->size > 0) {
1057                 osrfLogDebug( OSRF_LOG_MARK, "%d class-local context field(s) specified", local_context->size);
1058             int i = 0;
1059             char* lcontext = NULL;
1060             while ( (lcontext = osrfStringArrayGetString(local_context, i++)) ) {
1061                 osrfStringArrayAdd( context_org_array, oilsFMGetString( param, lcontext ) );
1062                     osrfLogDebug(
1063                     OSRF_LOG_MARK,
1064                     "adding class-local field %s (value: %s) to the context org list",
1065                     lcontext,
1066                     osrfStringArrayGetString(context_org_array, context_org_array->size - 1)
1067                 );
1068             }
1069         }
1070
1071         osrfStringArray* class_list;
1072
1073         if (foreign_context) {
1074             class_list = osrfHashKeys( foreign_context );
1075                 osrfLogDebug( OSRF_LOG_MARK, "%d foreign context classes(s) specified", class_list->size);
1076
1077             if (class_list->size > 0) {
1078     
1079                 int i = 0;
1080                 char* class_name = NULL;
1081                 while ( (class_name = osrfStringArrayGetString(class_list, i++)) ) {
1082                     osrfHash* fcontext = osrfHashGet(foreign_context, class_name);
1083
1084                         osrfLogDebug(
1085                         OSRF_LOG_MARK,
1086                         "%d foreign context fields(s) specified for class %s",
1087                         ((osrfStringArray*)osrfHashGet(fcontext,"context"))->size,
1088                         class_name
1089                     );
1090     
1091                     char* foreign_pkey = osrfHashGet(fcontext, "field");
1092                     char* foreign_pkey_value = oilsFMGetString(param, osrfHashGet(fcontext, "fkey"));
1093
1094                     jsonObject* _tmp_params = jsonParseStringFmt(
1095                         "[{\"%s\":\"%s\"}]",
1096                         foreign_pkey,
1097                         foreign_pkey_value
1098                     );
1099     
1100                         jsonObject* _list = doFieldmapperSearch(
1101                         ctx,
1102                         osrfHashGet( oilsIDL(), class_name ),
1103                         _tmp_params,
1104                         &err
1105                     );
1106
1107                     jsonObject* _fparam = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1108                     jsonObjectFree(_tmp_params);
1109                     jsonObjectFree(_list);
1110  
1111                     osrfStringArray* jump_list = osrfHashGet(fcontext, "jump");
1112
1113                     if (_fparam && jump_list) {
1114                         char* flink = NULL;
1115                         int k = 0;
1116                         while ( (flink = osrfStringArrayGetString(jump_list, k++)) && _fparam ) {
1117                             free(foreign_pkey_value);
1118
1119                             osrfHash* foreign_link_hash = oilsIDLFindPath( "/%s/links/%s", _fparam->classname, flink );
1120
1121                             foreign_pkey_value = oilsFMGetString(_fparam, flink);
1122                             foreign_pkey = osrfHashGet( foreign_link_hash, "key" );
1123
1124                             _tmp_params = jsonParseStringFmt(
1125                                 "[{\"%s\":\"%s\"}]",
1126                                 foreign_pkey,
1127                                 foreign_pkey_value
1128                             );
1129
1130                                 _list = doFieldmapperSearch(
1131                                 ctx,
1132                                 osrfHashGet( oilsIDL(), osrfHashGet( foreign_link_hash, "class" ) ),
1133                                 _tmp_params,
1134                                 &err
1135                             );
1136
1137                             _fparam = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1138                             jsonObjectFree(_tmp_params);
1139                             jsonObjectFree(_list);
1140                         }
1141                     }
1142
1143            
1144                     if (!_fparam) {
1145
1146                         growing_buffer* msg = buffer_init(128);
1147                         buffer_fadd(
1148                             msg,
1149                             "%s: no object found with primary key %s of %s",
1150                             MODULENAME,
1151                             foreign_pkey,
1152                             foreign_pkey_value
1153                         );
1154                 
1155                         char* m = buffer_release(msg);
1156                         osrfAppSessionStatus(
1157                             ctx->session,
1158                             OSRF_STATUS_INTERNALSERVERERROR,
1159                             "osrfMethodException",
1160                             ctx->request,
1161                             m
1162                         );
1163
1164                         free(m);
1165                         osrfStringArrayFree(class_list);
1166                         free(foreign_pkey_value);
1167                         jsonObjectFree(param);
1168
1169                         return 0;
1170                     }
1171         
1172                     free(foreign_pkey_value);
1173     
1174                     int j = 0;
1175                     char* foreign_field = NULL;
1176                     while ( (foreign_field = osrfStringArrayGetString(osrfHashGet(fcontext,"context"), j++)) ) {
1177                         osrfStringArrayAdd( context_org_array, oilsFMGetString( _fparam, foreign_field ) );
1178                             osrfLogDebug(
1179                             OSRF_LOG_MARK,
1180                             "adding foreign class %s field %s (value: %s) to the context org list",
1181                             class_name,
1182                             foreign_field,
1183                             osrfStringArrayGetString(context_org_array, context_org_array->size - 1)
1184                         );
1185                     }
1186
1187                     jsonObjectFree(_fparam);
1188                 }
1189     
1190                 osrfStringArrayFree(class_list);
1191             }
1192         }
1193
1194         jsonObjectFree(param);
1195     }
1196
1197     char* context_org = NULL;
1198     char* perm = NULL;
1199     int OK = 0;
1200
1201     if (permission->size == 0) {
1202             osrfLogDebug( OSRF_LOG_MARK, "No permission specified for this action, passing through" );
1203         OK = 1;
1204     }
1205     
1206     int i = 0;
1207     while ( (perm = osrfStringArrayGetString(permission, i++)) ) {
1208         int j = 0;
1209         while ( (context_org = osrfStringArrayGetString(context_org_array, j++)) ) {
1210             dbi_result result;
1211
1212             if (pkey_value) {
1213                     osrfLogDebug(
1214                     OSRF_LOG_MARK,
1215                     "Checking object permission [%s] for user %d on object %s (class %s) at org %d",
1216                     perm,
1217                     userid,
1218                     pkey_value,
1219                     osrfHashGet(class, "classname"),
1220                     atoi(context_org)
1221                 );
1222
1223                 result = dbi_conn_queryf(
1224                     writehandle,
1225                     "SELECT permission.usr_has_object_perm(%d, '%s', '%s', '%s', %d) AS has_perm;",
1226                     userid,
1227                     perm,
1228                     osrfHashGet(class, "classname"),
1229                     pkey_value,
1230                     atoi(context_org)
1231                 );
1232
1233                 if (result) {
1234                     osrfLogDebug(
1235                         OSRF_LOG_MARK,
1236                         "Recieved a result for object permission [%s] for user %d on object %s (class %s) at org %d",
1237                         perm,
1238                         userid,
1239                         pkey_value,
1240                         osrfHashGet(class, "classname"),
1241                         atoi(context_org)
1242                     );
1243
1244                     if (dbi_result_first_row(result)) {
1245                         jsonObject* return_val = oilsMakeJSONFromResult( result );
1246                                                 const char* has_perm = jsonObjectGetString( jsonObjectGetKeyConst(return_val, "has_perm") );
1247
1248                             osrfLogDebug(
1249                             OSRF_LOG_MARK,
1250                             "Status of object permission [%s] for user %d on object %s (class %s) at org %d is %s",
1251                             perm,
1252                             userid,
1253                             pkey_value,
1254                             osrfHashGet(class, "classname"),
1255                             atoi(context_org),
1256                             has_perm
1257                         );
1258
1259                         if ( *has_perm == 't' ) OK = 1;
1260                         jsonObjectFree(return_val);
1261                     }
1262
1263                     dbi_result_free(result); 
1264                     if (OK) break;
1265                 }
1266             }
1267
1268                 osrfLogDebug( OSRF_LOG_MARK, "Checking non-object permission [%s] for user %d at org %d", perm, userid, atoi(context_org) );
1269             result = dbi_conn_queryf(
1270                 writehandle,
1271                 "SELECT permission.usr_has_perm(%d, '%s', %d) AS has_perm;",
1272                 userid,
1273                 perm,
1274                 atoi(context_org)
1275             );
1276
1277                         if (result) {
1278                                 osrfLogDebug( OSRF_LOG_MARK, "Received a result for permission [%s] for user %d at org %d",
1279                                                 perm, userid, atoi(context_org) );
1280                                 if ( dbi_result_first_row(result) ) {
1281                                         jsonObject* return_val = oilsMakeJSONFromResult( result );
1282                                         const char* has_perm = jsonObjectGetString( jsonObjectGetKeyConst(return_val, "has_perm") );
1283                                         osrfLogDebug( OSRF_LOG_MARK, "Status of permission [%s] for user %d at org %d is [%s]",
1284                                                         perm, userid, atoi(context_org), has_perm );
1285                                         if ( *has_perm == 't' ) OK = 1;
1286                                         jsonObjectFree(return_val);
1287                                 }
1288
1289                                 dbi_result_free(result); 
1290                                 if (OK) break;
1291                         }
1292
1293         }
1294         if (OK) break;
1295     }
1296
1297     if (pkey_value) free(pkey_value);
1298     osrfStringArrayFree(context_org_array);
1299
1300     return OK;
1301 }
1302 #endif
1303
1304
1305 static jsonObject* doCreate(osrfMethodContext* ctx, int* err ) {
1306
1307         osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1308 #ifdef PCRUD
1309         jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
1310         jsonObject* options = jsonObjectGetIndex( ctx->params, 2 );
1311 #else
1312         jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
1313         jsonObject* options = jsonObjectGetIndex( ctx->params, 1 );
1314 #endif
1315
1316         if (!verifyObjectClass(ctx, target)) {
1317                 *err = -1;
1318                 return jsonNULL;
1319         }
1320
1321         osrfLogDebug( OSRF_LOG_MARK, "Object seems to be of the correct type" );
1322
1323         char* trans_id = NULL;
1324         if( ctx->session && ctx->session->userData )
1325                 trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
1326
1327         if ( !trans_id ) {
1328                 osrfLogError( OSRF_LOG_MARK, "No active transaction -- required for CREATE" );
1329
1330                 osrfAppSessionStatus(
1331                         ctx->session,
1332                         OSRF_STATUS_BADREQUEST,
1333                         "osrfMethodException",
1334                         ctx->request,
1335                         "No active transaction -- required for CREATE"
1336                 );
1337                 *err = -1;
1338                 return jsonNULL;
1339         }
1340
1341         // The following test is harmless but redundant.  If a class is
1342         // readonly, we don't register a create method for it.
1343         if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
1344                 osrfAppSessionStatus(
1345                         ctx->session,
1346                         OSRF_STATUS_BADREQUEST,
1347                         "osrfMethodException",
1348                         ctx->request,
1349                         "Cannot INSERT readonly class"
1350                 );
1351                 *err = -1;
1352                 return jsonNULL;
1353         }
1354
1355         // Set the last_xact_id
1356         int index = oilsIDL_ntop( target->classname, "last_xact_id" );
1357         if (index > -1) {
1358                 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
1359                 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
1360         }       
1361
1362         osrfLogDebug( OSRF_LOG_MARK, "There is a transaction running..." );
1363
1364         dbhandle = writehandle;
1365
1366         osrfHash* fields = osrfHashGet(meta, "fields");
1367         char* pkey = osrfHashGet(meta, "primarykey");
1368         char* seq = osrfHashGet(meta, "sequence");
1369
1370         growing_buffer* table_buf = buffer_init(128);
1371         growing_buffer* col_buf = buffer_init(128);
1372         growing_buffer* val_buf = buffer_init(128);
1373
1374         OSRF_BUFFER_ADD(table_buf, "INSERT INTO ");
1375         OSRF_BUFFER_ADD(table_buf, osrfHashGet(meta, "tablename"));
1376         OSRF_BUFFER_ADD_CHAR( col_buf, '(' );
1377         buffer_add(val_buf,"VALUES (");
1378
1379
1380         int i = 0;
1381         int first = 1;
1382         char* field_name;
1383         osrfStringArray* field_list = osrfHashKeys( fields );
1384         while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
1385
1386                 osrfHash* field = osrfHashGet( fields, field_name );
1387
1388                 if( str_is_true( osrfHashGet( field, "virtual" ) ) )
1389                         continue;
1390
1391                 const jsonObject* field_object = oilsFMGetObject( target, field_name );
1392
1393                 char* value;
1394                 if (field_object && field_object->classname) {
1395                         value = oilsFMGetString(
1396                                 field_object,
1397                                 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
1398                         );
1399                 } else {
1400                         value = jsonObjectToSimpleString( field_object );
1401                 }
1402
1403
1404                 if (first) {
1405                         first = 0;
1406                 } else {
1407                         OSRF_BUFFER_ADD_CHAR( col_buf, ',' );
1408                         OSRF_BUFFER_ADD_CHAR( val_buf, ',' );
1409                 }
1410
1411                 buffer_add(col_buf, field_name);
1412
1413                 if (!field_object || field_object->type == JSON_NULL) {
1414                         buffer_add( val_buf, "DEFAULT" );
1415                         
1416                 } else if ( !strcmp(get_primitive( field ), "number") ) {
1417                         const char* numtype = get_datatype( field );
1418                         if ( !strcmp( numtype, "INT8") ) {
1419                                 buffer_fadd( val_buf, "%lld", atoll(value) );
1420                                 
1421                         } else if ( !strcmp( numtype, "INT") ) {
1422                                 buffer_fadd( val_buf, "%d", atoi(value) );
1423                                 
1424                         } else if ( !strcmp( numtype, "NUMERIC") ) {
1425                                 buffer_fadd( val_buf, "%f", atof(value) );
1426                         }
1427                 } else {
1428                         if ( dbi_conn_quote_string(writehandle, &value) ) {
1429                                 OSRF_BUFFER_ADD( val_buf, value );
1430
1431                         } else {
1432                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
1433                                 osrfAppSessionStatus(
1434                                         ctx->session,
1435                                         OSRF_STATUS_INTERNALSERVERERROR,
1436                                         "osrfMethodException",
1437                                         ctx->request,
1438                                         "Error quoting string -- please see the error log for more details"
1439                                 );
1440                                 free(value);
1441                                 buffer_free(table_buf);
1442                                 buffer_free(col_buf);
1443                                 buffer_free(val_buf);
1444                                 *err = -1;
1445                                 return jsonNULL;
1446                         }
1447                 }
1448
1449                 free(value);
1450                 
1451         }
1452
1453
1454         OSRF_BUFFER_ADD_CHAR( col_buf, ')' );
1455         OSRF_BUFFER_ADD_CHAR( val_buf, ')' );
1456
1457         char* table_str = buffer_release(table_buf);
1458         char* col_str   = buffer_release(col_buf);
1459         char* val_str   = buffer_release(val_buf);
1460         growing_buffer* sql = buffer_init(128);
1461         buffer_fadd( sql, "%s %s %s;", table_str, col_str, val_str );
1462         free(table_str);
1463         free(col_str);
1464         free(val_str);
1465
1466         char* query = buffer_release(sql);
1467
1468         osrfLogDebug(OSRF_LOG_MARK, "%s: Insert SQL [%s]", MODULENAME, query);
1469
1470         
1471         dbi_result result = dbi_conn_query(writehandle, query);
1472
1473         jsonObject* obj = NULL;
1474
1475         if (!result) {
1476                 obj = jsonNewObject(NULL);
1477                 osrfLogError(
1478                         OSRF_LOG_MARK,
1479                         "%s ERROR inserting %s object using query [%s]",
1480                         MODULENAME,
1481                         osrfHashGet(meta, "fieldmapper"),
1482                         query
1483                 );
1484                 osrfAppSessionStatus(
1485                         ctx->session,
1486                         OSRF_STATUS_INTERNALSERVERERROR,
1487                         "osrfMethodException",
1488                         ctx->request,
1489                         "INSERT error -- please see the error log for more details"
1490                 );
1491                 *err = -1;
1492         } else {
1493
1494                 char* id = oilsFMGetString(target, pkey);
1495                 if (!id) {
1496                         unsigned long long new_id = dbi_conn_sequence_last(writehandle, seq);
1497                         growing_buffer* _id = buffer_init(10);
1498                         buffer_fadd(_id, "%lld", new_id);
1499                         id = buffer_release(_id);
1500                 }
1501
1502                 // Find quietness specification, if present
1503                 const char* quiet_str = NULL;
1504                 if ( options ) {
1505                         const jsonObject* quiet_obj = jsonObjectGetKeyConst( options, "quiet" );
1506                         if( quiet_obj )
1507                                 quiet_str = jsonObjectGetString( quiet_obj );
1508                 }
1509
1510                 if( str_is_true( quiet_str ) ) {  // if quietness is specified
1511                         obj = jsonNewObject(id);
1512                 }
1513                 else {
1514
1515                         jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
1516                         jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH));
1517
1518                         jsonObjectSetKey(
1519                                 jsonObjectGetIndex(fake_params, 0),
1520                                 pkey,
1521                                 jsonNewObject(id)
1522                         );
1523
1524                         jsonObject* list = doFieldmapperSearch( ctx,meta, fake_params, err);
1525
1526                         if(*err) {
1527                                 jsonObjectFree( fake_params );
1528                                 obj = jsonNULL;
1529                         } else {
1530                                 obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
1531                         }
1532
1533                         jsonObjectFree( list );
1534                         jsonObjectFree( fake_params );
1535                 }
1536
1537                 free(id);
1538         }
1539
1540         free(query);
1541
1542         return obj;
1543
1544 }
1545
1546
1547 static jsonObject* doRetrieve(osrfMethodContext* ctx, int* err ) {
1548
1549     int id_pos = 0;
1550     int order_pos = 1;
1551
1552 #ifdef PCRUD
1553     id_pos = 1;
1554     order_pos = 2;
1555 #endif
1556
1557         osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1558
1559         const char* id = jsonObjectGetString(jsonObjectGetIndex(ctx->params, id_pos));
1560         jsonObject* order_hash = jsonObjectGetIndex(ctx->params, order_pos);
1561
1562         osrfLogDebug(
1563                 OSRF_LOG_MARK,
1564                 "%s retrieving %s object with primary key value of %s",
1565                 MODULENAME,
1566                 osrfHashGet(meta, "fieldmapper"),
1567                 id
1568         );
1569
1570         jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
1571         jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH));
1572
1573         jsonObjectSetKey(
1574                 jsonObjectGetIndex(fake_params, 0),
1575                 osrfHashGet(meta, "primarykey"),
1576                 jsonObjectClone(jsonObjectGetIndex(ctx->params, id_pos))
1577         );
1578
1579
1580         if (order_hash) jsonObjectPush(fake_params, jsonObjectClone(order_hash) );
1581
1582         jsonObject* list = doFieldmapperSearch( ctx,meta, fake_params, err);
1583
1584         if(*err) {
1585                 jsonObjectFree( fake_params );
1586                 return jsonNULL;
1587         }
1588
1589         jsonObject* obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
1590
1591         jsonObjectFree( list );
1592         jsonObjectFree( fake_params );
1593
1594 #ifdef PCRUD
1595         if(!verifyObjectPCRUD(ctx, obj)) {
1596         jsonObjectFree(obj);
1597         *err = -1;
1598
1599         growing_buffer* msg = buffer_init(128);
1600                 OSRF_BUFFER_ADD( msg, MODULENAME );
1601                 OSRF_BUFFER_ADD( msg, ": Insufficient permissions to retrieve object" );
1602
1603         char* m = buffer_release(msg);
1604         osrfAppSessionStatus( ctx->session, OSRF_STATUS_NOTALLOWED, "osrfMethodException", ctx->request, m );
1605
1606         free(m);
1607
1608                 return jsonNULL;
1609         }
1610 #endif
1611
1612         return obj;
1613 }
1614
1615 static char* jsonNumberToDBString ( osrfHash* field, const jsonObject* value ) {
1616         growing_buffer* val_buf = buffer_init(32);
1617         const char* numtype = get_datatype( field );
1618
1619         if ( !strncmp( numtype, "INT", 3 ) ) {
1620                 if (value->type == JSON_NUMBER)
1621                         //buffer_fadd( val_buf, "%ld", (long)jsonObjectGetNumber(value) );
1622                         buffer_fadd( val_buf, jsonObjectGetString( value ) );
1623                 else {
1624                         //const char* val_str = jsonObjectGetString( value );
1625                         //buffer_fadd( val_buf, "%ld", atol(val_str) );
1626                         buffer_fadd( val_buf, jsonObjectGetString( value ) );
1627                 }
1628
1629         } else if ( !strcmp( numtype, "NUMERIC" ) ) {
1630                 if (value->type == JSON_NUMBER)
1631                         //buffer_fadd( val_buf, "%f",  jsonObjectGetNumber(value) );
1632                         buffer_fadd( val_buf, jsonObjectGetString( value ) );
1633                 else {
1634                         //const char* val_str = jsonObjectGetString( value );
1635                         //buffer_fadd( val_buf, "%f", atof(val_str) );
1636                         buffer_fadd( val_buf, jsonObjectGetString( value ) );
1637                 }
1638
1639         } else {
1640                 // Presumably this was really intended ot be a string, so quote it
1641                 char* str = jsonObjectToSimpleString( value );
1642                 if ( dbi_conn_quote_string(dbhandle, &str) ) {
1643                         OSRF_BUFFER_ADD( val_buf, str );
1644                         free(str);
1645                 } else {
1646                         osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, str);
1647                         free(str);
1648                         buffer_free(val_buf);
1649                         return NULL;
1650                 }
1651         }
1652
1653         return buffer_release(val_buf);
1654 }
1655
1656 static char* searchINPredicate (const char* class, osrfHash* field,
1657                 jsonObject* node, const char* op, osrfMethodContext* ctx ) {
1658         growing_buffer* sql_buf = buffer_init(32);
1659         
1660         buffer_fadd(
1661                 sql_buf,
1662                 "\"%s\".%s ",
1663                 class,
1664                 osrfHashGet(field, "name")
1665         );
1666
1667         if (!op) {
1668                 buffer_add(sql_buf, "IN (");
1669         } else if (!(strcasecmp(op,"not in"))) {
1670                 buffer_add(sql_buf, "NOT IN (");
1671         } else {
1672                 buffer_add(sql_buf, "IN (");
1673         }
1674
1675     if (node->type == JSON_HASH) {
1676         // subquery predicate
1677         char* subpred = SELECT(
1678             ctx,
1679             jsonObjectGetKey( node, "select" ),
1680             jsonObjectGetKey( node, "from" ),
1681             jsonObjectGetKey( node, "where" ),
1682             jsonObjectGetKey( node, "having" ),
1683             jsonObjectGetKey( node, "order_by" ),
1684             jsonObjectGetKey( node, "limit" ),
1685             jsonObjectGetKey( node, "offset" ),
1686             SUBSELECT
1687         );
1688
1689                 if( subpred ) {
1690                         buffer_add(sql_buf, subpred);
1691                         free(subpred);
1692                 } else {
1693                         buffer_free( sql_buf );
1694                         return NULL;
1695                 }
1696
1697     } else if (node->type == JSON_ARRAY) {
1698         // literal value list
1699         int in_item_index = 0;
1700         int in_item_first = 1;
1701         const jsonObject* in_item;
1702         while ( (in_item = jsonObjectGetIndex(node, in_item_index++)) ) {
1703
1704                         if (in_item_first)
1705                                 in_item_first = 0;
1706                         else
1707                                 buffer_add(sql_buf, ", ");
1708
1709                         // Sanity check
1710                         if ( in_item->type != JSON_STRING && in_item->type != JSON_NUMBER ) {
1711                                 osrfLogError(OSRF_LOG_MARK, "%s: Expected string or number within IN list; found %s",
1712                                                 MODULENAME, json_type( in_item->type ) );
1713                                                                         buffer_free(sql_buf);
1714                                 return NULL;
1715                         }
1716                         
1717                         // Append the literal value -- quoted if not a number
1718                         if ( JSON_NUMBER == in_item->type ) {
1719                                 char* val = jsonNumberToDBString( field, in_item );
1720                                 OSRF_BUFFER_ADD( sql_buf, val );
1721                                 free(val);
1722
1723                         } else if ( !strcmp( get_primitive( field ), "number") ) {
1724                                 char* val = jsonNumberToDBString( field, in_item );
1725                                 OSRF_BUFFER_ADD( sql_buf, val );
1726                                 free(val);
1727
1728                         } else {
1729                                 char* key_string = jsonObjectToSimpleString(in_item);
1730                                 if ( dbi_conn_quote_string(dbhandle, &key_string) ) {
1731                                         OSRF_BUFFER_ADD( sql_buf, key_string );
1732                                         free(key_string);
1733                                 } else {
1734                                         osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, key_string);
1735                                         free(key_string);
1736                                         buffer_free(sql_buf);
1737                                         return NULL;
1738                                 }
1739                         }
1740                 }
1741
1742                 if( in_item_first ) {
1743                         osrfLogError(OSRF_LOG_MARK, "%s: Empty IN list", MODULENAME );
1744                         buffer_free( sql_buf );
1745                         return NULL;
1746                 }
1747         } else {
1748                 osrfLogError(OSRF_LOG_MARK, "%s: Expected object or array for IN clause; found %s",
1749                         MODULENAME, json_type( node->type ) );
1750                 buffer_free(sql_buf);
1751                 return NULL;
1752         }
1753
1754         OSRF_BUFFER_ADD_CHAR( sql_buf, ')' );
1755
1756         return buffer_release(sql_buf);
1757 }
1758
1759 // Receive a JSON_ARRAY representing a function call.  The first
1760 // entry in the array is the function name.  The rest are parameters.
1761 static char* searchValueTransform( const jsonObject* array ) {
1762         
1763         if( array->size < 1 ) {
1764                 osrfLogError(OSRF_LOG_MARK, "%s: Empty array for value transform", MODULENAME);
1765                 return NULL;
1766         }
1767         
1768         // Get the function name
1769         jsonObject* func_item = jsonObjectGetIndex( array, 0 );
1770         if( func_item->type != JSON_STRING ) {
1771                 osrfLogError(OSRF_LOG_MARK, "%s: Error: expected function name, found %s",
1772                         MODULENAME, json_type( func_item->type ) );
1773                 return NULL;
1774         }
1775         
1776         growing_buffer* sql_buf = buffer_init(32);
1777
1778         OSRF_BUFFER_ADD( sql_buf, jsonObjectGetString( func_item ) );
1779         OSRF_BUFFER_ADD( sql_buf, "( " );
1780         
1781         // Get the parameters
1782         int func_item_index = 1;   // We already grabbed the zeroth entry
1783         while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1784
1785                 // Add a separator comma, if we need one
1786                 if( func_item_index > 2 )
1787                         buffer_add( sql_buf, ", " );
1788
1789                 // Add the current parameter
1790                 if (func_item->type == JSON_NULL) {
1791                         buffer_add( sql_buf, "NULL" );
1792                 } else {
1793                         char* val = jsonObjectToSimpleString(func_item);
1794                         if ( dbi_conn_quote_string(dbhandle, &val) ) {
1795                                 OSRF_BUFFER_ADD( sql_buf, val );
1796                                 free(val);
1797                         } else {
1798                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1799                                 buffer_free(sql_buf);
1800                                 free(val);
1801                                 return NULL;
1802                         }
1803                 }
1804         }
1805
1806         buffer_add( sql_buf, " )" );
1807
1808         return buffer_release(sql_buf);
1809 }
1810
1811 static char* searchFunctionPredicate (const char* class, osrfHash* field,
1812                 const jsonObject* node, const char* op) {
1813
1814         if( ! is_good_operator( op ) ) {
1815                 osrfLogError( OSRF_LOG_MARK, "%s: Invalid operator [%s]", MODULENAME, op );
1816                 return NULL;
1817         }
1818         
1819         char* val = searchValueTransform(node);
1820         if( !val )
1821                 return NULL;
1822         
1823         growing_buffer* sql_buf = buffer_init(32);
1824         buffer_fadd(
1825                 sql_buf,
1826                 "\"%s\".%s %s %s",
1827                 class,
1828                 osrfHashGet(field, "name"),
1829                 op,
1830                 val
1831         );
1832
1833         free(val);
1834
1835         return buffer_release(sql_buf);
1836 }
1837
1838 // class is a class name
1839 // field is a field definition as stored in the IDL
1840 // node comes from the method parameter, and may represent an entry in the SELECT list
1841 static char* searchFieldTransform (const char* class, osrfHash* field, const jsonObject* node) {
1842         growing_buffer* sql_buf = buffer_init(32);
1843
1844         const char* field_transform = jsonObjectGetString( jsonObjectGetKeyConst( node, "transform" ) );
1845         const char* transform_subcolumn = jsonObjectGetString( jsonObjectGetKeyConst( node, "result_field" ) );
1846
1847         if(transform_subcolumn) {
1848                 if( ! is_identifier( transform_subcolumn ) ) {
1849                         osrfLogError( OSRF_LOG_MARK, "%s: Invalid subfield name: \"%s\"\n",
1850                                         MODULENAME, transform_subcolumn );
1851                         buffer_free( sql_buf );
1852                         return NULL;
1853                 }
1854                 OSRF_BUFFER_ADD_CHAR( sql_buf, '(' );    // enclose transform in parentheses
1855         }
1856
1857         if (field_transform) {
1858                 
1859                 if( ! is_identifier( field_transform ) ) {
1860                         osrfLogError( OSRF_LOG_MARK, "%s: Expected function name, found \"%s\"\n",
1861                                         MODULENAME, field_transform );
1862                         buffer_free( sql_buf );
1863                         return NULL;
1864                 }
1865                 
1866                 buffer_fadd( sql_buf, "%s(\"%s\".%s", field_transform, class, osrfHashGet(field, "name"));
1867                 const jsonObject* array = jsonObjectGetKeyConst( node, "params" );
1868
1869                 if (array) {
1870                         if( array->type != JSON_ARRAY ) {
1871                                 osrfLogError( OSRF_LOG_MARK,
1872                                         "%s: Expected JSON_ARRAY for function params; found %s",
1873                                         MODULENAME, json_type( array->type ) );
1874                                 buffer_free( sql_buf );
1875                                 return NULL;
1876                         }
1877                         int func_item_index = 0;
1878                         jsonObject* func_item;
1879                         while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1880
1881                                 char* val = jsonObjectToSimpleString(func_item);
1882
1883                                 if ( !val ) {
1884                                         buffer_add( sql_buf, ",NULL" );
1885                                 } else if ( dbi_conn_quote_string(dbhandle, &val) ) {
1886                                         OSRF_BUFFER_ADD_CHAR( sql_buf, ',' );
1887                                         OSRF_BUFFER_ADD( sql_buf, val );
1888                                 } else {
1889                                         osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1890                                         free(val);
1891                                         buffer_free(sql_buf);
1892                                         return NULL;
1893                         }
1894                                 free(val);
1895                         }
1896                 }
1897
1898                 buffer_add( sql_buf, " )" );
1899
1900         } else {
1901                 buffer_fadd( sql_buf, "\"%s\".%s", class, osrfHashGet(field, "name"));
1902         }
1903
1904         if (transform_subcolumn)
1905                 buffer_fadd( sql_buf, ").\"%s\"", transform_subcolumn );
1906
1907         return buffer_release(sql_buf);
1908 }
1909
1910 static char* searchFieldTransformPredicate (const char* class, osrfHash* field,
1911                 const jsonObject* node, const char* op ) {
1912
1913         if( ! is_good_operator( op ) ) {
1914                 osrfLogError(OSRF_LOG_MARK, "%s: Error: Invalid operator %s", MODULENAME, op);
1915                 return NULL;
1916         }
1917
1918         char* field_transform = searchFieldTransform( class, field, node );
1919         if( ! field_transform )
1920                 return NULL;
1921         char* value = NULL;
1922         int extra_parens = 0;   // boolean
1923
1924         const jsonObject* value_obj = jsonObjectGetKeyConst( node, "value" );
1925         if ( ! value_obj ) {
1926                 value = searchWHERE( node, osrfHashGet( oilsIDL(), class ), AND_OP_JOIN, NULL );
1927                 if( !value ) {
1928                         osrfLogError(OSRF_LOG_MARK, "%s: Error building condition for field transform", MODULENAME);
1929                         free(field_transform);
1930                         return NULL;
1931                 }
1932                 extra_parens = 1;
1933         } else if ( value_obj->type == JSON_ARRAY ) {
1934                 value = searchValueTransform( value_obj );
1935                 if( !value ) {
1936                         osrfLogError(OSRF_LOG_MARK, "%s: Error building value transform for field transform", MODULENAME);
1937                         free( field_transform );
1938                         return NULL;
1939                 }
1940         } else if ( value_obj->type == JSON_HASH ) {
1941                 value = searchWHERE( value_obj, osrfHashGet( oilsIDL(), class ), AND_OP_JOIN, NULL );
1942                 if( !value ) {
1943                         osrfLogError(OSRF_LOG_MARK, "%s: Error building predicate for field transform", MODULENAME);
1944                         free(field_transform);
1945                         return NULL;
1946                 }
1947                 extra_parens = 1;
1948         } else if ( value_obj->type == JSON_NUMBER ) {
1949                 value = jsonNumberToDBString( field, value_obj );
1950         } else if ( value_obj->type == JSON_NULL ) {
1951                 osrfLogError(OSRF_LOG_MARK, "%s: Error building predicate for field transform: null value", MODULENAME);
1952                 free(field_transform);
1953                 return NULL;
1954         } else if ( value_obj->type == JSON_BOOL ) {
1955                 osrfLogError(OSRF_LOG_MARK, "%s: Error building predicate for field transform: boolean value", MODULENAME);
1956                 free(field_transform);
1957                 return NULL;
1958         } else {
1959                 if ( !strcmp( get_primitive( field ), "number") ) {
1960                         value = jsonNumberToDBString( field, value_obj );
1961                 } else {
1962                         value = jsonObjectToSimpleString( value_obj );
1963                         if ( !dbi_conn_quote_string(dbhandle, &value) ) {
1964                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, value);
1965                                 free(value);
1966                                 free(field_transform);
1967                                 return NULL;
1968                         }
1969                 }
1970         }
1971
1972         const char* left_parens  = "";
1973         const char* right_parens = "";
1974
1975         if( extra_parens ) {
1976                 left_parens  = "(";
1977                 right_parens = ")";
1978         }
1979
1980         growing_buffer* sql_buf = buffer_init(32);
1981
1982         buffer_fadd(
1983                 sql_buf,
1984                 "%s%s %s %s %s %s%s",
1985                 left_parens,
1986                 field_transform,
1987                 op,
1988                 left_parens,
1989                 value,
1990                 right_parens,
1991                 right_parens
1992         );
1993
1994         free(value);
1995         free(field_transform);
1996
1997         return buffer_release(sql_buf);
1998 }
1999
2000 static char* searchSimplePredicate (const char* op, const char* class,
2001                 osrfHash* field, const jsonObject* node) {
2002
2003         if( ! is_good_operator( op ) ) {
2004                 osrfLogError( OSRF_LOG_MARK, "%s: Invalid operator [%s]", MODULENAME, op );
2005                 return NULL;
2006         }
2007
2008         char* val = NULL;
2009
2010         // Get the value to which we are comparing the specified column
2011         if (node->type != JSON_NULL) {
2012                 if ( node->type == JSON_NUMBER ) {
2013                         val = jsonNumberToDBString( field, node );
2014                 } else if ( !strcmp( get_primitive( field ), "number" ) ) {
2015                         val = jsonNumberToDBString( field, node );
2016                 } else {
2017                         val = jsonObjectToSimpleString(node);
2018                 }
2019         }
2020
2021         if( val ) {
2022                 if( JSON_NUMBER != node->type && strcmp( get_primitive( field ), "number") ) {
2023                         // Value is not numeric; enclose it in quotes
2024                         if ( !dbi_conn_quote_string( dbhandle, &val ) ) {
2025                                 osrfLogError( OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val );
2026                                 free( val );
2027                                 return NULL;
2028                         }
2029                 }
2030         } else {
2031                 // Compare to a null value
2032                 val = strdup( "NULL" );
2033                 if (strcmp( op, "=" ))
2034                         op = "IS NOT";
2035                 else
2036                         op = "IS";
2037         }
2038
2039         growing_buffer* sql_buf = buffer_init(32);
2040         buffer_fadd( sql_buf, "\"%s\".%s %s %s", class, osrfHashGet(field, "name"), op, val );
2041         char* pred = buffer_release( sql_buf );
2042
2043         free(val);
2044
2045         return pred;
2046 }
2047
2048 static char* searchBETWEENPredicate (const char* class, osrfHash* field, const jsonObject* node) {
2049
2050         const jsonObject* x_node = jsonObjectGetIndex( node, 0 );
2051         const jsonObject* y_node = jsonObjectGetIndex( node, 1 );
2052         
2053         if( NULL == y_node ) {
2054                 osrfLogError( OSRF_LOG_MARK, "%s: Not enough operands for BETWEEN operator", MODULENAME );
2055                 return NULL;
2056         }
2057         else if( NULL != jsonObjectGetIndex( node, 2 ) ) {
2058                 osrfLogError( OSRF_LOG_MARK, "%s: Too many operands for BETWEEN operator", MODULENAME );
2059                 return NULL;
2060         }
2061         
2062         char* x_string;
2063         char* y_string;
2064
2065         if ( !strcmp( get_primitive( field ), "number") ) {
2066                 x_string = jsonNumberToDBString(field, x_node);
2067                 y_string = jsonNumberToDBString(field, y_node);
2068
2069         } else {
2070                 x_string = jsonObjectToSimpleString(x_node);
2071                 y_string = jsonObjectToSimpleString(y_node);
2072                 if ( !(dbi_conn_quote_string(dbhandle, &x_string) && dbi_conn_quote_string(dbhandle, &y_string)) ) {
2073                         osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key strings [%s] and [%s]",
2074                                         MODULENAME, x_string, y_string);
2075                         free(x_string);
2076                         free(y_string);
2077                         return NULL;
2078                 }
2079         }
2080
2081         growing_buffer* sql_buf = buffer_init(32);
2082         buffer_fadd( sql_buf, "%s BETWEEN %s AND %s", osrfHashGet(field, "name"), x_string, y_string );
2083         free(x_string);
2084         free(y_string);
2085
2086         return buffer_release(sql_buf);
2087 }
2088
2089 static char* searchPredicate ( const char* class, osrfHash* field, 
2090                                                            jsonObject* node, osrfMethodContext* ctx ) {
2091
2092         char* pred = NULL;
2093         if (node->type == JSON_ARRAY) { // equality IN search
2094                 pred = searchINPredicate( class, field, node, NULL, ctx );
2095         } else if (node->type == JSON_HASH) { // other search
2096                 jsonIterator* pred_itr = jsonNewIterator( node );
2097                 if( !jsonIteratorHasNext( pred_itr ) ) {
2098                         osrfLogError( OSRF_LOG_MARK, "%s: Empty predicate for field \"%s\"", 
2099                                         MODULENAME, osrfHashGet(field, "name") );
2100                 } else {
2101                         jsonObject* pred_node = jsonIteratorNext( pred_itr );
2102
2103                         // Verify that there are no additional predicates
2104                         if( jsonIteratorHasNext( pred_itr ) ) {
2105                                 osrfLogError( OSRF_LOG_MARK, "%s: Multiple predicates for field \"%s\"", 
2106                                                 MODULENAME, osrfHashGet(field, "name") );
2107                         } else if ( !(strcasecmp( pred_itr->key,"between" )) )
2108                                 pred = searchBETWEENPredicate( class, field, pred_node );
2109                         else if ( !(strcasecmp( pred_itr->key,"in" )) || !(strcasecmp( pred_itr->key,"not in" )) )
2110                                 pred = searchINPredicate( class, field, pred_node, pred_itr->key, ctx );
2111                         else if ( pred_node->type == JSON_ARRAY )
2112                                 pred = searchFunctionPredicate( class, field, pred_node, pred_itr->key );
2113                         else if ( pred_node->type == JSON_HASH )
2114                                 pred = searchFieldTransformPredicate( class, field, pred_node, pred_itr->key );
2115                         else
2116                                 pred = searchSimplePredicate( pred_itr->key, class, field, pred_node );
2117                 }
2118                 jsonIteratorFree(pred_itr);
2119
2120         } else if (node->type == JSON_NULL) { // IS NULL search
2121                 growing_buffer* _p = buffer_init(64);
2122                 buffer_fadd(
2123                         _p,
2124                         "\"%s\".%s IS NULL",
2125                         class,
2126                         osrfHashGet(field, "name")
2127                 );
2128                 pred = buffer_release(_p);
2129         } else { // equality search
2130                 pred = searchSimplePredicate( "=", class, field, node );
2131         }
2132
2133         return pred;
2134
2135 }
2136
2137
2138 /*
2139
2140 join : {
2141         acn : {
2142                 field : record,
2143                 fkey : id
2144                 type : left
2145                 filter_op : or
2146                 filter : { ... },
2147                 join : {
2148                         acp : {
2149                                 field : call_number,
2150                                 fkey : id,
2151                                 filter : { ... },
2152                         },
2153                 },
2154         },
2155         mrd : {
2156                 field : record,
2157                 type : inner
2158                 fkey : id,
2159                 filter : { ... },
2160         }
2161 }
2162
2163 */
2164
2165 static char* searchJOIN ( const jsonObject* join_hash, osrfHash* leftmeta ) {
2166
2167         const jsonObject* working_hash;
2168         jsonObject* freeable_hash = NULL;
2169
2170         if (join_hash->type == JSON_STRING) {
2171                 // create a wrapper around a copy of the original
2172                 const char* _tmp = jsonObjectGetString( join_hash );
2173                 freeable_hash = jsonNewObjectType(JSON_HASH);
2174                 jsonObjectSetKey(freeable_hash, _tmp, NULL);
2175                 working_hash = freeable_hash;
2176         }
2177         else {
2178                 if( join_hash->type != JSON_HASH ) {
2179                         osrfLogError(
2180                                 OSRF_LOG_MARK,
2181                                 "%s: JOIN failed; expected JSON object type not found",
2182                                 MODULENAME
2183                         );
2184                         return NULL;
2185                 }
2186                 working_hash = join_hash;
2187         }
2188
2189         growing_buffer* join_buf = buffer_init(128);
2190         const char* leftclass = osrfHashGet(leftmeta, "classname");
2191
2192         jsonObject* snode = NULL;
2193         jsonIterator* search_itr = jsonNewIterator( working_hash );
2194
2195         while ( (snode = jsonIteratorNext( search_itr )) ) {
2196                 const char* class = search_itr->key;
2197                 osrfHash* idlClass = osrfHashGet( oilsIDL(), class );
2198                 if( !idlClass ) {
2199                         osrfLogError(
2200                                 OSRF_LOG_MARK,
2201                                 "%s: JOIN failed.  No class \"%s\" defined in IDL",
2202                                 MODULENAME,
2203                                 search_itr->key
2204                         );
2205                         jsonIteratorFree( search_itr );
2206                         buffer_free( join_buf );
2207                         if( freeable_hash )
2208                                 jsonObjectFree( freeable_hash );
2209                         return NULL;
2210                 }
2211
2212                 const char* fkey = jsonObjectGetString( jsonObjectGetKeyConst( snode, "fkey" ) );
2213                 const char* field = jsonObjectGetString( jsonObjectGetKeyConst( snode, "field" ) );
2214
2215                 if (field && !fkey) {
2216                         fkey = (const char*)oilsIDLFindPath("/%s/links/%s/key", class, field);
2217                         if (!fkey) {
2218                                 osrfLogError(
2219                                         OSRF_LOG_MARK,
2220                                         "%s: JOIN failed.  No link defined from %s.%s to %s",
2221                                         MODULENAME,
2222                                         class,
2223                                         field,
2224                                         leftclass
2225                                 );
2226                                 buffer_free(join_buf);
2227                                 if(freeable_hash)
2228                                         jsonObjectFree(freeable_hash);
2229                                 jsonIteratorFree(search_itr);
2230                                 return NULL;
2231                         }
2232
2233                 } else if (!field && fkey) {
2234                         field = (const char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, fkey );
2235                         if (!field) {
2236                                 osrfLogError(
2237                                         OSRF_LOG_MARK,
2238                                         "%s: JOIN failed.  No link defined from %s.%s to %s",
2239                                         MODULENAME,
2240                                         leftclass,
2241                                         fkey,
2242                                         class
2243                                 );
2244                                 buffer_free(join_buf);
2245                                 if(freeable_hash)
2246                                         jsonObjectFree(freeable_hash);
2247                                 jsonIteratorFree(search_itr);
2248                                 return NULL;
2249                         }
2250
2251                 } else if (!field && !fkey) {
2252                         osrfHash* _links = oilsIDL_links( leftclass );
2253
2254                         // For each link defined for the left class:
2255                         // see if the link references the joined class
2256                         osrfHashIterator* itr = osrfNewHashIterator( _links );
2257                         osrfHash* curr_link = NULL;
2258                         while( (curr_link = osrfHashIteratorNext( itr ) ) ) {
2259                                 const char* other_class = osrfHashGet( curr_link, "class" );
2260                                 if( other_class && !strcmp( other_class, class ) ) {
2261
2262                                         // In the IDL, the parent class doesn't know then names of the child
2263                                         // columns that are pointing to it, so don't use that end of the link
2264                                         const char* reltype = osrfHashGet( curr_link, "reltype" );
2265                                         if( reltype && strcmp( reltype, "has_many" ) ) {
2266                                                 // Found a link between the classes
2267                                                 fkey = osrfHashIteratorKey( itr );
2268                                                 field = osrfHashGet( curr_link, "key" );
2269                                                 break;
2270                                         }
2271                                 }
2272                         }
2273                         osrfHashIteratorFree( itr );
2274
2275                         if (!field || !fkey) {
2276                                 // Do another such search, with the classes reversed
2277                                 _links = oilsIDL_links( class );
2278
2279                                 // For each link defined for the joined class:
2280                                 // see if the link references the left class
2281                                 osrfHashIterator* itr = osrfNewHashIterator( _links );
2282                                 osrfHash* curr_link = NULL;
2283                                 while( (curr_link = osrfHashIteratorNext( itr ) ) ) {
2284                                         const char* other_class = osrfHashGet( curr_link, "class" );
2285                                         if( other_class && !strcmp( other_class, leftclass ) ) {
2286
2287                                                 // In the IDL, the parent class doesn't know then names of the child
2288                                                 // columns that are pointing to it, so don't use that end of the link
2289                                                 const char* reltype = osrfHashGet( curr_link, "reltype" );
2290                                                 if( reltype && strcmp( reltype, "has_many" ) ) {
2291                                                         // Found a link between the classes
2292                                                         field = osrfHashIteratorKey( itr );
2293                                                         fkey = osrfHashGet( curr_link, "key" );
2294                                                         break;
2295                                                 }
2296                                         }
2297                                 }
2298                                 osrfHashIteratorFree( itr );
2299                         }
2300
2301                         if (!field || !fkey) {
2302                                 osrfLogError(
2303                                         OSRF_LOG_MARK,
2304                                         "%s: JOIN failed.  No link defined between %s and %s",
2305                                         MODULENAME,
2306                                         leftclass,
2307                                         class
2308                                 );
2309                                 buffer_free(join_buf);
2310                                 if(freeable_hash)
2311                                         jsonObjectFree(freeable_hash);
2312                                 jsonIteratorFree(search_itr);
2313                                 return NULL;
2314                         }
2315
2316                 }
2317
2318                 const char* type = jsonObjectGetString( jsonObjectGetKeyConst( snode, "type" ) );
2319                 if (type) {
2320                         if ( !strcasecmp(type,"left") ) {
2321                                 buffer_add(join_buf, " LEFT JOIN");
2322                         } else if ( !strcasecmp(type,"right") ) {
2323                                 buffer_add(join_buf, " RIGHT JOIN");
2324                         } else if ( !strcasecmp(type,"full") ) {
2325                                 buffer_add(join_buf, " FULL JOIN");
2326                         } else {
2327                                 buffer_add(join_buf, " INNER JOIN");
2328                         }
2329                 } else {
2330                         buffer_add(join_buf, " INNER JOIN");
2331                 }
2332
2333                 char* table = getSourceDefinition(idlClass);
2334                 if( !table ) {
2335                         jsonIteratorFree( search_itr );
2336                         buffer_free( join_buf );
2337                         if( freeable_hash )
2338                                 jsonObjectFree( freeable_hash );
2339                         return NULL;
2340                 }
2341
2342                 buffer_fadd(join_buf, " %s AS \"%s\" ON ( \"%s\".%s = \"%s\".%s",
2343                                         table, class, class, field, leftclass, fkey);
2344                 free(table);
2345
2346                 const jsonObject* filter = jsonObjectGetKeyConst( snode, "filter" );
2347                 if (filter) {
2348                         const char* filter_op = jsonObjectGetString( jsonObjectGetKeyConst( snode, "filter_op" ) );
2349                         if ( filter_op && !strcasecmp("or",filter_op) ) {
2350                                 buffer_add( join_buf, " OR " );
2351                         } else {
2352                                 buffer_add( join_buf, " AND " );
2353                         }
2354
2355                         char* jpred = searchWHERE( filter, idlClass, AND_OP_JOIN, NULL );
2356                         if( jpred ) {
2357                                 OSRF_BUFFER_ADD_CHAR( join_buf, ' ' );
2358                                 OSRF_BUFFER_ADD( join_buf, jpred );
2359                                 free(jpred);
2360                         } else {
2361                                 osrfLogError(
2362                                         OSRF_LOG_MARK,
2363                                         "%s: JOIN failed.  Invalid conditional expression.",
2364                                         MODULENAME
2365                                 );
2366                                 jsonIteratorFree( search_itr );
2367                                 buffer_free( join_buf );
2368                                 if( freeable_hash )
2369                                         jsonObjectFree( freeable_hash );
2370                                 return NULL;
2371                         }
2372                 }
2373
2374                 buffer_add(join_buf, " ) ");
2375                 
2376                 const jsonObject* join_filter = jsonObjectGetKeyConst( snode, "join" );
2377                 if (join_filter) {
2378                         char* jpred = searchJOIN( join_filter, idlClass );
2379                         OSRF_BUFFER_ADD_CHAR( join_buf, ' ' );
2380                         OSRF_BUFFER_ADD( join_buf, jpred );
2381                         free(jpred);
2382                 }
2383         }
2384
2385         if(freeable_hash)
2386                 jsonObjectFree(freeable_hash);
2387         jsonIteratorFree(search_itr);
2388
2389         return buffer_release(join_buf);
2390 }
2391
2392 /*
2393
2394 { +class : { -or|-and : { field : { op : value }, ... } ... }, ... }
2395 { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }
2396 [ { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }, ... ]
2397
2398 Generate code to express a set of conditions, as for a WHERE clause.  Parameters:
2399
2400 search_hash is the JSON expression of the conditions.
2401 meta is the class definition from the IDL, for the relevant table.
2402 opjoin_type indicates whether multiple conditions, if present, should be
2403         connected by AND or OR.
2404 osrfMethodContext is loaded with all sorts of stuff, but all we do with it here is
2405         to pass it to other functions -- and all they do with it is to use the session
2406         and request members to send error messages back to the client.
2407
2408 */
2409
2410 static char* searchWHERE ( const jsonObject* search_hash, osrfHash* meta, int opjoin_type, osrfMethodContext* ctx ) {
2411
2412         osrfLogDebug(
2413         OSRF_LOG_MARK,
2414         "%s: Entering searchWHERE; search_hash addr = %p, meta addr = %p, opjoin_type = %d, ctx addr = %p",
2415         MODULENAME,
2416         search_hash,
2417         meta,
2418         opjoin_type,
2419         ctx
2420     );
2421
2422         growing_buffer* sql_buf = buffer_init(128);
2423
2424         jsonObject* node = NULL;
2425
2426         int first = 1;
2427         if ( search_hash->type == JSON_ARRAY ) {
2428                 osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_ARRAY", MODULENAME);
2429                 jsonIterator* search_itr = jsonNewIterator( search_hash );
2430                 if( !jsonIteratorHasNext( search_itr ) ) {
2431                         osrfLogError(
2432                                 OSRF_LOG_MARK,
2433                                 "%s: Invalid predicate structure: empty JSON array",
2434                                 MODULENAME
2435                         );
2436                         jsonIteratorFree( search_itr );
2437                         buffer_free( sql_buf );
2438                         return NULL;
2439                 }
2440
2441                 while ( (node = jsonIteratorNext( search_itr )) ) {
2442             if (first) {
2443                 first = 0;
2444             } else {
2445                 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2446                 else buffer_add(sql_buf, " AND ");
2447             }
2448
2449             char* subpred = searchWHERE( node, meta, opjoin_type, ctx );
2450                         if( subpred ) {
2451                 buffer_fadd(sql_buf, "( %s )", subpred);
2452                 free(subpred);
2453                         } else {
2454                                 jsonIteratorFree( search_itr );
2455                                 buffer_free( sql_buf );
2456                                 return NULL;
2457                         }
2458         }
2459         jsonIteratorFree(search_itr);
2460
2461         } else if ( search_hash->type == JSON_HASH ) {
2462                 osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_HASH", MODULENAME);
2463                 jsonIterator* search_itr = jsonNewIterator( search_hash );
2464                 if( !jsonIteratorHasNext( search_itr ) ) {
2465                         osrfLogError(
2466                                 OSRF_LOG_MARK,
2467                                 "%s: Invalid predicate structure: empty JSON object",
2468                                 MODULENAME
2469                         );
2470                         jsonIteratorFree( search_itr );
2471                         buffer_free( sql_buf );
2472                         return NULL;
2473                 }
2474
2475                 while ( (node = jsonIteratorNext( search_itr )) ) {
2476
2477             if (first) {
2478                 first = 0;
2479             } else {
2480                 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2481                 else buffer_add(sql_buf, " AND ");
2482             }
2483
2484                         if ( '+' == search_itr->key[ 0 ] ) {
2485                                 if ( node->type == JSON_STRING ) {
2486                                         // Intended purpose; to allow reference to a Boolean column
2487
2488                                         // Verify that the class alias is not empty
2489                                         if( '\0' == search_itr->key[ 1 ] ) {
2490                                                 osrfLogError(
2491                                                         OSRF_LOG_MARK,
2492                                                         "%s: Table alias is empty",
2493                                                         MODULENAME
2494                                                 );
2495                                                 jsonIteratorFree( search_itr );
2496                                                 buffer_free( sql_buf );
2497                                                 return NULL;
2498                                         }
2499
2500                                         // Verify that the string looks like an identifier.
2501                                         const char* subpred = jsonObjectGetString( node );
2502                                         if( ! is_identifier( subpred ) ) {
2503                                                 osrfLogError(
2504                                                          OSRF_LOG_MARK,
2505                                                         "%s: Invalid boolean identifier in WHERE clause: \"%s\"",
2506                                                         MODULENAME,
2507                                                         subpred
2508                                                 );
2509                                                 jsonIteratorFree( search_itr );
2510                                                 buffer_free( sql_buf );
2511                                                 return NULL;
2512                                         }
2513
2514                                         buffer_fadd(sql_buf, " \"%s\".%s ", search_itr->key + 1, subpred);
2515                                 } else {
2516                                         char* subpred = searchWHERE( node, osrfHashGet( oilsIDL(), search_itr->key + 1 ), AND_OP_JOIN, ctx );
2517                                         if( subpred ) {
2518                                                 buffer_fadd(sql_buf, "( %s )", subpred);
2519                                                 free(subpred);
2520                                         } else {
2521                                                 jsonIteratorFree( search_itr );
2522                                                 buffer_free( sql_buf );
2523                                                 return NULL;
2524                                         }
2525                                 }
2526                         } else if ( !strcasecmp("-or",search_itr->key) ) {
2527                                 char* subpred = searchWHERE( node, meta, OR_OP_JOIN, ctx );
2528                                 if( subpred ) {
2529                                         buffer_fadd(sql_buf, "( %s )", subpred);
2530                                         free( subpred );
2531                                 } else {
2532                                         buffer_free( sql_buf );
2533                                         return NULL;
2534                                 }
2535                         } else if ( !strcasecmp("-and",search_itr->key) ) {
2536                                 char* subpred = searchWHERE( node, meta, AND_OP_JOIN, ctx );
2537                                 if( subpred ) {
2538                                         buffer_fadd(sql_buf, "( %s )", subpred);
2539                                         free( subpred );
2540                                 } else {
2541                                         buffer_free( sql_buf );
2542                                         return NULL;
2543                                 }
2544                         } else if ( !strcasecmp("-not",search_itr->key) ) {
2545                                 char* subpred = searchWHERE( node, meta, AND_OP_JOIN, ctx );
2546                                 if( subpred ) {
2547                                         buffer_fadd(sql_buf, " NOT ( %s )", subpred);
2548                                         free( subpred );
2549                                 } else {
2550                                         buffer_free( sql_buf );
2551                                         return NULL;
2552                                 }
2553                         } else if ( !strcasecmp("-exists",search_itr->key) ) {
2554                 char* subpred = SELECT(
2555                     ctx,
2556                     jsonObjectGetKey( node, "select" ),
2557                     jsonObjectGetKey( node, "from" ),
2558                     jsonObjectGetKey( node, "where" ),
2559                     jsonObjectGetKey( node, "having" ),
2560                     jsonObjectGetKey( node, "order_by" ),
2561                     jsonObjectGetKey( node, "limit" ),
2562                     jsonObjectGetKey( node, "offset" ),
2563                     SUBSELECT
2564                 );
2565
2566                                 if( subpred ) {
2567                                         buffer_fadd(sql_buf, "EXISTS ( %s )", subpred);
2568                                         free(subpred);
2569                                 } else {
2570                                         buffer_free( sql_buf );
2571                                         return NULL;
2572                                 }
2573             } else if ( !strcasecmp("-not-exists",search_itr->key) ) {
2574                 char* subpred = SELECT(
2575                     ctx,
2576                     jsonObjectGetKey( node, "select" ),
2577                     jsonObjectGetKey( node, "from" ),
2578                     jsonObjectGetKey( node, "where" ),
2579                     jsonObjectGetKey( node, "having" ),
2580                     jsonObjectGetKey( node, "order_by" ),
2581                     jsonObjectGetKey( node, "limit" ),
2582                     jsonObjectGetKey( node, "offset" ),
2583                     SUBSELECT
2584                 );
2585
2586                                 if( subpred ) {
2587                                         buffer_fadd(sql_buf, "NOT EXISTS ( %s )", subpred);
2588                                         free(subpred);
2589                                 } else {
2590                                         buffer_free( sql_buf );
2591                                         return NULL;
2592                                 }
2593
2594             } else {
2595
2596                 char* class = osrfHashGet(meta, "classname");
2597                 osrfHash* fields = osrfHashGet(meta, "fields");
2598                 osrfHash* field = osrfHashGet( fields, search_itr->key );
2599
2600
2601                 if (!field) {
2602                     char* table = getSourceDefinition(meta);
2603                                         if( !table )
2604                                                 table = strdup( "(?)" );
2605                     osrfLogError(
2606                         OSRF_LOG_MARK,
2607                         "%s: Attempt to reference non-existent column \"%s\" on %s (%s)",
2608                         MODULENAME,
2609                         search_itr->key,
2610                         table,
2611                         class ? class : "?"
2612                     );
2613                     buffer_free(sql_buf);
2614                     free(table);
2615                                         jsonIteratorFree(search_itr);
2616                                         return NULL;
2617                                 }
2618
2619                                 char* subpred = searchPredicate( class, field, node, ctx );
2620                                 if( subpred ) {
2621                                         buffer_add( sql_buf, subpred );
2622                                         free(subpred);
2623                                 } else {
2624                                         buffer_free(sql_buf);
2625                                         jsonIteratorFree(search_itr);
2626                                         return NULL;
2627                                 }
2628                         }
2629                 }
2630                 jsonIteratorFree(search_itr);
2631
2632     } else {
2633         // ERROR ... only hash and array allowed at this level
2634         char* predicate_string = jsonObjectToJSON( search_hash );
2635         osrfLogError(
2636             OSRF_LOG_MARK,
2637             "%s: Invalid predicate structure: %s",
2638             MODULENAME,
2639             predicate_string
2640         );
2641         buffer_free(sql_buf);
2642         free(predicate_string);
2643         return NULL;
2644     }
2645
2646         return buffer_release(sql_buf);
2647 }
2648
2649 char* SELECT (
2650                 /* method context */ osrfMethodContext* ctx,
2651                 
2652                 /* SELECT   */ jsonObject* selhash,
2653                 /* FROM     */ jsonObject* join_hash,
2654                 /* WHERE    */ jsonObject* search_hash,
2655                 /* HAVING   */ jsonObject* having_hash,
2656                 /* ORDER BY */ jsonObject* order_hash,
2657                 /* LIMIT    */ jsonObject* limit,
2658                 /* OFFSET   */ jsonObject* offset,
2659                 /* flags    */ int flags
2660 ) {
2661         const char* locale = osrf_message_get_last_locale();
2662
2663         // in case we don't get a select list
2664         jsonObject* defaultselhash = NULL;
2665
2666         // general tmp objects
2667         const jsonObject* tmp_const;
2668         jsonObject* selclass = NULL;
2669         jsonObject* selfield = NULL;
2670         jsonObject* snode = NULL;
2671         jsonObject* onode = NULL;
2672
2673         char* string = NULL;
2674         int from_function = 0;
2675         int first = 1;
2676         int gfirst = 1;
2677         //int hfirst = 1;
2678
2679         // the core search class
2680         char* core_class = NULL;
2681
2682         // metadata about the core search class
2683         osrfHash* core_meta = NULL;
2684
2685         osrfLogDebug(OSRF_LOG_MARK, "cstore SELECT locale: %s", locale);
2686
2687         // punt if there's no core class
2688         if (!join_hash || ( join_hash->type == JSON_HASH && !join_hash->size )) {
2689                 osrfLogError(
2690                         OSRF_LOG_MARK,
2691                         "%s: FROM clause is missing or empty",
2692                         MODULENAME
2693                 );
2694                 if( ctx )
2695                         osrfAppSessionStatus(
2696                                 ctx->session,
2697                                 OSRF_STATUS_INTERNALSERVERERROR,
2698                                 "osrfMethodException",
2699                                 ctx->request,
2700                                 "FROM clause is missing or empty in JSON query"
2701                         );
2702                 return NULL;
2703         }
2704
2705         // get the core class -- the only key of the top level FROM clause, or a string
2706         if (join_hash->type == JSON_HASH) {
2707                 jsonIterator* tmp_itr = jsonNewIterator( join_hash );
2708                 snode = jsonIteratorNext( tmp_itr );
2709                 
2710                 core_class = strdup( tmp_itr->key );
2711                 join_hash = snode;
2712                 
2713                 jsonObject* extra = jsonIteratorNext( tmp_itr );
2714
2715                 jsonIteratorFree( tmp_itr );
2716                 snode = NULL;
2717
2718                 // There shouldn't be more than one entry in join_hash
2719                 if( extra ) {
2720                         osrfLogError(
2721                                 OSRF_LOG_MARK,
2722                                 "%s: Malformed FROM clause: extra entry in JSON_HASH",
2723                                 MODULENAME
2724                         );
2725                         if( ctx )
2726                                 osrfAppSessionStatus(
2727                                         ctx->session,
2728                                         OSRF_STATUS_INTERNALSERVERERROR,
2729                                         "osrfMethodException",
2730                                         ctx->request,
2731                                         "Malformed FROM clause in JSON query"
2732                                 );
2733                         free( core_class );
2734                         return NULL;    // Malformed join_hash; extra entry
2735                 }
2736         } else if (join_hash->type == JSON_ARRAY) {
2737                 from_function = 1;
2738                 core_class = jsonObjectToSimpleString( jsonObjectGetIndex(join_hash, 0) );
2739                 selhash = NULL;
2740
2741         } else if (join_hash->type == JSON_STRING) {
2742                 core_class = jsonObjectToSimpleString( join_hash );
2743                 join_hash = NULL;
2744         }
2745         else {
2746                 osrfLogError(
2747                         OSRF_LOG_MARK,
2748                         "%s: FROM clause is unexpected JSON type: %s",
2749                         MODULENAME,
2750                         json_type( join_hash->type )
2751                 );
2752                 if( ctx )
2753                         osrfAppSessionStatus(
2754                                 ctx->session,
2755                                 OSRF_STATUS_INTERNALSERVERERROR,
2756                                 "osrfMethodException",
2757                                 ctx->request,
2758                                 "Ill-formed FROM clause in JSON query"
2759                         );
2760                 free( core_class );
2761                 return NULL;
2762         }
2763
2764         if (!from_function) {
2765                 // Get the IDL class definition for the core class
2766                 core_meta = osrfHashGet( oilsIDL(), core_class );
2767                 if( !core_meta ) {    // Didn't find it?
2768                         osrfLogError(
2769                                 OSRF_LOG_MARK,
2770                                 "%s: SELECT clause references undefined class: \"%s\"",
2771                                 MODULENAME,
2772                                 core_class
2773                         );
2774                         if( ctx )
2775                                 osrfAppSessionStatus(
2776                                         ctx->session,
2777                                         OSRF_STATUS_INTERNALSERVERERROR,
2778                                         "osrfMethodException",
2779                                         ctx->request,
2780                                         "SELECT clause references undefined class in JSON query"
2781                                 );
2782                         free( core_class );
2783                         return NULL;
2784                 }
2785
2786                 // Make sure the class isn't virtual
2787                 if( str_is_true( osrfHashGet( core_meta, "virtual" ) ) ) {
2788                         osrfLogError(
2789                                 OSRF_LOG_MARK,
2790                                 "%s: Core class is virtual: \"%s\"",
2791                                 MODULENAME,
2792                                 core_class
2793                         );
2794                         if( ctx )
2795                                 osrfAppSessionStatus(
2796                                         ctx->session,
2797                                         OSRF_STATUS_INTERNALSERVERERROR,
2798                                         "osrfMethodException",
2799                                         ctx->request,
2800                                         "FROM clause references virtual class in JSON query"
2801                                 );
2802                         free( core_class );
2803                         return NULL;
2804                 }
2805         }
2806
2807         // if the select list is empty, or the core class field list is '*',
2808         // build the default select list ...
2809         if (!selhash) {
2810                 selhash = defaultselhash = jsonNewObjectType(JSON_HASH);
2811                 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2812         } else if( selhash->type != JSON_HASH ) {
2813                 osrfLogError(
2814                         OSRF_LOG_MARK,
2815                         "%s: Expected JSON_HASH for SELECT clause; found %s",
2816                         MODULENAME,
2817                         json_type( selhash->type )
2818                 );
2819
2820                 if (ctx)
2821                         osrfAppSessionStatus(
2822                                 ctx->session,
2823                                 OSRF_STATUS_INTERNALSERVERERROR,
2824                                 "osrfMethodException",
2825                                 ctx->request,
2826                                 "Malformed SELECT clause in JSON query"
2827                         );
2828                 free( core_class );
2829                 return NULL;
2830         } else if ( (tmp_const = jsonObjectGetKeyConst( selhash, core_class )) && tmp_const->type == JSON_STRING ) {
2831                 const char* _x = jsonObjectGetString( tmp_const );
2832                 if (!strncmp( "*", _x, 1 )) {
2833                         jsonObjectRemoveKey( selhash, core_class );
2834                         jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2835                 }
2836         }
2837
2838         // the query buffer
2839         growing_buffer* sql_buf = buffer_init(128);
2840
2841         // temp buffer for the SELECT list
2842         growing_buffer* select_buf = buffer_init(128);
2843         growing_buffer* order_buf = buffer_init(128);
2844         growing_buffer* group_buf = buffer_init(128);
2845         growing_buffer* having_buf = buffer_init(128);
2846
2847         int aggregate_found = 0;     // boolean
2848
2849         // Build a select list
2850         if(from_function)   // From a function we select everything
2851                 OSRF_BUFFER_ADD_CHAR( select_buf, '*' );
2852         else {
2853
2854                 // If we need to build a default list, prepare to do so
2855                 jsonObject* _tmp = jsonObjectGetKey( selhash, core_class );
2856                 if ( _tmp && !_tmp->size ) {
2857
2858                         osrfHash* core_fields = osrfHashGet( core_meta, "fields" );
2859
2860                         osrfHashIterator* field_itr = osrfNewHashIterator( core_fields );
2861                         osrfHash* field_def;
2862                         while( ( field_def = osrfHashIteratorNext( field_itr ) ) ) {
2863                                 if( ! str_is_true( osrfHashGet( field_def, "virtual" ) ) ) {
2864                                         // This field is not virtual, so add it to the list
2865                                         jsonObjectPush( _tmp, jsonNewObject( osrfHashIteratorKey( field_itr ) ) );
2866                                 }
2867                         }
2868                         osrfHashIteratorFree( field_itr );
2869                 }
2870
2871                 // Now build the actual select list
2872             int sel_pos = 1;
2873             first = 1;
2874             gfirst = 1;
2875             jsonIterator* selclass_itr = jsonNewIterator( selhash );
2876             while ( (selclass = jsonIteratorNext( selclass_itr )) ) {    // For each class
2877
2878                     // Make sure the class is defined in the IDL
2879                         const char* cname = selclass_itr->key;
2880                         osrfHash* idlClass = osrfHashGet( oilsIDL(), cname );
2881                     if (!idlClass) {
2882                                 osrfLogError(
2883                                         OSRF_LOG_MARK,
2884                                         "%s: Selected class \"%s\" not defined in IDL",
2885                                         MODULENAME,
2886                                         cname
2887                                 );
2888
2889                                 if (ctx)
2890                                         osrfAppSessionStatus(
2891                                                 ctx->session,
2892                                                 OSRF_STATUS_INTERNALSERVERERROR,
2893                                                 "osrfMethodException",
2894                                                 ctx->request,
2895                                                 "Selected class is not defined"
2896                                         );
2897                                 jsonIteratorFree( selclass_itr );
2898                                 buffer_free( sql_buf );
2899                                 buffer_free( select_buf );
2900                                 buffer_free( order_buf );
2901                                 buffer_free( group_buf );
2902                                 buffer_free( having_buf );
2903                                 if( defaultselhash ) jsonObjectFree( defaultselhash );
2904                                 free( core_class );
2905                                 return NULL;
2906                         }
2907
2908                     // Make sure the target relation is in the join tree.
2909                         
2910                         // At this point join_hash is a step down from the join_hash we
2911                         // received as a parameter.  If the original was a JSON_STRING,
2912                         // then json_hash is now NULL.  If the original was a JSON_HASH,
2913                         // then json_hash is now the first (and only) entry in it,
2914                         // denoting the core class.  We've already excluded the
2915                         // possibility that the original was a JSON_ARRAY, because in
2916                         // that case from_function would be non-NULL, and we wouldn't
2917                         // be here.
2918
2919                         int class_in_from_clause;    // boolean
2920                         
2921                     if ( ! strcmp( core_class, cname ))
2922                                 // This is the core class -- no problem
2923                                 class_in_from_clause = 1;
2924                         else {
2925                                 if (!join_hash) 
2926                                         // There's only one class in the FROM clause, and this isn't it
2927                                         class_in_from_clause = 0;
2928                                 else if (join_hash->type == JSON_STRING) {
2929                                         // There's only one class in the FROM clause
2930                                         const char* str = jsonObjectGetString(join_hash);
2931                                         if ( strcmp( str, cname ) )
2932                                                 class_in_from_clause = 0;    // This isn't it
2933                                         else 
2934                                                 class_in_from_clause = 1;    // This is it
2935                                 } else {
2936                                         jsonObject* found = jsonObjectFindPath(join_hash, "//%s", cname);
2937                                         if ( 0 == found->size )
2938                                                 class_in_from_clause = 0;   // Nowhere in the join tree
2939                                         else
2940                                                 class_in_from_clause = 1;   // Found it
2941                                         jsonObjectFree( found );
2942                                 }
2943                         }
2944
2945                         // If the class isn't in the FROM clause, bail out
2946                         if( ! class_in_from_clause ) {
2947                                 osrfLogError(
2948                                         OSRF_LOG_MARK,
2949                                         "%s: SELECT clause references class not in FROM clause: \"%s\"",
2950                                         MODULENAME,
2951                                         cname
2952                                 );
2953                                 if( ctx )
2954                                         osrfAppSessionStatus(
2955                                                 ctx->session,
2956                                                 OSRF_STATUS_INTERNALSERVERERROR,
2957                                                 "osrfMethodException",
2958                                                 ctx->request,
2959                                                 "Selected class not in FROM clause in JSON query"
2960                                         );
2961                                 jsonIteratorFree( selclass_itr );
2962                                 buffer_free( sql_buf );
2963                                 buffer_free( select_buf );
2964                                 buffer_free( order_buf );
2965                                 buffer_free( group_buf );
2966                                 buffer_free( having_buf );
2967                                 if( defaultselhash ) jsonObjectFree( defaultselhash );
2968                                 free( core_class );
2969                                 return NULL;
2970                         }
2971
2972                         // Look up some attributes of the current class, so that we 
2973                         // don't have to look them up again for each field
2974                         osrfHash* class_field_set = osrfHashGet( idlClass, "fields" );
2975                         const char* class_pkey = osrfHashGet( idlClass, "primarykey" );
2976                         const char* class_tname = osrfHashGet( idlClass, "tablename" );
2977                         
2978                     // stitch together the column list ...
2979                     jsonIterator* select_itr = jsonNewIterator( selclass );
2980                     while ( (selfield = jsonIteratorNext( select_itr )) ) {   // for each SELECT column
2981
2982                                 // If we need a separator comma, add one
2983                                 if (first) {
2984                                         first = 0;
2985                                 } else {
2986                                         OSRF_BUFFER_ADD_CHAR( select_buf, ',' );
2987                                 }
2988
2989                                 // ... if it's a string, just toss it on the pile
2990                                 if (selfield->type == JSON_STRING) {
2991
2992                                         // Look up the field in the IDL
2993                                         const char* col_name = jsonObjectGetString( selfield );
2994                                         osrfHash* field_def = osrfHashGet( class_field_set, col_name );
2995                                         if ( !field_def ) {
2996                                                 // No such field in current class
2997                                                 osrfLogError(
2998                                                         OSRF_LOG_MARK,
2999                                                         "%s: Selected column \"%s\" not defined in IDL for class \"%s\"",
3000                                                         MODULENAME,
3001                                                         col_name,
3002                                                         cname
3003                                                 );
3004                                                 if( ctx )
3005                                                         osrfAppSessionStatus(
3006                                                                 ctx->session,
3007                                                                 OSRF_STATUS_INTERNALSERVERERROR,
3008                                                                 "osrfMethodException",
3009                                                                 ctx->request,
3010                                                                 "Selected column not defined in JSON query"
3011                                                         );
3012                                                 jsonIteratorFree( select_itr );
3013                                                 jsonIteratorFree( selclass_itr );
3014                                                 buffer_free( sql_buf );
3015                                                 buffer_free( select_buf );
3016                                                 buffer_free( order_buf );
3017                                                 buffer_free( group_buf );
3018                                                 buffer_free( having_buf );
3019                                                 if( defaultselhash ) jsonObjectFree( defaultselhash );
3020                                                 free( core_class );
3021                                                 return NULL;
3022                                         } else if ( str_is_true( osrfHashGet( field_def, "virtual" ) ) ) {
3023                                                 // Virtual field not allowed
3024                                                 osrfLogError(
3025                                                         OSRF_LOG_MARK,
3026                                                         "%s: Selected column \"%s\" for class \"%s\" is virtual",
3027                                                         MODULENAME,
3028                                                         col_name,
3029                                                         cname
3030                                                 );
3031                                                 if( ctx )
3032                                                         osrfAppSessionStatus(
3033                                                                 ctx->session,
3034                                                                 OSRF_STATUS_INTERNALSERVERERROR,
3035                                                                 "osrfMethodException",
3036                                                                 ctx->request,
3037                                                                 "Selected column may not be virtual in JSON query"
3038                                                         );
3039                                                 jsonIteratorFree( select_itr );
3040                                                 jsonIteratorFree( selclass_itr );
3041                                                 buffer_free( sql_buf );
3042                                                 buffer_free( select_buf );
3043                                                 buffer_free( order_buf );
3044                                                 buffer_free( group_buf );
3045                                                 buffer_free( having_buf );
3046                                                 if( defaultselhash ) jsonObjectFree( defaultselhash );
3047                                                 free( core_class );
3048                                                 return NULL;
3049                                         }
3050
3051                                         if (locale) {
3052                                                 const char* i18n;
3053                                                 if (flags & DISABLE_I18N)
3054                                                         i18n = NULL;
3055                                                 else
3056                                                         i18n = osrfHashGet(field_def, "i18n");
3057
3058                                                 if( str_is_true( i18n ) ) {
3059                             buffer_fadd( select_buf,
3060                                                                 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
3061                                                                 class_tname, cname, col_name, class_pkey, cname, class_pkey, locale, col_name );
3062                         } else {
3063                                             buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
3064                         }
3065                     } else {
3066                                         buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
3067                     }
3068                                         
3069                                 // ... but it could be an object, in which case we check for a Field Transform
3070                                 } else if (selfield->type == JSON_HASH) {
3071
3072                                         const char* col_name = jsonObjectGetString( jsonObjectGetKeyConst( selfield, "column" ) );
3073
3074                                         // Get the field definition from the IDL
3075                                         osrfHash* field_def = osrfHashGet( class_field_set, col_name );
3076                                         if ( !field_def ) {
3077                                                 // No such field in current class
3078                                                 osrfLogError(
3079                                                         OSRF_LOG_MARK,
3080                                                         "%s: Selected column \"%s\" is not defined in IDL for class \"%s\"",
3081                                                         MODULENAME,
3082                                                         col_name,
3083                                                         cname
3084                                                 );
3085                                                 if( ctx )
3086                                                         osrfAppSessionStatus(
3087                                                                 ctx->session,
3088                                                                 OSRF_STATUS_INTERNALSERVERERROR,
3089                                                                 "osrfMethodException",
3090                                                                 ctx->request,
3091                                                                 "Selected column is not defined in JSON query"
3092                                                         );
3093                                                 jsonIteratorFree( select_itr );
3094                                                 jsonIteratorFree( selclass_itr );
3095                                                 buffer_free( sql_buf );
3096                                                 buffer_free( select_buf );
3097                                                 buffer_free( order_buf );
3098                                                 buffer_free( group_buf );
3099                                                 buffer_free( having_buf );
3100                                                 if( defaultselhash ) jsonObjectFree( defaultselhash );
3101                                                 free( core_class );
3102                                                 return NULL;
3103                                         } else if ( str_is_true( osrfHashGet( field_def, "virtual" ) ) ) {
3104                                                 // No such field in current class
3105                                                 osrfLogError(
3106                                                         OSRF_LOG_MARK,
3107                                                         "%s: Selected column \"%s\" is virtual for class \"%s\"",
3108                                                         MODULENAME,
3109                                                         col_name,
3110                                                         cname
3111                                                 );
3112                                                 if( ctx )
3113                                                         osrfAppSessionStatus(
3114                                                                 ctx->session,
3115                                                                 OSRF_STATUS_INTERNALSERVERERROR,
3116                                                                 "osrfMethodException",
3117                                                                 ctx->request,
3118                                                                 "Selected column is virtual in JSON query"
3119                                                         );
3120                                                 jsonIteratorFree( select_itr );
3121                                                 jsonIteratorFree( selclass_itr );
3122                                                 buffer_free( sql_buf );
3123                                                 buffer_free( select_buf );
3124                                                 buffer_free( order_buf );
3125                                                 buffer_free( group_buf );
3126                                                 buffer_free( having_buf );
3127                                                 if( defaultselhash ) jsonObjectFree( defaultselhash );
3128                                                 free( core_class );
3129                                                 return NULL;
3130                                         }
3131
3132                                         // Decide what to use as a column alias
3133                                         const char* _alias;
3134                                         if ((tmp_const = jsonObjectGetKeyConst( selfield, "alias" ))) {
3135                                                 _alias = jsonObjectGetString( tmp_const );
3136                                         } else {         // Use field name as the alias
3137                                                 _alias = col_name;
3138                                         }
3139
3140                                         if (jsonObjectGetKeyConst( selfield, "transform" )) {
3141                                                 char* transform_str = searchFieldTransform(cname, field_def, selfield);
3142                                                 if( transform_str ) {
3143                                                         buffer_fadd(select_buf, " %s AS \"%s\"", transform_str, _alias);
3144                                                         free(transform_str);
3145                                                 } else {
3146                                                         if( ctx )
3147                                                                 osrfAppSessionStatus(
3148                                                                         ctx->session,
3149                                                                         OSRF_STATUS_INTERNALSERVERERROR,
3150                                                                         "osrfMethodException",
3151                                                                         ctx->request,
3152                                                                         "Unable to generate transform function in JSON query"
3153                                                                 );
3154                                                         jsonIteratorFree( select_itr );
3155                                                         jsonIteratorFree( selclass_itr );
3156                                                         buffer_free( sql_buf );
3157                                                         buffer_free( select_buf );
3158                                                         buffer_free( order_buf );
3159                                                         buffer_free( group_buf );
3160                                                         buffer_free( having_buf );
3161                                                         if( defaultselhash ) jsonObjectFree( defaultselhash );
3162                                                         free( core_class );
3163                                                         return NULL;
3164                                                 }
3165                                         } else {
3166
3167                                                 if (locale) {
3168                                                         const char* i18n;
3169                                                         if (flags & DISABLE_I18N)
3170                                                                 i18n = NULL;
3171                                                         else
3172                                                                 i18n = osrfHashGet(field_def, "i18n");
3173
3174                                                         if( str_is_true( i18n ) ) {
3175                                                                 buffer_fadd( select_buf,
3176                                                                         " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
3177                                                                         class_tname, cname, col_name, class_pkey, cname, class_pkey, locale, _alias);
3178                                                         } else {
3179                                                                 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, _alias);
3180                                                         }
3181                                                 } else {
3182                                                         buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, _alias);
3183                                                 }
3184                                         }
3185                                 }
3186                                 else {
3187                                         osrfLogError(
3188                                                 OSRF_LOG_MARK,
3189                                                 "%s: Selected item is unexpected JSON type: %s",
3190                                                 MODULENAME,
3191                                                 json_type( selfield->type )
3192                                         );
3193                                         if( ctx )
3194                                                 osrfAppSessionStatus(
3195                                                         ctx->session,
3196                                                         OSRF_STATUS_INTERNALSERVERERROR,
3197                                                         "osrfMethodException",
3198                                                         ctx->request,
3199                                                         "Ill-formed SELECT item in JSON query"
3200                                                 );
3201                                         jsonIteratorFree( select_itr );
3202                                         jsonIteratorFree( selclass_itr );
3203                                         buffer_free( sql_buf );
3204                                         buffer_free( select_buf );
3205                                         buffer_free( order_buf );
3206                                         buffer_free( group_buf );
3207                                         buffer_free( having_buf );
3208                                         if( defaultselhash ) jsonObjectFree( defaultselhash );
3209                                         free( core_class );
3210                                         return NULL;
3211                                 }
3212
3213                                 const jsonObject* agg_obj = jsonObjectGetKey( selfield, "aggregate" );
3214                                 if( obj_is_true( agg_obj ) )
3215                                         aggregate_found = 1;
3216                                 else {
3217                                         // Append a comma (except for the first one)
3218                                         // and add the column to a GROUP BY clause
3219                                         if (gfirst)
3220                                                 gfirst = 0;
3221                                         else
3222                                                 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
3223
3224                                         buffer_fadd(group_buf, " %d", sel_pos);
3225                                 }
3226
3227 #if 0
3228                             if (is_agg->size || (flags & SELECT_DISTINCT)) {
3229
3230                                         const jsonObject* aggregate_obj = jsonObjectGetKey( selfield, "aggregate" );
3231                                     if ( ! obj_is_true( aggregate_obj ) ) {
3232                                             if (gfirst) {
3233                                                     gfirst = 0;
3234                                             } else {
3235                                                         OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
3236                                             }
3237
3238                                             buffer_fadd(group_buf, " %d", sel_pos);
3239
3240                                         /*
3241                                     } else if (is_agg = jsonObjectGetKey( selfield, "having" )) {
3242                                             if (gfirst) {
3243                                                     gfirst = 0;
3244                                             } else {
3245                                                         OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
3246                                             }
3247
3248                                             _column = searchFieldTransform(cname, field, selfield);
3249                                                 OSRF_BUFFER_ADD_CHAR(group_buf, ' ');
3250                                                 OSRF_BUFFER_ADD(group_buf, _column);
3251                                             _column = searchFieldTransform(cname, field, selfield);
3252                                         */
3253                                     }
3254                             }
3255 #endif
3256
3257                             sel_pos++;
3258                     } // end while -- iterating across SELECT columns
3259
3260             jsonIteratorFree(select_itr);
3261             } // end while -- iterating across classes
3262
3263         jsonIteratorFree(selclass_itr);
3264     }
3265
3266
3267         char* col_list = buffer_release(select_buf);
3268         char* table = NULL;
3269         if (from_function) table = searchValueTransform(join_hash);
3270         else table = getSourceDefinition(core_meta);
3271         
3272         if( !table ) {
3273                 if (ctx)
3274                         osrfAppSessionStatus(
3275                                 ctx->session,
3276                                 OSRF_STATUS_INTERNALSERVERERROR,
3277                                 "osrfMethodException",
3278                                 ctx->request,
3279                                 "Unable to identify table for core class"
3280                         );
3281                 free( col_list );
3282                 buffer_free( sql_buf );
3283                 buffer_free( order_buf );
3284                 buffer_free( group_buf );
3285                 buffer_free( having_buf );
3286                 if( defaultselhash ) jsonObjectFree( defaultselhash );
3287                 free( core_class );
3288                 return NULL;    
3289         }
3290         
3291         // Put it all together
3292         buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\" ", col_list, table, core_class );
3293         free(col_list);
3294         free(table);
3295
3296     if (!from_function) {
3297             // Now, walk the join tree and add that clause
3298             if ( join_hash ) {
3299                     char* join_clause = searchJOIN( join_hash, core_meta );
3300                         if( join_clause ) {
3301                                 buffer_add(sql_buf, join_clause);
3302                         free(join_clause);
3303                         } else {
3304                                 if (ctx)
3305                                         osrfAppSessionStatus(
3306                                                 ctx->session,
3307                                                 OSRF_STATUS_INTERNALSERVERERROR,
3308                                                 "osrfMethodException",
3309                                                 ctx->request,
3310                                                 "Unable to construct JOIN clause(s)"
3311                                         );
3312                                 buffer_free( sql_buf );
3313                                 buffer_free( order_buf );
3314                                 buffer_free( group_buf );
3315                                 buffer_free( having_buf );
3316                                 if( defaultselhash ) jsonObjectFree( defaultselhash );
3317                                 free( core_class );
3318                                 return NULL;
3319                         }
3320             }
3321
3322                 // Build a WHERE clause, if there is one
3323             if ( search_hash ) {
3324                     buffer_add(sql_buf, " WHERE ");
3325
3326                     // and it's on the WHERE clause
3327                     char* pred = searchWHERE( search_hash, core_meta, AND_OP_JOIN, ctx );
3328
3329                     if (pred) {
3330                                 buffer_add(sql_buf, pred);
3331                                 free(pred);
3332                         } else {
3333                                 if (ctx) {
3334                                 osrfAppSessionStatus(
3335                                         ctx->session,
3336                                         OSRF_STATUS_INTERNALSERVERERROR,
3337                                         "osrfMethodException",
3338                                         ctx->request,
3339                                         "Severe query error in WHERE predicate -- see error log for more details"
3340                                 );
3341                             }
3342                             free(core_class);
3343                             buffer_free(having_buf);
3344                             buffer_free(group_buf);
3345                             buffer_free(order_buf);
3346                             buffer_free(sql_buf);
3347                             if (defaultselhash) jsonObjectFree(defaultselhash);
3348                             return NULL;
3349                     }
3350         }
3351
3352                 // Build a HAVING clause, if there is one
3353             if ( having_hash ) {
3354                     buffer_add(sql_buf, " HAVING ");
3355
3356                     // and it's on the the WHERE clause
3357                     char* pred = searchWHERE( having_hash, core_meta, AND_OP_JOIN, ctx );
3358
3359                     if (pred) {
3360                                 buffer_add(sql_buf, pred);
3361                                 free(pred);
3362                         } else {
3363                                 if (ctx) {
3364                                 osrfAppSessionStatus(
3365                                         ctx->session,
3366                                         OSRF_STATUS_INTERNALSERVERERROR,
3367                                         "osrfMethodException",
3368                                         ctx->request,
3369                                         "Severe query error in HAVING predicate -- see error log for more details"
3370                                 );
3371                             }
3372                             free(core_class);
3373                             buffer_free(having_buf);
3374                             buffer_free(group_buf);
3375                             buffer_free(order_buf);
3376                             buffer_free(sql_buf);
3377                             if (defaultselhash) jsonObjectFree(defaultselhash);
3378                             return NULL;
3379                     }
3380             }
3381
3382                 // Build an ORDER BY clause, if there is one
3383             first = 1;
3384             jsonIterator* class_itr = jsonNewIterator( order_hash );
3385             while ( (snode = jsonIteratorNext( class_itr )) ) {
3386
3387                     if (!jsonObjectGetKeyConst(selhash,class_itr->key))
3388                             continue;
3389
3390                         if ( snode->type == JSON_HASH ) {
3391
3392                                 jsonIterator* order_itr = jsonNewIterator( snode );
3393                                 while ( (onode = jsonIteratorNext( order_itr )) ) {
3394
3395                                         if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
3396                                                 continue;
3397
3398                                         const char* direction = NULL;
3399                                         if ( onode->type == JSON_HASH ) {
3400                                                 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
3401                                                         string = searchFieldTransform(
3402                                                                 class_itr->key,
3403                                                                 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
3404                                                                 onode
3405                                                         );
3406                                                         if( ! string ) {
3407                                                                 osrfAppSessionStatus(
3408                                                                         ctx->session,
3409                                                                         OSRF_STATUS_INTERNALSERVERERROR,
3410                                                                         "osrfMethodException",
3411                                                                         ctx->request,
3412                                                                         "Severe query error in ORDER BY clause -- see error log for more details"
3413                                                                 );
3414                                                                 jsonIteratorFree( order_itr );
3415                                                                 jsonIteratorFree( class_itr );
3416                                                                 free(core_class);
3417                                                                 buffer_free(having_buf);
3418                                                                 buffer_free(group_buf);
3419                                                                 buffer_free(order_buf);
3420                                                                 buffer_free(sql_buf);
3421                                                                 if (defaultselhash) jsonObjectFree(defaultselhash);
3422                                                                 return NULL;
3423                                                         }
3424                                                 } else {
3425                                                         growing_buffer* field_buf = buffer_init(16);
3426                                                         buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
3427                                                         string = buffer_release(field_buf);
3428                                                 }
3429
3430                                                 if ( (tmp_const = jsonObjectGetKeyConst( onode, "direction" )) ) {
3431                                                         const char* dir = jsonObjectGetString(tmp_const);
3432                                                         if (!strncasecmp(dir, "d", 1)) {
3433                                                                 direction = " DESC";
3434                                                         } else {
3435                                                                 direction = " ASC";
3436                                                         }
3437                                                 }
3438
3439                                         } else {
3440                                                 string = strdup(order_itr->key);
3441                                                 const char* dir = jsonObjectGetString(onode);
3442                                                 if (!strncasecmp(dir, "d", 1)) {
3443                                                         direction = " DESC";
3444                                                 } else {
3445                                                         direction = " ASC";
3446                                                 }
3447                                         }
3448
3449                                     if (first) {
3450                                             first = 0;
3451                                     } else {
3452                                             buffer_add(order_buf, ", ");
3453                                     }
3454
3455                                     buffer_add(order_buf, string);
3456                                     free(string);
3457
3458                                     if (direction) {
3459                                             buffer_add(order_buf, direction);
3460                                     }
3461
3462                             } // end while
3463                 // jsonIteratorFree(order_itr);
3464
3465                     } else if ( snode->type == JSON_ARRAY ) {
3466
3467                         jsonIterator* order_itr = jsonNewIterator( snode );
3468                             while ( (onode = jsonIteratorNext( order_itr )) ) {
3469
3470                                         const char* _f = jsonObjectGetString( onode );
3471
3472                                         if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, _f))
3473                                                 continue;
3474
3475                                         if (first) {
3476                                                 first = 0;
3477                                         } else {
3478                                                 buffer_add(order_buf, ", ");
3479                                         }
3480
3481                                         buffer_add(order_buf, _f);
3482
3483                                 } // end while
3484                 // jsonIteratorFree(order_itr);
3485
3486
3487                     // IT'S THE OOOOOOOOOOOLD STYLE!
3488                     } else {
3489                             osrfLogError(OSRF_LOG_MARK, "%s: Possible SQL injection attempt; direct order by is not allowed", MODULENAME);
3490                             if (ctx) {
3491                                 osrfAppSessionStatus(
3492                                         ctx->session,
3493                                         OSRF_STATUS_INTERNALSERVERERROR,
3494                                         "osrfMethodException",
3495                                         ctx->request,
3496                                         "Severe query error -- see error log for more details"
3497                                 );
3498                             }
3499
3500                             free(core_class);
3501                             buffer_free(having_buf);
3502                             buffer_free(group_buf);
3503                             buffer_free(order_buf);
3504                             buffer_free(sql_buf);
3505                             if (defaultselhash) jsonObjectFree(defaultselhash);
3506                             jsonIteratorFree(class_itr);
3507                             return NULL;
3508                     }
3509
3510             } // end while
3511                 // jsonIteratorFree(class_itr);
3512         }
3513
3514
3515         string = buffer_release(group_buf);
3516
3517         if ( *string && ( aggregate_found || (flags & SELECT_DISTINCT) ) ) {
3518                 OSRF_BUFFER_ADD( sql_buf, " GROUP BY " );
3519                 OSRF_BUFFER_ADD( sql_buf, string );
3520         }
3521
3522         free(string);
3523
3524         string = buffer_release(having_buf);
3525  
3526         if ( *string ) {
3527                 OSRF_BUFFER_ADD( sql_buf, " HAVING " );
3528                 OSRF_BUFFER_ADD( sql_buf, string );
3529         }
3530
3531         free(string);
3532
3533         string = buffer_release(order_buf);
3534
3535         if ( *string ) {
3536                 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
3537                 OSRF_BUFFER_ADD( sql_buf, string );
3538         }
3539
3540         free(string);
3541
3542         if ( limit ){
3543                 const char* str = jsonObjectGetString(limit);
3544                 buffer_fadd( sql_buf, " LIMIT %d", atoi(str) );
3545         }
3546
3547         if (offset) {
3548                 const char* str = jsonObjectGetString(offset);
3549                 buffer_fadd( sql_buf, " OFFSET %d", atoi(str) );
3550         }
3551
3552         if (!(flags & SUBSELECT)) OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
3553
3554         free(core_class);
3555         if (defaultselhash) jsonObjectFree(defaultselhash);
3556
3557         return buffer_release(sql_buf);
3558
3559 }
3560
3561 static char* buildSELECT ( jsonObject* search_hash, jsonObject* order_hash, osrfHash* meta, osrfMethodContext* ctx ) {
3562
3563         const char* locale = osrf_message_get_last_locale();
3564
3565         osrfHash* fields = osrfHashGet(meta, "fields");
3566         char* core_class = osrfHashGet(meta, "classname");
3567
3568         const jsonObject* join_hash = jsonObjectGetKeyConst( order_hash, "join" );
3569
3570         jsonObject* node = NULL;
3571         jsonObject* snode = NULL;
3572         jsonObject* onode = NULL;
3573         const jsonObject* _tmp = NULL;
3574         jsonObject* selhash = NULL;
3575         jsonObject* defaultselhash = NULL;
3576
3577         growing_buffer* sql_buf = buffer_init(128);
3578         growing_buffer* select_buf = buffer_init(128);
3579
3580         if ( !(selhash = jsonObjectGetKey( order_hash, "select" )) ) {
3581                 defaultselhash = jsonNewObjectType(JSON_HASH);
3582                 selhash = defaultselhash;
3583         }
3584         
3585         if ( !jsonObjectGetKeyConst(selhash,core_class) ) {
3586                 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
3587                 jsonObject* flist = jsonObjectGetKey( selhash, core_class );
3588                 
3589                 int i = 0;
3590                 char* field;
3591
3592                 osrfStringArray* keys = osrfHashKeys( fields );
3593                 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
3594                         if( ! str_is_true( osrfHashGet( osrfHashGet( fields, field ), "virtual" ) ) )
3595                                 jsonObjectPush( flist, jsonNewObject( field ) );
3596                 }
3597                 osrfStringArrayFree(keys);
3598         }
3599
3600         int first = 1;
3601         jsonIterator* class_itr = jsonNewIterator( selhash );
3602         while ( (snode = jsonIteratorNext( class_itr )) ) {
3603
3604                 char* cname = class_itr->key;
3605                 osrfHash* idlClass = osrfHashGet( oilsIDL(), cname );
3606                 if (!idlClass) continue;
3607
3608                 if (strcmp(core_class,class_itr->key)) {
3609                         if (!join_hash) continue;
3610
3611                         jsonObject* found =  jsonObjectFindPath(join_hash, "//%s", class_itr->key);
3612                         if (!found->size) {
3613                                 jsonObjectFree(found);
3614                                 continue;
3615                         }
3616
3617                         jsonObjectFree(found);
3618                 }
3619
3620                 jsonIterator* select_itr = jsonNewIterator( snode );
3621                 while ( (node = jsonIteratorNext( select_itr )) ) {
3622                         const char* item_str = jsonObjectGetString( node );
3623                         osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), item_str );
3624                         char* fname = osrfHashGet(field, "name");
3625
3626                         if (!field) continue;
3627
3628                         if (first) {
3629                                 first = 0;
3630                         } else {
3631                                 OSRF_BUFFER_ADD_CHAR(select_buf, ',');
3632                         }
3633
3634             if (locale) {
3635                         const char* i18n;
3636                                 const jsonObject* no_i18n_obj = jsonObjectGetKey( order_hash, "no_i18n" );
3637                                 if ( obj_is_true( no_i18n_obj ) )    // Suppress internationalization?
3638                                         i18n = NULL;
3639                                 else
3640                                         i18n = osrfHashGet(field, "i18n");
3641
3642                                 if( str_is_true( i18n ) ) {
3643                         char* pkey = osrfHashGet(idlClass, "primarykey");
3644                         char* tname = osrfHashGet(idlClass, "tablename");
3645
3646                     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);
3647                 } else {
3648                                 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
3649                 }
3650             } else {
3651                             buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
3652             }
3653                 }
3654
3655         jsonIteratorFree(select_itr);
3656         }
3657
3658     jsonIteratorFree(class_itr);
3659
3660         char* col_list = buffer_release(select_buf);
3661         char* table = getSourceDefinition(meta);
3662         if( !table )
3663                 table = strdup( "(null)" );
3664
3665         buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\"", col_list, table, core_class );
3666         free(col_list);
3667         free(table);
3668
3669         if ( join_hash ) {
3670                 char* join_clause = searchJOIN( join_hash, meta );
3671                 OSRF_BUFFER_ADD_CHAR(sql_buf, ' ');
3672                 OSRF_BUFFER_ADD(sql_buf, join_clause);
3673                 free(join_clause);
3674         }
3675
3676         osrfLogDebug(OSRF_LOG_MARK, "%s pre-predicate SQL =  %s",
3677                                  MODULENAME, OSRF_BUFFER_C_STR(sql_buf));
3678
3679         buffer_add(sql_buf, " WHERE ");
3680
3681         char* pred = searchWHERE( search_hash, meta, AND_OP_JOIN, ctx );
3682         if (!pred) {
3683                 osrfAppSessionStatus(
3684                         ctx->session,
3685                         OSRF_STATUS_INTERNALSERVERERROR,
3686                                 "osrfMethodException",
3687                                 ctx->request,
3688                                 "Severe query error -- see error log for more details"
3689                         );
3690                 buffer_free(sql_buf);
3691                 if(defaultselhash) jsonObjectFree(defaultselhash);
3692                 return NULL;
3693         } else {
3694                 buffer_add(sql_buf, pred);
3695                 free(pred);
3696         }
3697
3698         if (order_hash) {
3699                 char* string = NULL;
3700                 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "order_by" )) ){
3701
3702                         growing_buffer* order_buf = buffer_init(128);
3703
3704                         first = 1;
3705                         jsonIterator* class_itr = jsonNewIterator( _tmp );
3706                         while ( (snode = jsonIteratorNext( class_itr )) ) {
3707
3708                                 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
3709                                         continue;
3710
3711                                 if ( snode->type == JSON_HASH ) {
3712
3713                                         jsonIterator* order_itr = jsonNewIterator( snode );
3714                                         while ( (onode = jsonIteratorNext( order_itr )) ) {
3715
3716                                                 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
3717                                                         continue;
3718
3719                                                 char* direction = NULL;
3720                                                 if ( onode->type == JSON_HASH ) {
3721                                                         if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
3722                                                                 string = searchFieldTransform(
3723                                                                         class_itr->key,
3724                                                                         oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
3725                                                                         onode
3726                                                                 );
3727                                                                 if( ! string ) {
3728                                                                         osrfAppSessionStatus(
3729                                                                                 ctx->session,
3730                                                                                 OSRF_STATUS_INTERNALSERVERERROR,
3731                                                                                 "osrfMethodException",
3732                                                                                 ctx->request,
3733                                                                                 "Severe query error in ORDER BY clause -- see error log for more details"
3734                                                                         );
3735                                                                         jsonIteratorFree( order_itr );
3736                                                                         jsonIteratorFree( class_itr );
3737                                                                         buffer_free( order_buf );
3738                                                                         buffer_free( sql_buf );
3739                                                                         if( defaultselhash ) jsonObjectFree( defaultselhash );
3740                                                                         return NULL;
3741                                                                 }
3742                                                         } else {
3743                                                                 growing_buffer* field_buf = buffer_init(16);
3744                                                                 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
3745                                                                 string = buffer_release(field_buf);
3746                                                         }
3747
3748                                                         if ( (_tmp = jsonObjectGetKeyConst( onode, "direction" )) ) {
3749                                                                 const char* dir = jsonObjectGetString(_tmp);
3750                                                                 if (!strncasecmp(dir, "d", 1)) {
3751                                                                         direction = " DESC";
3752                                                                 } else {
3753                                                                         free(direction);
3754                                                                 }
3755                                                         }
3756
3757                                                 } else {
3758                                                         string = strdup(order_itr->key);
3759                                                         const char* dir = jsonObjectGetString(onode);
3760                                                         if (!strncasecmp(dir, "d", 1)) {
3761                                                                 direction = " DESC";
3762                                                         } else {
3763                                                                 direction = " ASC";
3764                                                         }
3765                                                 }
3766
3767                                                 if (first) {
3768                                                         first = 0;
3769                                                 } else {
3770                                                         buffer_add(order_buf, ", ");
3771                                                 }
3772
3773                                                 buffer_add(order_buf, string);
3774                                                 free(string);
3775
3776                                                 if (direction) {
3777                                                         buffer_add(order_buf, direction);
3778                                                 }
3779
3780                                         }
3781
3782                     jsonIteratorFree(order_itr);
3783
3784                                 } else {
3785                                         const char* str = jsonObjectGetString(snode);
3786                                         buffer_add(order_buf, str);
3787                                         break;
3788                                 }
3789
3790                         }
3791
3792                         jsonIteratorFree(class_itr);
3793
3794                         string = buffer_release(order_buf);
3795
3796                         if ( *string ) {
3797                                 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
3798                                 OSRF_BUFFER_ADD( sql_buf, string );
3799                         }
3800
3801                         free(string);
3802                 }
3803
3804                 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "limit" )) ){
3805                         const char* str = jsonObjectGetString(_tmp);
3806                         buffer_fadd(
3807                                 sql_buf,
3808                                 " LIMIT %d",
3809                                 atoi(str)
3810                         );
3811                 }
3812
3813                 _tmp = jsonObjectGetKeyConst( order_hash, "offset" );
3814                 if (_tmp) {
3815                         const char* str = jsonObjectGetString(_tmp);
3816                         buffer_fadd(
3817                                 sql_buf,
3818                                 " OFFSET %d",
3819                                 atoi(str)
3820                         );
3821                 }
3822         }
3823
3824         if (defaultselhash) jsonObjectFree(defaultselhash);
3825
3826         OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
3827         return buffer_release(sql_buf);
3828 }
3829
3830 int doJSONSearch ( osrfMethodContext* ctx ) {
3831         if(osrfMethodVerifyContext( ctx )) {
3832                 osrfLogError( OSRF_LOG_MARK,  "Invalid method context" );
3833                 return -1;
3834         }
3835
3836         osrfLogDebug(OSRF_LOG_MARK, "Recieved query request");
3837
3838         int err = 0;
3839
3840         // XXX for now...
3841         dbhandle = writehandle;
3842
3843         jsonObject* hash = jsonObjectGetIndex(ctx->params, 0);
3844
3845         int flags = 0;
3846
3847         if ( obj_is_true( jsonObjectGetKey( hash, "distinct" ) ) )
3848                 flags |= SELECT_DISTINCT;
3849
3850         if ( obj_is_true( jsonObjectGetKey( hash, "no_i18n" ) ) )
3851                 flags |= DISABLE_I18N;
3852
3853         osrfLogDebug(OSRF_LOG_MARK, "Building SQL ...");
3854         char* sql = SELECT(
3855                         ctx,
3856                         jsonObjectGetKey( hash, "select" ),
3857                         jsonObjectGetKey( hash, "from" ),
3858                         jsonObjectGetKey( hash, "where" ),
3859                         jsonObjectGetKey( hash, "having" ),
3860                         jsonObjectGetKey( hash, "order_by" ),
3861                         jsonObjectGetKey( hash, "limit" ),
3862                         jsonObjectGetKey( hash, "offset" ),
3863                         flags
3864         );
3865
3866         if (!sql) {
3867                 err = -1;
3868                 return err;
3869         }
3870         
3871         osrfLogDebug(OSRF_LOG_MARK, "%s SQL =  %s", MODULENAME, sql);
3872         dbi_result result = dbi_conn_query(dbhandle, sql);
3873
3874         if(result) {
3875                 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3876
3877                 if (dbi_result_first_row(result)) {
3878                         /* JSONify the result */
3879                         osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3880
3881                         do {
3882                                 jsonObject* return_val = oilsMakeJSONFromResult( result );
3883                                 osrfAppRespond( ctx, return_val );
3884                 jsonObjectFree( return_val );
3885                         } while (dbi_result_next_row(result));
3886
3887                 } else {
3888                         osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
3889                 }
3890
3891                 osrfAppRespondComplete( ctx, NULL );
3892
3893                 /* clean up the query */
3894                 dbi_result_free(result); 
3895
3896         } else {
3897                 err = -1;
3898                 osrfLogError(OSRF_LOG_MARK, "%s: Error with query [%s]", MODULENAME, sql);
3899                 osrfAppSessionStatus(
3900                         ctx->session,
3901                         OSRF_STATUS_INTERNALSERVERERROR,
3902                         "osrfMethodException",
3903                         ctx->request,
3904                         "Severe query error -- see error log for more details"
3905                 );
3906         }
3907
3908         free(sql);
3909         return err;
3910 }
3911
3912 static jsonObject* doFieldmapperSearch ( osrfMethodContext* ctx, osrfHash* meta,
3913                 const jsonObject* params, int* err ) {
3914
3915         // XXX for now...
3916         dbhandle = writehandle;
3917
3918         osrfHash* links = osrfHashGet(meta, "links");
3919         osrfHash* fields = osrfHashGet(meta, "fields");
3920         char* core_class = osrfHashGet(meta, "classname");
3921         char* pkey = osrfHashGet(meta, "primarykey");
3922
3923         const jsonObject* _tmp;
3924         jsonObject* obj;
3925         jsonObject* search_hash = jsonObjectGetIndex(params, 0);
3926         jsonObject* order_hash = jsonObjectGetIndex(params, 1);
3927
3928         char* sql = buildSELECT( search_hash, order_hash, meta, ctx );
3929         if (!sql) {
3930                 osrfLogDebug(OSRF_LOG_MARK, "Problem building query, returning NULL");
3931                 *err = -1;
3932                 return NULL;
3933         }
3934         
3935         osrfLogDebug(OSRF_LOG_MARK, "%s SQL =  %s", MODULENAME, sql);
3936
3937         dbi_result result = dbi_conn_query(dbhandle, sql);
3938         if( NULL == result ) {
3939                 osrfLogError(OSRF_LOG_MARK, "%s: Error retrieving %s with query [%s]",
3940                         MODULENAME, osrfHashGet(meta, "fieldmapper"), sql);
3941                 osrfAppSessionStatus(
3942                         ctx->session,
3943                         OSRF_STATUS_INTERNALSERVERERROR,
3944                         "osrfMethodException",
3945                         ctx->request,
3946                         "Severe query error -- see error log for more details"
3947                 );
3948                 *err = -1;
3949                 free(sql);
3950                 return jsonNULL;
3951
3952         } else {
3953                 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3954         }
3955
3956         jsonObject* res_list = jsonNewObjectType(JSON_ARRAY);
3957         osrfHash* dedup = osrfNewHash();
3958
3959         if (dbi_result_first_row(result)) {
3960                 /* JSONify the result */
3961                 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3962                 do {
3963                         obj = oilsMakeFieldmapperFromResult( result, meta );
3964                         char* pkey_val = oilsFMGetString( obj, pkey );
3965                         if ( osrfHashGet( dedup, pkey_val ) ) {
3966                                 jsonObjectFree(obj);
3967                                 free(pkey_val);
3968                         } else {
3969                                 osrfHashSet( dedup, pkey_val, pkey_val );
3970                                 jsonObjectPush(res_list, obj);
3971                         }
3972                 } while (dbi_result_next_row(result));
3973         } else {
3974                 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s",
3975                         MODULENAME, sql );
3976         }
3977
3978         osrfHashFree(dedup);
3979         /* clean up the query */
3980         dbi_result_free(result);
3981         free(sql);
3982
3983         if (res_list->size && order_hash) {
3984                 _tmp = jsonObjectGetKeyConst( order_hash, "flesh" );
3985                 if (_tmp) {
3986                         int x = (int)jsonObjectGetNumber(_tmp);
3987                         if (x == -1 || x > max_flesh_depth) x = max_flesh_depth;
3988
3989                         const jsonObject* temp_blob;
3990                         if ((temp_blob = jsonObjectGetKeyConst( order_hash, "flesh_fields" )) && x > 0) {
3991
3992                                 jsonObject* flesh_blob = jsonObjectClone( temp_blob );
3993                                 const jsonObject* flesh_fields = jsonObjectGetKeyConst( flesh_blob, core_class );
3994
3995                                 osrfStringArray* link_fields = NULL;
3996
3997                                 if (flesh_fields) {
3998                                         if (flesh_fields->size == 1) {
3999                                                 const char* _t = jsonObjectGetString( jsonObjectGetIndex( flesh_fields, 0 ) );
4000                                                 if (!strcmp(_t,"*")) link_fields = osrfHashKeys( links );
4001                                         }
4002
4003                                         if (!link_fields) {
4004                                                 jsonObject* _f;
4005                                                 link_fields = osrfNewStringArray(1);
4006                                                 jsonIterator* _i = jsonNewIterator( flesh_fields );
4007                                                 while ((_f = jsonIteratorNext( _i ))) {
4008                                                         osrfStringArrayAdd( link_fields, jsonObjectGetString( _f ) );
4009                                                 }
4010                         jsonIteratorFree(_i);
4011                                         }
4012                                 }
4013
4014                                 jsonObject* cur;
4015                                 jsonIterator* itr = jsonNewIterator( res_list );
4016                                 while ((cur = jsonIteratorNext( itr ))) {
4017
4018                                         int i = 0;
4019                                         char* link_field;
4020                                         
4021                                         while ( (link_field = osrfStringArrayGetString(link_fields, i++)) ) {
4022
4023                                                 osrfLogDebug(OSRF_LOG_MARK, "Starting to flesh %s", link_field);
4024
4025                                                 osrfHash* kid_link = osrfHashGet(links, link_field);
4026                                                 if (!kid_link) continue;
4027
4028                                                 osrfHash* field = osrfHashGet(fields, link_field);
4029                                                 if (!field) continue;
4030
4031                                                 osrfHash* value_field = field;
4032
4033                                                 osrfHash* kid_idl = osrfHashGet(oilsIDL(), osrfHashGet(kid_link, "class"));
4034                                                 if (!kid_idl) continue;
4035
4036                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
4037                                                         value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
4038                                                 }
4039                                                         
4040                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) { // might_have
4041                                                         value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
4042                                                 }
4043
4044                                                 osrfStringArray* link_map = osrfHashGet( kid_link, "map" );
4045
4046                                                 if (link_map->size > 0) {
4047                                                         jsonObject* _kid_key = jsonNewObjectType(JSON_ARRAY);
4048                                                         jsonObjectPush(
4049                                                                 _kid_key,
4050                                                                 jsonNewObject( osrfStringArrayGetString( link_map, 0 ) )
4051                                                         );
4052
4053                                                         jsonObjectSetKey(
4054                                                                 flesh_blob,
4055                                                                 osrfHashGet(kid_link, "class"),
4056                                                                 _kid_key
4057                                                         );
4058                                                 };
4059
4060                                                 osrfLogDebug(
4061                                                         OSRF_LOG_MARK,
4062                                                         "Link field: %s, remote class: %s, fkey: %s, reltype: %s",
4063                                                         osrfHashGet(kid_link, "field"),
4064                                                         osrfHashGet(kid_link, "class"),
4065                                                         osrfHashGet(kid_link, "key"),
4066                                                         osrfHashGet(kid_link, "reltype")
4067                                                 );
4068
4069                                                 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
4070                                                 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // search hash
4071                                                 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // order/flesh hash
4072
4073                                                 osrfLogDebug(OSRF_LOG_MARK, "Creating dummy params object...");
4074
4075                                                 const char* search_key = jsonObjectGetString(
4076                                                         jsonObjectGetIndex(
4077                                                                 cur,
4078                                                                 atoi( osrfHashGet(value_field, "array_position") )
4079                                                         )
4080                                                 );
4081
4082                                                 if (!search_key) {
4083                                                         osrfLogDebug(OSRF_LOG_MARK, "Nothing to search for!");
4084                                                         continue;
4085                                                 }
4086
4087                                                 jsonObjectSetKey(
4088                                                         jsonObjectGetIndex(fake_params, 0),
4089                                                         osrfHashGet(kid_link, "key"),
4090                                                         jsonNewObject( search_key )
4091                                                 );
4092
4093                                                 jsonObjectSetKey(
4094                                                         jsonObjectGetIndex(fake_params, 1),
4095                                                         "flesh",
4096                                                         jsonNewNumberObject( (double)(x - 1 + link_map->size) )
4097                                                 );
4098
4099                                                 if (flesh_blob)
4100                                                         jsonObjectSetKey( jsonObjectGetIndex(fake_params, 1), "flesh_fields", jsonObjectClone(flesh_blob) );
4101
4102                                                 if (jsonObjectGetKeyConst(order_hash, "order_by")) {
4103                                                         jsonObjectSetKey(
4104                                                                 jsonObjectGetIndex(fake_params, 1),
4105                                                                 "order_by",
4106                                                                 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "order_by"))
4107                                                         );
4108                                                 }
4109
4110                                                 if (jsonObjectGetKeyConst(order_hash, "select")) {
4111                                                         jsonObjectSetKey(
4112                                                                 jsonObjectGetIndex(fake_params, 1),
4113                                                                 "select",
4114                                                                 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "select"))
4115                                                         );
4116                                                 }
4117
4118                                                 jsonObject* kids = doFieldmapperSearch(ctx, kid_idl, fake_params, err);
4119
4120                                                 if(*err) {
4121                                                         jsonObjectFree( fake_params );
4122                                                         osrfStringArrayFree(link_fields);
4123                                                         jsonIteratorFree(itr);
4124                                                         jsonObjectFree(res_list);
4125                                                         jsonObjectFree(flesh_blob);
4126                                                         return jsonNULL;
4127                                                 }
4128
4129                                                 osrfLogDebug(OSRF_LOG_MARK, "Search for %s return %d linked objects", osrfHashGet(kid_link, "class"), kids->size);
4130
4131                                                 jsonObject* X = NULL;
4132                                                 if ( link_map->size > 0 && kids->size > 0 ) {
4133                                                         X = kids;
4134                                                         kids = jsonNewObjectType(JSON_ARRAY);
4135
4136                                                         jsonObject* _k_node;
4137                                                         jsonIterator* _k = jsonNewIterator( X );
4138                                                         while ((_k_node = jsonIteratorNext( _k ))) {
4139                                                                 jsonObjectPush(
4140                                                                         kids,
4141                                                                         jsonObjectClone(
4142                                                                                 jsonObjectGetIndex(
4143                                                                                         _k_node,
4144                                                                                         (unsigned long)atoi(
4145                                                                                                 osrfHashGet(
4146                                                                                                         osrfHashGet(
4147                                                                                                                 osrfHashGet(
4148                                                                                                                         osrfHashGet(
4149                                                                                                                                 oilsIDL(),
4150                                                                                                                                 osrfHashGet(kid_link, "class")
4151                                                                                                                         ),
4152                                                                                                                         "fields"
4153                                                                                                                 ),
4154                                                                                                                 osrfStringArrayGetString( link_map, 0 )
4155                                                                                                         ),
4156                                                                                                         "array_position"
4157                                                                                                 )
4158                                                                                         )
4159                                                                                 )
4160                                                                         )
4161                                                                 );
4162                                                         }
4163                                                         jsonIteratorFree(_k);
4164                                                 }
4165
4166                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_a" )) || !(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) {
4167                                                         osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
4168                                                         jsonObjectSetIndex(
4169                                                                 cur,
4170                                                                 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
4171                                                                 jsonObjectClone( jsonObjectGetIndex(kids, 0) )
4172                                                         );
4173                                                 }
4174
4175                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
4176                                                         osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
4177                                                         jsonObjectSetIndex(
4178                                                                 cur,
4179                                                                 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
4180                                                                 jsonObjectClone( kids )
4181                                                         );
4182                                                 }
4183
4184                                                 if (X) {
4185                                                         jsonObjectFree(kids);
4186                                                         kids = X;
4187                                                 }
4188
4189                                                 jsonObjectFree( kids );
4190                                                 jsonObjectFree( fake_params );
4191
4192                                                 osrfLogDebug(OSRF_LOG_MARK, "Fleshing of %s complete", osrfHashGet(kid_link, "field"));
4193                                                 osrfLogDebug(OSRF_LOG_MARK, "%s", jsonObjectToJSON(cur));
4194
4195                                         }
4196                                 }
4197                                 jsonObjectFree( flesh_blob );
4198                                 osrfStringArrayFree(link_fields);
4199                                 jsonIteratorFree(itr);
4200                         }
4201                 }
4202         }
4203
4204         return res_list;
4205 }
4206
4207
4208 static jsonObject* doUpdate(osrfMethodContext* ctx, int* err ) {
4209
4210         osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
4211 #ifdef PCRUD
4212         jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
4213 #else
4214         jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
4215 #endif
4216
4217         if (!verifyObjectClass(ctx, target)) {
4218                 *err = -1;
4219                 return jsonNULL;
4220         }
4221
4222         if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
4223                 osrfAppSessionStatus(
4224                         ctx->session,
4225                         OSRF_STATUS_BADREQUEST,
4226                         "osrfMethodException",
4227                         ctx->request,
4228                         "No active transaction -- required for UPDATE"
4229                 );
4230                 *err = -1;
4231                 return jsonNULL;
4232         }
4233
4234         // The following test is harmless but redundant.  If a class is
4235         // readonly, we don't register an update method for it.
4236         if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
4237                 osrfAppSessionStatus(
4238                         ctx->session,
4239                         OSRF_STATUS_BADREQUEST,
4240                         "osrfMethodException",
4241                         ctx->request,
4242                         "Cannot UPDATE readonly class"
4243                 );
4244                 *err = -1;
4245                 return jsonNULL;
4246         }
4247
4248         dbhandle = writehandle;
4249
4250         char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
4251
4252         // Set the last_xact_id
4253         int index = oilsIDL_ntop( target->classname, "last_xact_id" );
4254         if (index > -1) {
4255                 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
4256                 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
4257         }       
4258
4259         char* pkey = osrfHashGet(meta, "primarykey");
4260         osrfHash* fields = osrfHashGet(meta, "fields");
4261
4262         char* id = oilsFMGetString( target, pkey );
4263
4264         osrfLogDebug(
4265                 OSRF_LOG_MARK,
4266                 "%s updating %s object with %s = %s",
4267                 MODULENAME,
4268                 osrfHashGet(meta, "fieldmapper"),
4269                 pkey,
4270                 id
4271         );
4272
4273         growing_buffer* sql = buffer_init(128);
4274         buffer_fadd(sql,"UPDATE %s SET", osrfHashGet(meta, "tablename"));
4275
4276         int i = 0;
4277         int first = 1;
4278         char* field_name;
4279         osrfStringArray* field_list = osrfHashKeys( fields );
4280         while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
4281
4282                 osrfHash* field = osrfHashGet( fields, field_name );
4283
4284                 if(!( strcmp( field_name, pkey ) )) continue;
4285                 if( str_is_true( osrfHashGet(osrfHashGet(fields,field_name), "virtual") ) )
4286                         continue;
4287
4288                 const jsonObject* field_object = oilsFMGetObject( target, field_name );
4289
4290                 int value_is_numeric = 0;    // boolean
4291                 char* value;
4292                 if (field_object && field_object->classname) {
4293                         value = oilsFMGetString(
4294                                 field_object,
4295                                 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
4296             );
4297                 } else {
4298                         value = jsonObjectToSimpleString( field_object );
4299                         if( field_object && JSON_NUMBER == field_object->type )
4300                                 value_is_numeric = 1;
4301                 }
4302
4303                 osrfLogDebug( OSRF_LOG_MARK, "Updating %s object with %s = %s", osrfHashGet(meta, "fieldmapper"), field_name, value);
4304
4305                 if (!field_object || field_object->type == JSON_NULL) {
4306                         if ( !(!( strcmp( osrfHashGet(meta, "classname"), "au" ) ) && !( strcmp( field_name, "passwd" ) )) ) { // arg at the special case!
4307                                 if (first) first = 0;
4308                                 else OSRF_BUFFER_ADD_CHAR(sql, ',');
4309                                 buffer_fadd( sql, " %s = NULL", field_name );
4310                         }
4311                         
4312                 } else if ( value_is_numeric || !strcmp( get_primitive( field ), "number") ) {
4313                         if (first) first = 0;
4314                         else OSRF_BUFFER_ADD_CHAR(sql, ',');
4315
4316                         const char* numtype = get_datatype( field );
4317                         if ( !strncmp( numtype, "INT", 3 ) ) {
4318                                 buffer_fadd( sql, " %s = %ld", field_name, atol(value) );
4319                         } else if ( !strcmp( numtype, "NUMERIC" ) ) {
4320                                 buffer_fadd( sql, " %s = %f", field_name, atof(value) );
4321                         } else {
4322                                 // Must really be intended as a string, so quote it
4323                                 if ( dbi_conn_quote_string(dbhandle, &value) ) {
4324                                         buffer_fadd( sql, " %s = %s", field_name, value );
4325                                 } else {
4326                                         osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
4327                                         osrfAppSessionStatus(
4328                                                 ctx->session,
4329                                                 OSRF_STATUS_INTERNALSERVERERROR,
4330                                                 "osrfMethodException",
4331                                                 ctx->request,
4332                                                 "Error quoting string -- please see the error log for more details"
4333                                         );
4334                                         free(value);
4335                                         free(id);
4336                                         buffer_free(sql);
4337                                         *err = -1;
4338                                         return jsonNULL;
4339                                 }
4340                         }
4341
4342                         osrfLogDebug( OSRF_LOG_MARK, "%s is of type %s", field_name, numtype );
4343
4344                 } else {
4345                         if ( dbi_conn_quote_string(dbhandle, &value) ) {
4346                                 if (first) first = 0;
4347                                 else OSRF_BUFFER_ADD_CHAR(sql, ',');
4348                                 buffer_fadd( sql, " %s = %s", field_name, value );
4349
4350                         } else {
4351                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
4352                                 osrfAppSessionStatus(
4353                                         ctx->session,
4354                                         OSRF_STATUS_INTERNALSERVERERROR,
4355                                         "osrfMethodException",
4356                                         ctx->request,
4357                                         "Error quoting string -- please see the error log for more details"
4358                                 );
4359                                 free(value);
4360                                 free(id);
4361                                 buffer_free(sql);
4362                                 *err = -1;
4363                                 return jsonNULL;
4364                         }
4365                 }
4366
4367                 free(value);
4368                 
4369         }
4370
4371         jsonObject* obj = jsonNewObject(id);
4372
4373         if ( strcmp( get_primitive( osrfHashGet( osrfHashGet(meta, "fields"), pkey ) ), "number" ) )
4374                 dbi_conn_quote_string(dbhandle, &id);
4375
4376         buffer_fadd( sql, " WHERE %s = %s;", pkey, id );
4377
4378         char* query = buffer_release(sql);
4379         osrfLogDebug(OSRF_LOG_MARK, "%s: Update SQL [%s]", MODULENAME, query);
4380
4381         dbi_result result = dbi_conn_query(dbhandle, query);
4382         free(query);
4383
4384         if (!result) {
4385                 jsonObjectFree(obj);
4386                 obj = jsonNewObject(NULL);
4387                 osrfLogError(
4388                         OSRF_LOG_MARK,
4389                         "%s ERROR updating %s object with %s = %s",
4390                         MODULENAME,
4391                         osrfHashGet(meta, "fieldmapper"),
4392                         pkey,
4393                         id
4394                 );
4395         }
4396
4397         free(id);
4398
4399         return obj;
4400 }
4401
4402 static jsonObject* doDelete(osrfMethodContext* ctx, int* err ) {
4403
4404         osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
4405
4406         if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
4407                 osrfAppSessionStatus(
4408                         ctx->session,
4409                         OSRF_STATUS_BADREQUEST,
4410                         "osrfMethodException",
4411                         ctx->request,
4412                         "No active transaction -- required for DELETE"
4413                 );
4414                 *err = -1;
4415                 return jsonNULL;
4416         }
4417
4418         // The following test is harmless but redundant.  If a class is
4419         // readonly, we don't register a delete method for it.
4420         if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
4421                 osrfAppSessionStatus(
4422                         ctx->session,
4423                         OSRF_STATUS_BADREQUEST,
4424                         "osrfMethodException",
4425                         ctx->request,
4426                         "Cannot DELETE readonly class"
4427                 );
4428                 *err = -1;
4429                 return jsonNULL;
4430         }
4431
4432         dbhandle = writehandle;
4433
4434         jsonObject* obj;
4435
4436         char* pkey = osrfHashGet(meta, "primarykey");
4437
4438         int _obj_pos = 0;
4439 #ifdef PCRUD
4440                 _obj_pos = 1;
4441 #endif
4442
4443         char* id;
4444         if (jsonObjectGetIndex(ctx->params, _obj_pos)->classname) {
4445                 if (!verifyObjectClass(ctx, jsonObjectGetIndex( ctx->params, _obj_pos ))) {
4446                         *err = -1;
4447                         return jsonNULL;
4448                 }
4449
4450                 id = oilsFMGetString( jsonObjectGetIndex(ctx->params, _obj_pos), pkey );
4451         } else {
4452 #ifdef PCRUD
4453         if (!verifyObjectPCRUD( ctx, NULL )) {
4454                         *err = -1;
4455                         return jsonNULL;
4456         }
4457 #endif
4458                 id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, _obj_pos));
4459         }
4460
4461         osrfLogDebug(
4462                 OSRF_LOG_MARK,
4463                 "%s deleting %s object with %s = %s",
4464                 MODULENAME,
4465                 osrfHashGet(meta, "fieldmapper"),
4466                 pkey,
4467                 id
4468         );
4469
4470         obj = jsonNewObject(id);
4471
4472         if ( strcmp( get_primitive( osrfHashGet( osrfHashGet(meta, "fields"), pkey ) ), "number" ) )
4473                 dbi_conn_quote_string(writehandle, &id);
4474
4475         dbi_result result = dbi_conn_queryf(writehandle, "DELETE FROM %s WHERE %s = %s;", osrfHashGet(meta, "tablename"), pkey, id);
4476
4477         if (!result) {
4478                 jsonObjectFree(obj);
4479                 obj = jsonNewObject(NULL);
4480                 osrfLogError(
4481                         OSRF_LOG_MARK,
4482                         "%s ERROR deleting %s object with %s = %s",
4483                         MODULENAME,
4484                         osrfHashGet(meta, "fieldmapper"),
4485                         pkey,
4486                         id
4487                 );
4488         }
4489
4490         free(id);
4491
4492         return obj;
4493
4494 }
4495
4496
4497 static jsonObject* oilsMakeFieldmapperFromResult( dbi_result result, osrfHash* meta) {
4498         if(!(result && meta)) return jsonNULL;
4499
4500         jsonObject* object = jsonNewObject(NULL);
4501         jsonObjectSetClass(object, osrfHashGet(meta, "classname"));
4502
4503         osrfHash* fields = osrfHashGet(meta, "fields");
4504
4505         osrfLogInternal(OSRF_LOG_MARK, "Setting object class to %s ", object->classname);
4506
4507         osrfHash* _f;
4508         time_t _tmp_dt;
4509         char dt_string[256];
4510         struct tm gmdt;
4511
4512         int fmIndex;
4513         int columnIndex = 1;
4514         int attr;
4515         unsigned short type;
4516         const char* columnName;
4517
4518         /* cycle through the column list */
4519         while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
4520
4521                 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
4522
4523                 fmIndex = -1; // reset the position
4524                 
4525                 /* determine the field type and storage attributes */
4526                 type = dbi_result_get_field_type(result, columnName);
4527                 attr = dbi_result_get_field_attribs(result, columnName);
4528
4529                 /* fetch the fieldmapper index */
4530                 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
4531                         
4532                         if ( str_is_true( osrfHashGet(_f, "virtual") ) )
4533                                 continue;
4534                         
4535                         const char* pos = (char*)osrfHashGet(_f, "array_position");
4536                         if ( !pos ) continue;
4537
4538                         fmIndex = atoi( pos );
4539                         osrfLogInternal(OSRF_LOG_MARK, "... Found column at position [%s]...", pos);
4540                 } else {
4541                         continue;
4542                 }
4543
4544                 if (dbi_result_field_is_null(result, columnName)) {
4545                         jsonObjectSetIndex( object, fmIndex, jsonNewObject(NULL) );
4546                 } else {
4547
4548                         switch( type ) {
4549
4550                                 case DBI_TYPE_INTEGER :
4551
4552                                         if( attr & DBI_INTEGER_SIZE8 ) 
4553                                                 jsonObjectSetIndex( object, fmIndex, 
4554                                                         jsonNewNumberObject(dbi_result_get_longlong(result, columnName)));
4555                                         else 
4556                                                 jsonObjectSetIndex( object, fmIndex, 
4557                                                         jsonNewNumberObject(dbi_result_get_int(result, columnName)));
4558
4559                                         break;
4560
4561                                 case DBI_TYPE_DECIMAL :
4562                                         jsonObjectSetIndex( object, fmIndex, 
4563                                                         jsonNewNumberObject(dbi_result_get_double(result, columnName)));
4564                                         break;
4565
4566                                 case DBI_TYPE_STRING :
4567
4568
4569                                         jsonObjectSetIndex(
4570                                                 object,
4571                                                 fmIndex,
4572                                                 jsonNewObject( dbi_result_get_string(result, columnName) )
4573                                         );
4574
4575                                         break;
4576
4577                                 case DBI_TYPE_DATETIME :
4578
4579                                         memset(dt_string, '\0', sizeof(dt_string));
4580                                         memset(&gmdt, '\0', sizeof(gmdt));
4581
4582                                         _tmp_dt = dbi_result_get_datetime(result, columnName);
4583
4584
4585                                         if (!(attr & DBI_DATETIME_DATE)) {
4586                                                 gmtime_r( &_tmp_dt, &gmdt );
4587                                                 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
4588                                         } else if (!(attr & DBI_DATETIME_TIME)) {
4589                                                 localtime_r( &_tmp_dt, &gmdt );
4590                                                 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
4591                                         } else {
4592                                                 localtime_r( &_tmp_dt, &gmdt );
4593                                                 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
4594                                         }
4595
4596                                         jsonObjectSetIndex( object, fmIndex, jsonNewObject(dt_string) );
4597
4598                                         break;
4599
4600                                 case DBI_TYPE_BINARY :
4601                                         osrfLogError( OSRF_LOG_MARK, 
4602                                                 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
4603                         }
4604                 }
4605         }
4606
4607         return object;
4608 }
4609
4610 static jsonObject* oilsMakeJSONFromResult( dbi_result result ) {
4611         if(!result) return jsonNULL;
4612
4613         jsonObject* object = jsonNewObject(NULL);
4614
4615         time_t _tmp_dt;
4616         char dt_string[256];
4617         struct tm gmdt;
4618
4619         int fmIndex;
4620         int columnIndex = 1;
4621         int attr;
4622         unsigned short type;
4623         const char* columnName;
4624
4625         /* cycle through the column list */
4626         while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
4627
4628                 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
4629
4630                 fmIndex = -1; // reset the position
4631                 
4632                 /* determine the field type and storage attributes */
4633                 type = dbi_result_get_field_type(result, columnName);
4634                 attr = dbi_result_get_field_attribs(result, columnName);
4635
4636                 if (dbi_result_field_is_null(result, columnName)) {
4637                         jsonObjectSetKey( object, columnName, jsonNewObject(NULL) );
4638                 } else {
4639
4640                         switch( type ) {
4641
4642                                 case DBI_TYPE_INTEGER :
4643
4644                                         if( attr & DBI_INTEGER_SIZE8 ) 
4645                                                 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_longlong(result, columnName)) );
4646                                         else 
4647                                                 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_int(result, columnName)) );
4648                                         break;
4649
4650                                 case DBI_TYPE_DECIMAL :
4651                                         jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_double(result, columnName)) );
4652                                         break;
4653
4654                                 case DBI_TYPE_STRING :
4655                                         jsonObjectSetKey( object, columnName, jsonNewObject(dbi_result_get_string(result, columnName)) );
4656                                         break;
4657
4658                                 case DBI_TYPE_DATETIME :
4659
4660                                         memset(dt_string, '\0', sizeof(dt_string));
4661                                         memset(&gmdt, '\0', sizeof(gmdt));
4662
4663                                         _tmp_dt = dbi_result_get_datetime(result, columnName);
4664
4665
4666                                         if (!(attr & DBI_DATETIME_DATE)) {
4667                                                 gmtime_r( &_tmp_dt, &gmdt );
4668                                                 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
4669                                         } else if (!(attr & DBI_DATETIME_TIME)) {
4670                                                 localtime_r( &_tmp_dt, &gmdt );
4671                                                 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
4672                                         } else {
4673                                                 localtime_r( &_tmp_dt, &gmdt );
4674                                                 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
4675                                         }
4676
4677                                         jsonObjectSetKey( object, columnName, jsonNewObject(dt_string) );
4678                                         break;
4679
4680                                 case DBI_TYPE_BINARY :
4681                                         osrfLogError( OSRF_LOG_MARK, 
4682                                                 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
4683                         }
4684                 }
4685         }
4686
4687         return object;
4688 }
4689
4690 // Interpret a string as true or false
4691 static int str_is_true( const char* str ) {
4692         if( NULL == str || strcasecmp( str, "true" ) )
4693                 return 0;
4694         else
4695                 return 1;
4696 }
4697
4698 // Interpret a jsonObject as true or false
4699 static int obj_is_true( const jsonObject* obj ) {
4700         if( !obj )
4701                 return 0;
4702         else switch( obj->type )
4703         {
4704                 case JSON_BOOL :
4705                         if( obj->value.b )
4706                                 return 1;
4707                         else
4708                                 return 0;
4709                 case JSON_STRING :
4710                         if( strcasecmp( obj->value.s, "true" ) )
4711                                 return 0;
4712                         else
4713                                 return 1;
4714                 case JSON_NUMBER :          // Support 1/0 for perl's sake
4715                         if( jsonObjectGetNumber( obj ) == 1.0 )
4716                                 return 1;
4717                         else
4718                                 return 0;
4719                 default :
4720                         return 0;
4721         }
4722 }
4723
4724 // Translate a numeric code into a text string identifying a type of
4725 // jsonObject.  To be used for building error messages.
4726 static const char* json_type( int code ) {
4727         switch ( code )
4728         {
4729                 case 0 :
4730                         return "JSON_HASH";
4731                 case 1 :
4732                         return "JSON_ARRAY";
4733                 case 2 :
4734                         return "JSON_STRING";
4735                 case 3 :
4736                         return "JSON_NUMBER";
4737                 case 4 :
4738                         return "JSON_NULL";
4739                 case 5 :
4740                         return "JSON_BOOL";
4741                 default :
4742                         return "(unrecognized)";
4743         }
4744 }
4745
4746 // Extract the "primitive" attribute from an IDL field definition.
4747 // If we haven't initialized the app, then we must be running in
4748 // some kind of testbed.  In that case, default to "string".
4749 static const char* get_primitive( osrfHash* field ) {
4750         const char* s = osrfHashGet( field, "primitive" );
4751         if( !s ) {
4752                 if( child_initialized )
4753                         osrfLogError(
4754                                 OSRF_LOG_MARK,
4755                                 "%s ERROR No \"datatype\" attribute for field \"%s\"",
4756                                 MODULENAME,
4757                                 osrfHashGet( field, "name" )
4758                         );
4759                 else
4760                         s = "string";
4761         }
4762         return s;
4763 }
4764
4765 // Extract the "datatype" attribute from an IDL field definition.
4766 // If we haven't initialized the app, then we must be running in
4767 // some kind of testbed.  In that case, default to to NUMERIC,
4768 // since we look at the datatype only for numbers.
4769 static const char* get_datatype( osrfHash* field ) {
4770         const char* s = osrfHashGet( field, "datatype" );
4771         if( !s ) {
4772                 if( child_initialized )
4773                         osrfLogError(
4774                                 OSRF_LOG_MARK,
4775                                 "%s ERROR No \"datatype\" attribute for field \"%s\"",
4776                                 MODULENAME,
4777                                 osrfHashGet( field, "name" )
4778                         );
4779                 else
4780                         s = "NUMERIC";
4781         }
4782         return s;
4783 }
4784
4785 /*
4786 If the input string is potentially a valid SQL identifier, return 1.
4787 Otherwise return 0.
4788
4789 Purpose: to prevent certain kinds of SQL injection.  To that end we
4790 don't necessarily need to follow all the rules exactly, such as requiring
4791 that the first character not be a digit.
4792
4793 We allow leading and trailing white space.  In between, we do not allow
4794 punctuation (except for underscores and dollar signs), control 
4795 characters, or embedded white space.
4796
4797 More pedantically we should allow quoted identifiers containing arbitrary
4798 characters, but for the foreseeable future such quoted identifiers are not
4799 likely to be an issue.
4800 */
4801 static int is_identifier( const char* s) {
4802         if( !s )
4803                 return 0;
4804
4805         // Skip leading white space
4806         while( isspace( (unsigned char) *s ) )
4807                 ++s;
4808
4809         if( !s )
4810                 return 0;   // Nothing but white space?  Not okay.
4811
4812         // Check each character until we reach white space or
4813         // end-of-string.  Letters, digits, underscores, and 
4814         // dollar signs are okay. With the exception of periods
4815         // (as in schema.identifier), control characters and other
4816         // punctuation characters are not okay.  Anything else
4817         // is okay -- it could for example be part of a multibyte
4818         // UTF8 character such as a letter with diacritical marks,
4819         // and those are allowed.
4820         do {
4821                 if( isalnum( (unsigned char) *s )
4822                         || '.' == *s
4823                         || '_' == *s
4824                         || '$' == *s )
4825                         ;  // Fine; keep going
4826                 else if(   ispunct( (unsigned char) *s )
4827                                 || iscntrl( (unsigned char) *s ) )
4828                         return 0;
4829                         ++s;
4830         } while( *s && ! isspace( (unsigned char) *s ) );
4831
4832         // If we found any white space in the above loop,
4833         // the rest had better be all white space.
4834         
4835         while( isspace( (unsigned char) *s ) )
4836                 ++s;
4837
4838         if( *s )
4839                 return 0;   // White space was embedded within non-white space
4840
4841         return 1;
4842 }
4843
4844 /*
4845 Determine whether to accept a character string as a comparison operator.
4846 Return 1 if it's good, or 0 if it's bad.
4847
4848 We don't validate it for real.  We just make sure that it doesn't contain
4849 any semicolons or white space (with a special exception for the
4850 "SIMILAR TO" operator).  The idea is to block certain kinds of SQL
4851 injection.  If it has no semicolons or white space but it's still not a
4852 valid operator, then the database will complain.
4853
4854 Another approach would be to compare the string against a short list of
4855 approved operators.  We don't do that because we want to allow custom
4856 operators like ">100*", which would be difficult or impossible to
4857 express otherwise in a JSON query.
4858 */
4859 static int is_good_operator( const char* op ) {
4860         if( !op ) return 0;   // Sanity check
4861
4862         const char* s = op;
4863         while( *s ) {
4864                 if( isspace( (unsigned char) *s ) ) {
4865                         // Special exception for SIMILAR TO.  Someday we might make
4866                         // exceptions for IS DISTINCT FROM and IS NOT DISTINCT FROM.
4867                         if( !strcasecmp( op, "similar to" ) )
4868                                 return 1;
4869                         else
4870                                 return 0;
4871                 }
4872                 else if( ';' == *s )
4873                         return 0;
4874                 ++s;
4875         }
4876         return 1;
4877 }