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