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