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