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