]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/c-apps/oils_cstore.c
Patch from Scott McKellar plugging several pointer leaks
[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, 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
1146         if (field_transform) {
1147                 buffer_fadd( sql_buf, "%s(\"%s\".%s", field_transform, class, osrfHashGet(field, "name"));
1148             const jsonObject* array = jsonObjectGetKeyConst( node, "params" );
1149
1150         if (array) {
1151                 int func_item_index = 0;
1152                 jsonObject* func_item;
1153                 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1154
1155                         char* val = jsonObjectToSimpleString(func_item);
1156
1157                     if ( dbi_conn_quote_string(dbhandle, &val) ) {
1158                             buffer_fadd( sql_buf, ",%s", val );
1159                         } else {
1160                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1161                             free(field_transform);
1162                                 buffer_free(sql_buf);
1163                                 return NULL;
1164                 }
1165             }
1166
1167         }
1168
1169         buffer_add(
1170                 sql_buf,
1171                 " )"
1172         );
1173  
1174         } else {
1175                 buffer_fadd( sql_buf, "\"%s\".%s", class, osrfHashGet(field, "name"));
1176     }
1177
1178         if (field_transform) free(field_transform);
1179
1180         return buffer_release(sql_buf);
1181 }
1182
1183 static char* searchFieldTransformPredicate (const char* class, osrfHash* field, jsonObjectNode* node) {
1184         char* field_transform = searchFieldTransform( class, field, node->item );
1185         char* value = NULL;
1186
1187         if (!jsonObjectGetKeyConst( node->item, "value" )) {
1188                 value = searchWHERE( node->item, osrfHashGet( oilsIDL(), class ), AND_OP_JOIN );
1189         } else if (jsonObjectGetKeyConst( node->item, "value" )->type == JSON_ARRAY) {
1190                 value = searchValueTransform(jsonObjectGetKeyConst( node->item, "value" ));
1191         } else if (jsonObjectGetKeyConst( node->item, "value" )->type == JSON_HASH) {
1192                 value = searchWHERE( jsonObjectGetKeyConst( node->item, "value" ), osrfHashGet( oilsIDL(), class ), AND_OP_JOIN );
1193         } else if (jsonObjectGetKeyConst( node->item, "value" )->type != JSON_NULL) {
1194                 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1195                         value = jsonNumberToDBString( field, jsonObjectGetKeyConst( node->item, "value" ) );
1196                 } else {
1197                         value = jsonObjectToSimpleString(jsonObjectGetKeyConst( node->item, "value" ));
1198                         if ( !dbi_conn_quote_string(dbhandle, &value) ) {
1199                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, value);
1200                                 free(value);
1201                                 free(field_transform);
1202                                 return NULL;
1203                         }
1204                 }
1205         }
1206
1207         growing_buffer* sql_buf = buffer_init(32);
1208         
1209         buffer_fadd(
1210                 sql_buf,
1211                 "%s %s %s",
1212                 field_transform,
1213                 node->key,
1214                 value
1215         );
1216
1217         free(value);
1218         free(field_transform);
1219
1220         return buffer_release(sql_buf);
1221 }
1222
1223 static char* searchSimplePredicate (const char* orig_op, const char* class,
1224                 osrfHash* field, const jsonObject* node) {
1225
1226         char* val = NULL;
1227
1228         if (node->type != JSON_NULL) {
1229                 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1230                         val = jsonNumberToDBString( field, node );
1231                 } else {
1232                         val = jsonObjectToSimpleString(node);
1233                 }
1234         }
1235
1236         char* pred = searchWriteSimplePredicate( class, field, osrfHashGet(field, "name"), orig_op, val );
1237
1238         if (val) free(val);
1239
1240         return pred;
1241 }
1242
1243 static char* searchWriteSimplePredicate ( const char* class, osrfHash* field,
1244         const char* left, const char* orig_op, const char* right ) {
1245
1246         char* val = NULL;
1247         char* op = NULL;
1248         if (right == NULL) {
1249                 val = strdup("NULL");
1250
1251                 if (strcmp( orig_op, "=" ))
1252                         op = strdup("IS NOT");
1253                 else
1254                         op = strdup("IS");
1255
1256         } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1257                 val = strdup(right);
1258                 op = strdup(orig_op);
1259
1260         } else {
1261                 val = strdup(right);
1262                 if ( !dbi_conn_quote_string(dbhandle, &val) ) {
1263                         osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1264                         free(val);
1265                         return NULL;
1266                 }
1267                 op = strdup(orig_op);
1268         }
1269
1270         growing_buffer* sql_buf = buffer_init(16);
1271         buffer_fadd( sql_buf, "\"%s\".%s %s %s", class, left, op, val );
1272         free(val);
1273         free(op);
1274
1275         return buffer_release(sql_buf);
1276 }
1277
1278 static char* searchBETWEENPredicate (const char* class, osrfHash* field, jsonObject* node) {
1279
1280         char* x_string;
1281         char* y_string;
1282
1283         if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1284                 x_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,0));
1285                 y_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,1));
1286
1287         } else {
1288                 x_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,0));
1289                 y_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,1));
1290                 if ( !(dbi_conn_quote_string(dbhandle, &x_string) && dbi_conn_quote_string(dbhandle, &y_string)) ) {
1291                         osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key strings [%s] and [%s]", MODULENAME, x_string, y_string);
1292                         free(x_string);
1293                         free(y_string);
1294                         return NULL;
1295                 }
1296         }
1297
1298         growing_buffer* sql_buf = buffer_init(32);
1299         buffer_fadd( sql_buf, "%s BETWEEN %s AND %s", osrfHashGet(field, "name"), x_string, y_string );
1300         free(x_string);
1301         free(y_string);
1302
1303         return buffer_release(sql_buf);
1304 }
1305
1306 static char* searchPredicate ( const char* class, osrfHash* field, jsonObject* node ) {
1307
1308         char* pred = NULL;
1309         if (node->type == JSON_ARRAY) { // equality IN search
1310                 pred = searchINPredicate( class, field, node, NULL );
1311         } else if (node->type == JSON_HASH) { // non-equality search
1312                 jsonObjectNode* pred_node;
1313                 jsonObjectIterator* pred_itr = jsonNewObjectIterator( node );
1314                 while ( (pred_node = jsonObjectIteratorNext( pred_itr )) ) {
1315                         if ( !(strcasecmp( pred_node->key,"between" )) )
1316                                 pred = searchBETWEENPredicate( class, field, pred_node->item );
1317                         else if ( !(strcasecmp( pred_node->key,"in" )) || !(strcasecmp( pred_node->key,"not in" )) )
1318                                 pred = searchINPredicate( class, field, pred_node->item, pred_node->key );
1319                         else if ( pred_node->item->type == JSON_ARRAY )
1320                                 pred = searchFunctionPredicate( class, field, pred_node );
1321                         else if ( pred_node->item->type == JSON_HASH )
1322                                 pred = searchFieldTransformPredicate( class, field, pred_node );
1323                         else 
1324                                 pred = searchSimplePredicate( pred_node->key, class, field, pred_node->item );
1325
1326                         break;
1327                 }
1328         jsonObjectIteratorFree(pred_itr);
1329         } else if (node->type == JSON_NULL) { // IS NULL search
1330                 growing_buffer* _p = buffer_init(64);
1331                 buffer_fadd(
1332                         _p,
1333                         "\"%s\".%s IS NULL",
1334                         class,
1335                         osrfHashGet(field, "name")
1336                 );
1337                 pred = buffer_release(_p);
1338         } else { // equality search
1339                 pred = searchSimplePredicate( "=", class, field, node );
1340         }
1341
1342         return pred;
1343
1344 }
1345
1346
1347 /*
1348
1349 join : {
1350         acn : {
1351                 field : record,
1352                 fkey : id
1353                 type : left
1354                 filter_op : or
1355                 filter : { ... },
1356                 join : {
1357                         acp : {
1358                                 field : call_number,
1359                                 fkey : id,
1360                                 filter : { ... },
1361                         },
1362                 },
1363         },
1364         mrd : {
1365                 field : record,
1366                 type : inner
1367                 fkey : id,
1368                 filter : { ... },
1369         }
1370 }
1371
1372 */
1373
1374 static char* searchJOIN ( const jsonObject* join_hash, osrfHash* leftmeta ) {
1375
1376         const jsonObject* working_hash;
1377         jsonObject* freeable_hash = NULL;
1378
1379         if (join_hash->type == JSON_STRING) {
1380                 // create a wrapper around a copy of the original
1381                 char* _tmp = jsonObjectToSimpleString( join_hash );
1382                 freeable_hash = jsonParseString("{}");
1383                 jsonObjectSetKey(freeable_hash, _tmp, NULL);
1384                 free(_tmp);
1385                 working_hash = freeable_hash;
1386         }
1387         else
1388                 working_hash = join_hash;
1389
1390         growing_buffer* join_buf = buffer_init(128);
1391         char* leftclass = osrfHashGet(leftmeta, "classname");
1392
1393         jsonObjectNode* snode = NULL;
1394         jsonObjectIterator* search_itr = jsonNewObjectIterator( working_hash );
1395         if(freeable_hash)
1396                 jsonObjectFree(freeable_hash);
1397         
1398         while ( (snode = jsonObjectIteratorNext( search_itr )) ) {
1399                 osrfHash* idlClass = osrfHashGet( oilsIDL(), snode->key );
1400
1401                 char* class = osrfHashGet(idlClass, "classname");
1402
1403                 char* table = getSourceDefinition(idlClass);
1404                 char* type = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode->item, "type" ) );
1405                 char* filter_op = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode->item, "filter_op" ) );
1406                 char* fkey = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode->item, "fkey" ) );
1407                 char* field = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode->item, "field" ) );
1408
1409                 const jsonObject* filter = jsonObjectGetKeyConst( snode->item, "filter" );
1410                 const jsonObject* join_filter = jsonObjectGetKeyConst( snode->item, "join" );
1411
1412                 if (field && !fkey) {
1413                         fkey = (char*)oilsIDLFindPath("/%s/links/%s/key", class, field);
1414                         if (!fkey) {
1415                                 osrfLogError(
1416                                         OSRF_LOG_MARK,
1417                                         "%s: JOIN failed.  No link defined from %s.%s to %s",
1418                                         MODULENAME,
1419                                         class,
1420                                         field,
1421                                         leftclass
1422                                 );
1423                                 buffer_free(join_buf);
1424                                 free(table);
1425                                 return NULL;
1426                         }
1427                         fkey = strdup( fkey );
1428
1429                 } else if (!field && fkey) {
1430                         field = (char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, fkey );
1431                         if (!field) {
1432                                 osrfLogError(
1433                                         OSRF_LOG_MARK,
1434                                         "%s: JOIN failed.  No link defined from %s.%s to %s",
1435                                         MODULENAME,
1436                                         leftclass,
1437                                         fkey,
1438                                         class
1439                                 );
1440                                 buffer_free(join_buf);
1441                                 free(table);
1442                                 return NULL;
1443                         }
1444                         field = strdup( field );
1445
1446                 } else if (!field && !fkey) {
1447                         osrfHash* _links = oilsIDLFindPath("/%s/links", leftclass);
1448
1449                         int i = 0;
1450                         osrfStringArray* keys = osrfHashKeys( _links );
1451                         while ( (fkey = osrfStringArrayGetString(keys, i++)) ) {
1452                                 fkey = strdup(osrfStringArrayGetString(keys, i++));
1453                                 if ( !strcmp( (char*)oilsIDLFindPath("/%s/links/%s/class", leftclass, fkey), class) ) {
1454                                         field = strdup( (char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, fkey) );
1455                                         break;
1456                                 } else {
1457                                         free(fkey);
1458                                 }
1459                         }
1460                         osrfStringArrayFree(keys);
1461
1462                         if (!field && !fkey) {
1463                                 _links = oilsIDLFindPath("/%s/links", class);
1464
1465                                 i = 0;
1466                                 keys = osrfHashKeys( _links );
1467                                 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
1468                                         field = strdup(osrfStringArrayGetString(keys, i++));
1469                                         if ( !strcmp( (char*)oilsIDLFindPath("/%s/links/%s/class", class, field), class) ) {
1470                                                 fkey = strdup( (char*)oilsIDLFindPath("/%s/links/%s/key", class, field) );
1471                                                 break;
1472                                         } else {
1473                                                 free(field);
1474                                         }
1475                                 }
1476                                 osrfStringArrayFree(keys);
1477                         }
1478
1479                         if (!field && !fkey) {
1480                                 osrfLogError(
1481                                         OSRF_LOG_MARK,
1482                                         "%s: JOIN failed.  No link defined between %s and %s",
1483                                         MODULENAME,
1484                                         leftclass,
1485                                         class
1486                                 );
1487                                 buffer_free(join_buf);
1488                                 free(table);
1489                                 return NULL;
1490                         }
1491
1492                 }
1493
1494                 if (type) {
1495                         if ( !strcasecmp(type,"left") ) {
1496                                 buffer_add(join_buf, " LEFT JOIN");
1497                         } else if ( !strcasecmp(type,"right") ) {
1498                                 buffer_add(join_buf, " RIGHT JOIN");
1499                         } else if ( !strcasecmp(type,"full") ) {
1500                                 buffer_add(join_buf, " FULL JOIN");
1501                         } else {
1502                                 buffer_add(join_buf, " INNER JOIN");
1503                         }
1504                 } else {
1505                         buffer_add(join_buf, " INNER JOIN");
1506                 }
1507
1508                 buffer_fadd(join_buf, " %s AS \"%s\" ON ( \"%s\".%s = \"%s\".%s", table, class, class, field, leftclass, fkey);
1509                 free(table);
1510
1511                 if (filter) {
1512                         if (filter_op) {
1513                                 if (!strcasecmp("or",filter_op)) {
1514                                         buffer_add( join_buf, " OR " );
1515                                 } else {
1516                                         buffer_add( join_buf, " AND " );
1517                                 }
1518                         } else {
1519                                 buffer_add( join_buf, " AND " );
1520                         }
1521
1522                         char* jpred = searchWHERE( filter, idlClass, AND_OP_JOIN );
1523                         buffer_fadd( join_buf, " %s", jpred );
1524                         free(jpred);
1525                 }
1526
1527                 buffer_add(join_buf, " ) ");
1528                 
1529                 if (join_filter) {
1530                         char* jpred = searchJOIN( join_filter, idlClass );
1531                         buffer_fadd( join_buf, " %s", jpred );
1532                         free(jpred);
1533                 }
1534
1535                 free(type);
1536                 free(filter_op);
1537                 free(fkey);
1538                 free(field);
1539         }
1540
1541     jsonObjectIteratorFree(search_itr);
1542
1543         return buffer_release(join_buf);
1544 }
1545
1546 /*
1547
1548 { +class : { -or|-and : { field : { op : value }, ... } ... }, ... }
1549 { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }
1550 [ { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }, ... ]
1551
1552 */
1553 static char* searchWHERE ( const jsonObject* search_hash, osrfHash* meta, int opjoin_type ) {
1554
1555         growing_buffer* sql_buf = buffer_init(128);
1556
1557         jsonObjectNode* node = NULL;
1558
1559     int first = 1;
1560     if ( search_hash->type == JSON_ARRAY ) {
1561         jsonObjectIterator* search_itr = jsonNewObjectIterator( search_hash );
1562         while ( (node = jsonObjectIteratorNext( search_itr )) ) {
1563             if (first) {
1564                 first = 0;
1565             } else {
1566                 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
1567                 else buffer_add(sql_buf, " AND ");
1568             }
1569
1570             char* subpred = searchWHERE( node->item, meta, opjoin_type );
1571             buffer_fadd(sql_buf, "( %s )", subpred);
1572             free(subpred);
1573         }
1574         jsonObjectIteratorFree(search_itr);
1575
1576     } else if ( search_hash->type == JSON_HASH ) {
1577         jsonObjectIterator* search_itr = jsonNewObjectIterator( search_hash );
1578         while ( (node = jsonObjectIteratorNext( search_itr )) ) {
1579
1580             if (first) {
1581                 first = 0;
1582             } else {
1583                 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
1584                 else buffer_add(sql_buf, " AND ");
1585             }
1586
1587             if ( !strncmp("+",node->key,1) ) {
1588                 if ( node->item->type == JSON_STRING ) {
1589                     char* subpred = jsonObjectToSimpleString( node->item );
1590                     buffer_fadd(sql_buf, " \"%s\".%s ", node->key + 1, subpred);
1591                     free(subpred);
1592                 } else {
1593                     char* subpred = searchWHERE( node->item, osrfHashGet( oilsIDL(), node->key + 1 ), AND_OP_JOIN );
1594                     buffer_fadd(sql_buf, "( %s )", subpred);
1595                     free(subpred);
1596                 }
1597             } else if ( !strcasecmp("-or",node->key) ) {
1598                 char* subpred = searchWHERE( node->item, meta, OR_OP_JOIN );
1599                 buffer_fadd(sql_buf, "( %s )", subpred);
1600                 free(subpred);
1601             } else if ( !strcasecmp("-and",node->key) ) {
1602                 char* subpred = searchWHERE( node->item, meta, AND_OP_JOIN );
1603                 buffer_fadd(sql_buf, "( %s )", subpred);
1604                 free(subpred);
1605             } else {
1606
1607                 char* class = osrfHashGet(meta, "classname");
1608                 osrfHash* fields = osrfHashGet(meta, "fields");
1609                 osrfHash* field = osrfHashGet( fields, node->key );
1610
1611
1612                 if (!field) {
1613                     char* table = getSourceDefinition(meta);
1614                     osrfLogError(
1615                         OSRF_LOG_MARK,
1616                         "%s: Attempt to reference non-existant column %s on %s (%s)",
1617                         MODULENAME,
1618                         node->key,
1619                         table,
1620                         class
1621                     );
1622                     buffer_free(sql_buf);
1623                     free(table);
1624                     return NULL;
1625                 }
1626
1627                 char* subpred = searchPredicate( class, field, node->item );
1628                 buffer_add( sql_buf, subpred );
1629                 free(subpred);
1630             }
1631         }
1632             jsonObjectIteratorFree(search_itr);
1633
1634     } else {
1635         // ERROR ... only hash and array allowed at this level
1636         char* predicate_string = jsonObjectToJSON( search_hash );
1637         osrfLogError(
1638             OSRF_LOG_MARK,
1639             "%s: Invalid predicate structure: %s",
1640             MODULENAME,
1641             predicate_string
1642         );
1643         buffer_free(sql_buf);
1644         free(predicate_string);
1645         return NULL;
1646     }
1647
1648
1649         return buffer_release(sql_buf);
1650 }
1651
1652 static char* SELECT (
1653                 /* method context */ osrfMethodContext* ctx,
1654                 
1655                 /* SELECT   */ jsonObject* selhash,
1656                 /* FROM     */ jsonObject* join_hash,
1657                 /* WHERE    */ jsonObject* search_hash,
1658                 /* HAVING   */ jsonObject* having_hash,
1659                 /* ORDER BY */ jsonObject* order_hash,
1660                 /* LIMIT    */ jsonObject* limit,
1661                 /* OFFSET   */ jsonObject* offset,
1662                 /* flags    */ int flags
1663 ) {
1664         const char* locale = osrf_message_get_last_locale();
1665
1666         // in case we don't get a select list
1667         jsonObject* defaultselhash = NULL;
1668
1669         // general tmp objects
1670         const jsonObject* tmp_const;
1671         jsonObject* _tmp = NULL;
1672         jsonObjectNode* selclass = NULL;
1673         jsonObjectNode* selfield = NULL;
1674         jsonObjectNode* snode = NULL;
1675         jsonObjectNode* onode = NULL;
1676         jsonObject* found = NULL;
1677
1678         char* string = NULL;
1679         int first = 1;
1680         int gfirst = 1;
1681         //int hfirst = 1;
1682
1683         // the core search class
1684         char* core_class = NULL;
1685
1686         // metadata about the core search class
1687         osrfHash* core_meta = NULL;
1688         osrfHash* core_fields = NULL;
1689         osrfHash* idlClass = NULL;
1690
1691         // punt if there's no core class
1692         if (!join_hash || ( join_hash->type == JSON_HASH && !join_hash->size ))
1693                 return NULL;
1694
1695         // get the core class -- the only key of the top level FROM clause, or a string
1696         if (join_hash->type == JSON_HASH) {
1697                 jsonObjectIterator* tmp_itr = jsonNewObjectIterator( join_hash );
1698                 snode = jsonObjectIteratorNext( tmp_itr );
1699                 
1700                 core_class = strdup( snode->key );
1701                 join_hash = snode->item;
1702
1703                 jsonObjectIteratorFree( tmp_itr );
1704                 snode = NULL;
1705
1706         } else if (join_hash->type == JSON_STRING) {
1707                 core_class = jsonObjectToSimpleString( join_hash );
1708                 join_hash = NULL;
1709         }
1710
1711         // punt if we don't know about the core class
1712         if (!(core_meta = osrfHashGet( oilsIDL(), core_class ))) {
1713                 free(core_class);
1714                 return NULL;
1715         }
1716
1717         // if the select list is empty, or the core class field list is '*',
1718         // build the default select list ...
1719         if (!selhash) {
1720                 selhash = defaultselhash = jsonParseString( "{}" );
1721                 jsonObjectSetKey( selhash, core_class, jsonParseString( "[]" ) );
1722         } else if ( (tmp_const = jsonObjectGetKeyConst( selhash, core_class )) && tmp_const->type == JSON_STRING ) {
1723                 char* _x = jsonObjectToSimpleString( tmp_const );
1724                 if (!strncmp( "*", _x, 1 )) {
1725                         jsonObjectRemoveKey( selhash, core_class );
1726                         jsonObjectSetKey( selhash, core_class, jsonParseString( "[]" ) );
1727                 }
1728                 free(_x);
1729         }
1730
1731         // the query buffer
1732         growing_buffer* sql_buf = buffer_init(128);
1733
1734         // temp buffer for the SELECT list
1735         growing_buffer* select_buf = buffer_init(128);
1736         growing_buffer* order_buf = buffer_init(128);
1737         growing_buffer* group_buf = buffer_init(128);
1738         growing_buffer* having_buf = buffer_init(128);
1739
1740         core_fields = osrfHashGet(core_meta, "fields");
1741
1742         // ... and if we /are/ building the default list, do that
1743         if ( (_tmp = jsonObjectGetKey(selhash,core_class)) && !_tmp->size ) {
1744                 
1745                 int i = 0;
1746                 char* field;
1747
1748                 osrfStringArray* keys = osrfHashKeys( core_fields );
1749                 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
1750                         if ( strncasecmp( "true", osrfHashGet( osrfHashGet( core_fields, field ), "virtual" ), 4 ) )
1751                                 jsonObjectPush( _tmp, jsonNewObject( field ) );
1752                 }
1753                 osrfStringArrayFree(keys);
1754         }
1755
1756         // Now we build the actual select list
1757         int sel_pos = 1;
1758         jsonObject* is_agg = jsonObjectFindPath(selhash, "//aggregate");
1759         first = 1;
1760         gfirst = 1;
1761         jsonObjectIterator* selclass_itr = jsonNewObjectIterator( selhash );
1762         while ( (selclass = jsonObjectIteratorNext( selclass_itr )) ) {
1763
1764                 // round trip through the idl, just to be safe
1765                 idlClass = osrfHashGet( oilsIDL(), selclass->key );
1766                 if (!idlClass) continue;
1767                 char* cname = osrfHashGet(idlClass, "classname");
1768
1769                 // make sure the target relation is in the join tree
1770                 if (strcmp(core_class,cname)) {
1771                         if (!join_hash) continue;
1772
1773                         if (join_hash->type == JSON_STRING) {
1774                                 string = jsonObjectToSimpleString(join_hash);
1775                                 found = strcmp(string,cname) ? NULL : jsonParseString("{\"1\":\"1\"}");
1776                                 free(string);
1777                         } else {
1778                                 found = jsonObjectFindPath(join_hash, "//%s", cname);
1779                         }
1780
1781                         if (!found->size) {
1782                                 jsonObjectFree(found);
1783                                 continue;
1784                         }
1785
1786                         jsonObjectFree(found);
1787                 }
1788
1789                 // stitch together the column list ...
1790                 jsonObjectIterator* select_itr = jsonNewObjectIterator( selclass->item );
1791                 while ( (selfield = jsonObjectIteratorNext( select_itr )) ) {
1792
1793                         char* __column = NULL;
1794                         char* __alias = NULL;
1795
1796                         // ... if it's a sstring, just toss it on the pile
1797                         if (selfield->item->type == JSON_STRING) {
1798
1799                                 // again, just to be safe
1800                                 char* _requested_col = jsonObjectToSimpleString(selfield->item);
1801                                 osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), _requested_col );
1802                                 free(_requested_col);
1803
1804                                 if (!field) continue;
1805                                 __column = strdup(osrfHashGet(field, "name"));
1806
1807                                 if (first) {
1808                                         first = 0;
1809                                 } else {
1810                                         buffer_add(select_buf, ",");
1811                                 }
1812
1813                 if (locale) {
1814                         char* i18n = osrfHashGet(field, "i18n");
1815                                 if (flags & DISABLE_I18N)
1816                         i18n = NULL;
1817
1818                         if ( i18n && !strncasecmp("true", i18n, 4)) {
1819                             char* pkey = osrfHashGet(idlClass, "primarykey");
1820                             char* tname = osrfHashGet(idlClass, "tablename");
1821
1822                         buffer_fadd(select_buf, " oils_i18n_xlate('%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"", tname, __column, pkey, cname, pkey, locale, __column);
1823                     } else {
1824                                         buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, __column, __column);
1825                     }
1826                 } else {
1827                                     buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, __column, __column);
1828                 }
1829
1830                         // ... but it could be an object, in which case we check for a Field Transform
1831                         } else {
1832
1833                                 __column = jsonObjectToSimpleString( jsonObjectGetKeyConst( selfield->item, "column" ) );
1834
1835                                 // again, just to be safe
1836                                 osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), __column );
1837                                 if (!field) continue;
1838                                 const char* fname = osrfHashGet(field, "name");
1839
1840                                 if (first) {
1841                                         first = 0;
1842                                 } else {
1843                                         buffer_add(select_buf, ",");
1844                                 }
1845
1846                                 if ((tmp_const = jsonObjectGetKeyConst( selfield->item, "alias" ))) {
1847                                         __alias = jsonObjectToSimpleString( tmp_const );
1848                                 } else {
1849                                         __alias = strdup(__column);
1850                                 }
1851
1852                                 if (jsonObjectGetKeyConst( selfield->item, "transform" )) {
1853                                         free(__column);
1854                                         __column = searchFieldTransform(cname, field, selfield->item);
1855                                         buffer_fadd(select_buf, " %s AS \"%s\"", __column, __alias);
1856                                 } else {
1857                     if (locale) {
1858                                 char* i18n = osrfHashGet(field, "i18n");
1859                                     if (flags & DISABLE_I18N)
1860                             i18n = NULL;
1861
1862                                 if ( i18n && !strncasecmp("true", i18n, 4)) {
1863                                 char* pkey = osrfHashGet(idlClass, "primarykey");
1864                                 char* tname = osrfHashGet(idlClass, "tablename");
1865
1866                             buffer_fadd(select_buf, " oils_i18n_xlate('%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"", tname, fname, pkey, cname, pkey, locale, __alias);
1867                         } else {
1868                                                 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, fname, __alias);
1869                         }
1870                     } else {
1871                                             buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, fname, __alias);
1872                     }
1873                                 }
1874                         }
1875
1876                         if (is_agg->size || (flags & SELECT_DISTINCT)) {
1877
1878                                 if (!jsonBoolIsTrue( jsonObjectGetKey( selfield->item, "aggregate" ) )) {
1879                                         if (gfirst) {
1880                                                 gfirst = 0;
1881                                         } else {
1882                                                 buffer_add(group_buf, ",");
1883                                         }
1884
1885                                         buffer_fadd(group_buf, " %d", sel_pos);
1886                                 /*
1887                                 } else if (is_agg = jsonObjectGetKey( selfield->item, "having" )) {
1888                                         if (gfirst) {
1889                                                 gfirst = 0;
1890                                         } else {
1891                                                 buffer_add(group_buf, ",");
1892                                         }
1893
1894                                         __column = searchFieldTransform(cname, field, selfield->item);
1895                                         buffer_fadd(group_buf, " %s", __column);
1896                                         __column = searchFieldTransform(cname, field, selfield->item);
1897                                 */
1898                                 }
1899                         }
1900
1901                         if (__column) free(__column);
1902                         if (__alias) free(__alias);
1903
1904                         sel_pos++;
1905                 }
1906
1907         // jsonObjectIteratorFree(select_itr);
1908         }
1909
1910     // jsonObjectIteratorFree(selclass_itr);
1911
1912         if (is_agg) jsonObjectFree(is_agg);
1913
1914         char* col_list = buffer_release(select_buf);
1915         char* table = getSourceDefinition(core_meta);
1916
1917         // Put it all together
1918         buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\" ", col_list, table, core_class );
1919         free(col_list);
1920         free(table);
1921
1922         // Now, walk the join tree and add that clause
1923         if ( join_hash ) {
1924                 char* join_clause = searchJOIN( join_hash, core_meta );
1925                 buffer_add(sql_buf, join_clause);
1926                 free(join_clause);
1927         }
1928
1929         if ( search_hash ) {
1930                 buffer_add(sql_buf, " WHERE ");
1931
1932                 // and it's on the the WHERE clause
1933                 char* pred = searchWHERE( search_hash, core_meta, AND_OP_JOIN );
1934
1935                 if (!pred) {
1936                         osrfAppSessionStatus(
1937                                 ctx->session,
1938                                 OSRF_STATUS_INTERNALSERVERERROR,
1939                                 "osrfMethodException",
1940                                 ctx->request,
1941                                 "Severe query error in WHERE predicate -- see error log for more details"
1942                         );
1943                         free(core_class);
1944                         buffer_free(having_buf);
1945                         buffer_free(group_buf);
1946                         buffer_free(order_buf);
1947                         buffer_free(sql_buf);
1948                         if (defaultselhash) jsonObjectFree(defaultselhash);
1949                         return NULL;
1950                 } else {
1951                         buffer_add(sql_buf, pred);
1952                         free(pred);
1953                 }
1954     }
1955
1956         if ( having_hash ) {
1957                 buffer_add(sql_buf, " HAVING ");
1958
1959                 // and it's on the the WHERE clause
1960                 char* pred = searchWHERE( having_hash, core_meta, AND_OP_JOIN );
1961
1962                 if (!pred) {
1963                         osrfAppSessionStatus(
1964                                 ctx->session,
1965                                 OSRF_STATUS_INTERNALSERVERERROR,
1966                                 "osrfMethodException",
1967                                 ctx->request,
1968                                 "Severe query error in HAVING predicate -- see error log for more details"
1969                         );
1970                         free(core_class);
1971                         buffer_free(having_buf);
1972                         buffer_free(group_buf);
1973                         buffer_free(order_buf);
1974                         buffer_free(sql_buf);
1975                         if (defaultselhash) jsonObjectFree(defaultselhash);
1976                         return NULL;
1977                 } else {
1978                         buffer_add(sql_buf, pred);
1979                         free(pred);
1980                 }
1981         }
1982
1983         first = 1;
1984         jsonObjectIterator* class_itr = jsonNewObjectIterator( order_hash );
1985         while ( (snode = jsonObjectIteratorNext( class_itr )) ) {
1986
1987                 if (!jsonObjectGetKeyConst(selhash,snode->key))
1988                         continue;
1989
1990                 if ( snode->item->type == JSON_HASH ) {
1991
1992                     jsonObjectIterator* order_itr = jsonNewObjectIterator( snode->item );
1993                         while ( (onode = jsonObjectIteratorNext( order_itr )) ) {
1994
1995                                 if (!oilsIDLFindPath( "/%s/fields/%s", snode->key, onode->key ))
1996                                         continue;
1997
1998                                 char* direction = NULL;
1999                                 if ( onode->item->type == JSON_HASH ) {
2000                                         if ( jsonObjectGetKeyConst( onode->item, "transform" ) ) {
2001                                                 string = searchFieldTransform(
2002                                                         snode->key,
2003                                                         oilsIDLFindPath( "/%s/fields/%s", snode->key, onode->key ),
2004                                                         onode->item
2005                                                 );
2006                                         } else {
2007                                                 growing_buffer* field_buf = buffer_init(16);
2008                                                 buffer_fadd(field_buf, "\"%s\".%s", snode->key, onode->key);
2009                                                 string = buffer_release(field_buf);
2010                                         }
2011
2012                                         if ( (tmp_const = jsonObjectGetKeyConst( onode->item, "direction" )) ) {
2013                                                 direction = jsonObjectToSimpleString(tmp_const);
2014                                                 if (!strncasecmp(direction, "d", 1)) {
2015                                                         free(direction);
2016                                                         direction = " DESC";
2017                                                 } else {
2018                                                         free(direction);
2019                                                         direction = " ASC";
2020                                                 }
2021                                         }
2022
2023                                 } else {
2024                                         string = strdup(onode->key);
2025                                         direction = jsonObjectToSimpleString(onode->item);
2026                                         if (!strncasecmp(direction, "d", 1)) {
2027                                                 free(direction);
2028                                                 direction = " DESC";
2029                                         } else {
2030                                                 free(direction);
2031                                                 direction = " ASC";
2032                                         }
2033                                 }
2034
2035                                 if (first) {
2036                                         first = 0;
2037                                 } else {
2038                                         buffer_add(order_buf, ", ");
2039                                 }
2040
2041                                 buffer_add(order_buf, string);
2042                                 free(string);
2043
2044                                 if (direction) {
2045                                         buffer_add(order_buf, direction);
2046                                 }
2047
2048                         }
2049             // jsonObjectIteratorFree(order_itr);
2050
2051                 } else if ( snode->item->type == JSON_ARRAY ) {
2052
2053                     jsonObjectIterator* order_itr = jsonNewObjectIterator( snode->item );
2054                         while ( (onode = jsonObjectIteratorNext( order_itr )) ) {
2055
2056                                 char* _f = jsonObjectToSimpleString( onode->item );
2057
2058                                 if (!oilsIDLFindPath( "/%s/fields/%s", snode->key, _f))
2059                                         continue;
2060
2061                                 if (first) {
2062                                         first = 0;
2063                                 } else {
2064                                         buffer_add(order_buf, ", ");
2065                                 }
2066
2067                                 buffer_add(order_buf, _f);
2068                                 free(_f);
2069
2070                         }
2071             // jsonObjectIteratorFree(order_itr);
2072
2073
2074                 // IT'S THE OOOOOOOOOOOLD STYLE!
2075                 } else {
2076                         osrfLogError(OSRF_LOG_MARK, "%s: Possible SQL injection attempt; direct order by is not allowed", MODULENAME);
2077                         osrfAppSessionStatus(
2078                                 ctx->session,
2079                                 OSRF_STATUS_INTERNALSERVERERROR,
2080                                 "osrfMethodException",
2081                                 ctx->request,
2082                                 "Severe query error -- see error log for more details"
2083                         );
2084
2085                         free(core_class);
2086                         buffer_free(having_buf);
2087                         buffer_free(group_buf);
2088                         buffer_free(order_buf);
2089                         buffer_free(sql_buf);
2090                         if (defaultselhash) jsonObjectFree(defaultselhash);
2091                         return NULL;
2092                 }
2093
2094         }
2095
2096     // jsonObjectIteratorFree(class_itr);
2097
2098         string = buffer_release(group_buf);
2099
2100         if (strlen(string)) {
2101                 buffer_fadd(
2102                         sql_buf,
2103                         " GROUP BY %s",
2104                         string
2105                 );
2106         }
2107
2108         free(string);
2109
2110         string = buffer_release(having_buf);
2111  
2112         if (strlen(string)) {
2113                 buffer_fadd(
2114                         sql_buf,
2115                         " HAVING %s",
2116                         string
2117                 );
2118         }
2119
2120         free(string);
2121
2122         string = buffer_release(order_buf);
2123
2124         if (strlen(string)) {
2125                 buffer_fadd(
2126                         sql_buf,
2127                         " ORDER BY %s",
2128                         string
2129                 );
2130         }
2131
2132         free(string);
2133
2134         if ( limit ){
2135                 string = jsonObjectToSimpleString(limit);
2136                 buffer_fadd( sql_buf, " LIMIT %d", atoi(string) );
2137                 free(string);
2138         }
2139
2140         if (offset) {
2141                 string = jsonObjectToSimpleString(offset);
2142                 buffer_fadd( sql_buf, " OFFSET %d", atoi(string) );
2143                 free(string);
2144         }
2145
2146         buffer_add(sql_buf, ";");
2147
2148         free(core_class);
2149         if (defaultselhash) jsonObjectFree(defaultselhash);
2150
2151         return buffer_release(sql_buf);
2152
2153 }
2154
2155 static char* buildSELECT ( jsonObject* search_hash, jsonObject* order_hash, osrfHash* meta, osrfMethodContext* ctx ) {
2156
2157         const char* locale = osrf_message_get_last_locale();
2158
2159         osrfHash* fields = osrfHashGet(meta, "fields");
2160         char* core_class = osrfHashGet(meta, "classname");
2161
2162         const jsonObject* join_hash = jsonObjectGetKeyConst( order_hash, "join" );
2163
2164         jsonObjectNode* node = NULL;
2165         jsonObjectNode* snode = NULL;
2166         jsonObjectNode* onode = NULL;
2167         const jsonObject* _tmp = NULL;
2168         jsonObject* selhash = NULL;
2169         jsonObject* defaultselhash = NULL;
2170
2171         growing_buffer* sql_buf = buffer_init(128);
2172         growing_buffer* select_buf = buffer_init(128);
2173
2174         if ( !(selhash = jsonObjectGetKey( order_hash, "select" )) ) {
2175                 defaultselhash = jsonParseString( "{}" );
2176                 selhash = defaultselhash;
2177         }
2178         
2179         if ( !jsonObjectGetKeyConst(selhash,core_class) ) {
2180                 jsonObjectSetKey( selhash, core_class, jsonParseString( "[]" ) );
2181                 jsonObject* flist = jsonObjectGetKey( selhash, core_class );
2182                 
2183                 int i = 0;
2184                 char* field;
2185
2186                 osrfStringArray* keys = osrfHashKeys( fields );
2187                 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
2188                         if ( strcasecmp( "true", osrfHashGet( osrfHashGet( fields, field ), "virtual" ) ) )
2189                                 jsonObjectPush( flist, jsonNewObject( field ) );
2190                 }
2191                 osrfStringArrayFree(keys);
2192         }
2193
2194         int first = 1;
2195         jsonObjectIterator* class_itr = jsonNewObjectIterator( selhash );
2196         while ( (snode = jsonObjectIteratorNext( class_itr )) ) {
2197
2198                 osrfHash* idlClass = osrfHashGet( oilsIDL(), snode->key );
2199                 if (!idlClass) continue;
2200                 char* cname = osrfHashGet(idlClass, "classname");
2201
2202                 if (strcmp(core_class,snode->key)) {
2203                         if (!join_hash) continue;
2204
2205                         jsonObject* found =  jsonObjectFindPath(join_hash, "//%s", snode->key);
2206                         if (!found->size) {
2207                                 jsonObjectFree(found);
2208                                 continue;
2209                         }
2210
2211                         jsonObjectFree(found);
2212                 }
2213
2214                 jsonObjectIterator* select_itr = jsonNewObjectIterator( snode->item );
2215                 while ( (node = jsonObjectIteratorNext( select_itr )) ) {
2216                         osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), jsonObjectToSimpleString(node->item) );
2217                         char* fname = osrfHashGet(field, "name");
2218
2219                         if (!field) continue;
2220
2221                         if (first) {
2222                                 first = 0;
2223                         } else {
2224                                 buffer_add(select_buf, ",");
2225                         }
2226
2227             if (locale) {
2228                         char* i18n = osrfHashGet(field, "i18n");
2229                     if (jsonBoolIsTrue(jsonObjectGetKey( order_hash, "no_i18n" )))
2230                     i18n = NULL;
2231
2232                         if ( i18n && !strncasecmp("true", i18n, 4)) {
2233                         char* pkey = osrfHashGet(idlClass, "primarykey");
2234                         char* tname = osrfHashGet(idlClass, "tablename");
2235
2236                     buffer_fadd(select_buf, " oils_i18n_xlate('%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"", tname, fname, pkey, cname, pkey, locale, fname);
2237                 } else {
2238                                 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
2239                 }
2240             } else {
2241                             buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
2242             }
2243                 }
2244
2245         jsonObjectIteratorFree(select_itr);
2246         }
2247
2248     jsonObjectIteratorFree(class_itr);
2249
2250         char* col_list = buffer_release(select_buf);
2251         char* table = getSourceDefinition(meta);
2252
2253         buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\"", col_list, table, core_class );
2254         free(col_list);
2255         free(table);
2256
2257         if ( join_hash ) {
2258                 char* join_clause = searchJOIN( join_hash, meta );
2259                 buffer_fadd(sql_buf, " %s", join_clause);
2260                 free(join_clause);
2261         }
2262
2263         char* tmpsql = buffer_data(sql_buf);
2264         osrfLogDebug(OSRF_LOG_MARK, "%s pre-predicate SQL =  %s", MODULENAME, tmpsql);
2265         free(tmpsql);
2266
2267         buffer_add(sql_buf, " WHERE ");
2268
2269         char* pred = searchWHERE( search_hash, meta, AND_OP_JOIN );
2270         if (!pred) {
2271                 osrfAppSessionStatus(
2272                         ctx->session,
2273                         OSRF_STATUS_INTERNALSERVERERROR,
2274                                 "osrfMethodException",
2275                                 ctx->request,
2276                                 "Severe query error -- see error log for more details"
2277                         );
2278                 buffer_free(sql_buf);
2279                 return NULL;
2280         } else {
2281                 buffer_add(sql_buf, pred);
2282                 free(pred);
2283         }
2284
2285         if (order_hash) {
2286                 char* string = NULL;
2287                 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "order_by" )) ){
2288
2289                         growing_buffer* order_buf = buffer_init(128);
2290
2291                         first = 1;
2292                         jsonObjectIterator* class_itr = jsonNewObjectIterator( _tmp );
2293                         while ( (snode = jsonObjectIteratorNext( class_itr )) ) {
2294
2295                                 if (!jsonObjectGetKeyConst(selhash,snode->key))
2296                                         continue;
2297
2298                                 if ( snode->item->type == JSON_HASH ) {
2299
2300                                         jsonObjectIterator* order_itr = jsonNewObjectIterator( snode->item );
2301                                         while ( (onode = jsonObjectIteratorNext( order_itr )) ) {
2302
2303                                                 if (!oilsIDLFindPath( "/%s/fields/%s", snode->key, onode->key ))
2304                                                         continue;
2305
2306                                                 char* direction = NULL;
2307                                                 if ( onode->item->type == JSON_HASH ) {
2308                                                         if ( jsonObjectGetKeyConst( onode->item, "transform" ) ) {
2309                                                                 string = searchFieldTransform(
2310                                                                         snode->key,
2311                                                                         oilsIDLFindPath( "/%s/fields/%s", snode->key, onode->key ),
2312                                                                         onode->item
2313                                                                 );
2314                                                         } else {
2315                                                                 growing_buffer* field_buf = buffer_init(16);
2316                                                                 buffer_fadd(field_buf, "\"%s\".%s", snode->key, onode->key);
2317                                                                 string = buffer_release(field_buf);
2318                                                         }
2319
2320                                                         if ( (_tmp = jsonObjectGetKeyConst( onode->item, "direction" )) ) {
2321                                                                 direction = jsonObjectToSimpleString(_tmp);
2322                                                                 if (!strncasecmp(direction, "d", 1)) {
2323                                                                         free(direction);
2324                                                                         direction = " DESC";
2325                                                                 } else {
2326                                                                         free(direction);
2327                                                                         direction = " ASC";
2328                                                                 }
2329                                                         }
2330
2331                                                 } else {
2332                                                         string = strdup(onode->key);
2333                                                         direction = jsonObjectToSimpleString(onode->item);
2334                                                         if (!strncasecmp(direction, "d", 1)) {
2335                                                                 free(direction);
2336                                                                 direction = " DESC";
2337                                                         } else {
2338                                                                 free(direction);
2339                                                                 direction = " ASC";
2340                                                         }
2341                                                 }
2342
2343                                                 if (first) {
2344                                                         first = 0;
2345                                                 } else {
2346                                                         buffer_add(order_buf, ", ");
2347                                                 }
2348
2349                                                 buffer_add(order_buf, string);
2350                                                 free(string);
2351
2352                                                 if (direction) {
2353                                                         buffer_add(order_buf, direction);
2354                                                 }
2355
2356                                         }
2357
2358                     jsonObjectIteratorFree(order_itr);
2359
2360                                 } else {
2361                                         string = jsonObjectToSimpleString(snode->item);
2362                                         buffer_add(order_buf, string);
2363                                         free(string);
2364                                         break;
2365                                 }
2366
2367                         }
2368
2369             jsonObjectIteratorFree(class_itr);
2370
2371                         string = buffer_release(order_buf);
2372
2373                         if (strlen(string)) {
2374                                 buffer_fadd(
2375                                         sql_buf,
2376                                         " ORDER BY %s",
2377                                         string
2378                                 );
2379                         }
2380
2381                         free(string);
2382                 }
2383
2384                 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "limit" )) ){
2385                         string = jsonObjectToSimpleString(_tmp);
2386                         buffer_fadd(
2387                                 sql_buf,
2388                                 " LIMIT %d",
2389                                 atoi(string)
2390                         );
2391                         free(string);
2392                 }
2393
2394                 _tmp = jsonObjectGetKeyConst( order_hash, "offset" );
2395                 if (_tmp) {
2396                         string = jsonObjectToSimpleString(_tmp);
2397                         buffer_fadd(
2398                                 sql_buf,
2399                                 " OFFSET %d",
2400                                 atoi(string)
2401                         );
2402                         free(string);
2403                 }
2404         }
2405
2406         if (defaultselhash) jsonObjectFree(defaultselhash);
2407
2408         buffer_add(sql_buf, ";");
2409         return buffer_release(sql_buf);
2410 }
2411
2412 int doJSONSearch ( osrfMethodContext* ctx ) {
2413         OSRF_METHOD_VERIFY_CONTEXT(ctx);
2414         osrfLogDebug(OSRF_LOG_MARK, "Recieved query request");
2415
2416         int err = 0;
2417
2418         // XXX for now...
2419         dbhandle = writehandle;
2420
2421         jsonObject* hash = jsonObjectGetIndex(ctx->params, 0);
2422
2423     int flags = 0;
2424
2425         if (jsonBoolIsTrue(jsonObjectGetKey( hash, "distinct" )))
2426          flags |= SELECT_DISTINCT;
2427
2428         if ( ((int)jsonObjectGetNumber(jsonObjectGetKey( hash, "distinct" ))) == 1 ) // support 1/0 for perl's sake
2429          flags |= SELECT_DISTINCT;
2430
2431         if (jsonBoolIsTrue(jsonObjectGetKey( hash, "no_i18n" )))
2432          flags |= DISABLE_I18N;
2433
2434         if ( ((int)jsonObjectGetNumber(jsonObjectGetKey( hash, "no_i18n" ))) == 1 ) // support 1/0 for perl's sake
2435          flags |= DISABLE_I18N;
2436
2437         osrfLogDebug(OSRF_LOG_MARK, "Building SQL ...");
2438         char* sql = SELECT(
2439                         ctx,
2440                         jsonObjectGetKey( hash, "select" ),
2441                         jsonObjectGetKey( hash, "from" ),
2442                         jsonObjectGetKey( hash, "where" ),
2443                         jsonObjectGetKey( hash, "having" ),
2444                         jsonObjectGetKey( hash, "order_by" ),
2445                         jsonObjectGetKey( hash, "limit" ),
2446                         jsonObjectGetKey( hash, "offset" ),
2447                         flags
2448         );
2449
2450         if (!sql) {
2451                 err = -1;
2452                 return err;
2453         }
2454         
2455         osrfLogDebug(OSRF_LOG_MARK, "%s SQL =  %s", MODULENAME, sql);
2456         dbi_result result = dbi_conn_query(dbhandle, sql);
2457
2458         if(result) {
2459                 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
2460
2461                 if (dbi_result_first_row(result)) {
2462                         /* JSONify the result */
2463                         osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
2464
2465                         do {
2466                                 jsonObject* return_val = oilsMakeJSONFromResult( result );
2467                                 osrfAppRespond( ctx, return_val );
2468                 jsonObjectFree( return_val );
2469                         } while (dbi_result_next_row(result));
2470
2471                 } else {
2472                         osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
2473                 }
2474
2475                 osrfAppRespondComplete( ctx, NULL );
2476
2477                 /* clean up the query */
2478                 dbi_result_free(result); 
2479
2480         } else {
2481                 err = -1;
2482                 osrfLogError(OSRF_LOG_MARK, "%s: Error with query [%s]", MODULENAME, sql);
2483                 osrfAppSessionStatus(
2484                         ctx->session,
2485                         OSRF_STATUS_INTERNALSERVERERROR,
2486                         "osrfMethodException",
2487                         ctx->request,
2488                         "Severe query error -- see error log for more details"
2489                 );
2490         }
2491
2492         free(sql);
2493         return err;
2494 }
2495
2496 static jsonObject* doFieldmapperSearch ( osrfMethodContext* ctx, osrfHash* meta,
2497                 const jsonObject* params, int* err ) {
2498
2499         // XXX for now...
2500         dbhandle = writehandle;
2501
2502         osrfHash* links = osrfHashGet(meta, "links");
2503         osrfHash* fields = osrfHashGet(meta, "fields");
2504         char* core_class = osrfHashGet(meta, "classname");
2505         char* pkey = osrfHashGet(meta, "primarykey");
2506
2507         const jsonObject* _tmp;
2508         jsonObject* obj;
2509         jsonObject* search_hash = jsonObjectGetIndex(params, 0);
2510         jsonObject* order_hash = jsonObjectGetIndex(params, 1);
2511
2512         char* sql = buildSELECT( search_hash, order_hash, meta, ctx );
2513         if (!sql) {
2514                 *err = -1;
2515                 return NULL;
2516         }
2517         
2518         osrfLogDebug(OSRF_LOG_MARK, "%s SQL =  %s", MODULENAME, sql);
2519         dbi_result result = dbi_conn_query(dbhandle, sql);
2520
2521         osrfHash* dedup = osrfNewHash();
2522         jsonObject* res_list = jsonParseString("[]");
2523         if(result) {
2524                 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
2525
2526                 if (dbi_result_first_row(result)) {
2527                         /* JSONify the result */
2528                         osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
2529                         do {
2530                                 obj = oilsMakeFieldmapperFromResult( result, meta );
2531                                 int pkey_pos = atoi( osrfHashGet( osrfHashGet( fields, pkey ), "array_position" ) );
2532                                 char* pkey_val = jsonObjectToSimpleString( jsonObjectGetIndex( obj, pkey_pos ) );
2533                                 if ( osrfHashGet( dedup, pkey_val ) ) {
2534                                         jsonObjectFree(obj);
2535                                 } else {
2536                                         osrfHashSet( dedup, pkey_val, pkey_val );
2537                                         jsonObjectPush(res_list, obj);
2538                                 }
2539                         } while (dbi_result_next_row(result));
2540                 } else {
2541                         osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
2542                 }
2543
2544                 /* clean up the query */
2545                 dbi_result_free(result); 
2546
2547         } else {
2548                 osrfLogError(OSRF_LOG_MARK, "%s: Error retrieving %s with query [%s]", MODULENAME, osrfHashGet(meta, "fieldmapper"), sql);
2549                 osrfAppSessionStatus(
2550                         ctx->session,
2551                         OSRF_STATUS_INTERNALSERVERERROR,
2552                         "osrfMethodException",
2553                         ctx->request,
2554                         "Severe query error -- see error log for more details"
2555                 );
2556                 *err = -1;
2557                 free(sql);
2558                 jsonObjectFree(res_list);
2559                 osrfHashFree(dedup);
2560                 return jsonNULL;
2561
2562         }
2563
2564         osrfHashFree(dedup);
2565         free(sql);
2566
2567         if (res_list->size && order_hash) {
2568                 _tmp = jsonObjectGetKeyConst( order_hash, "flesh" );
2569                 if (_tmp) {
2570                         int x = (int)jsonObjectGetNumber(_tmp);
2571                         if (x == -1 || x > max_flesh_depth) x = max_flesh_depth;
2572
2573                         const jsonObject* temp_blob;
2574                         if ((temp_blob = jsonObjectGetKeyConst( order_hash, "flesh_fields" )) && x > 0) {
2575
2576                                 jsonObject* flesh_blob = jsonObjectClone( temp_blob );
2577                                 const jsonObject* flesh_fields = jsonObjectGetKeyConst( flesh_blob, core_class );
2578
2579                                 osrfStringArray* link_fields = NULL;
2580
2581                                 if (flesh_fields) {
2582                                         if (flesh_fields->size == 1) {
2583                                                 char* _t = jsonObjectToSimpleString( jsonObjectGetIndex( flesh_fields, 0 ) );
2584                                                 if (!strcmp(_t,"*")) link_fields = osrfHashKeys( links );
2585                                                 free(_t);
2586                                         }
2587
2588                                         if (!link_fields) {
2589                                                 jsonObjectNode* _f;
2590                                                 link_fields = osrfNewStringArray(1);
2591                                                 jsonObjectIterator* _i = jsonNewObjectIterator( flesh_fields );
2592                                                 while ((_f = jsonObjectIteratorNext( _i ))) {
2593                                                         osrfStringArrayAdd( link_fields, jsonObjectToSimpleString( _f->item ) );
2594                                                 }
2595                         jsonObjectIteratorFree(_i);
2596                                         }
2597                                 }
2598
2599                                 jsonObjectNode* cur;
2600                                 jsonObjectIterator* itr = jsonNewObjectIterator( res_list );
2601                                 while ((cur = jsonObjectIteratorNext( itr ))) {
2602
2603                                         int i = 0;
2604                                         char* link_field;
2605                                         
2606                                         while ( (link_field = osrfStringArrayGetString(link_fields, i++)) ) {
2607
2608                                                 osrfLogDebug(OSRF_LOG_MARK, "Starting to flesh %s", link_field);
2609
2610                                                 osrfHash* kid_link = osrfHashGet(links, link_field);
2611                                                 if (!kid_link) continue;
2612
2613                                                 osrfHash* field = osrfHashGet(fields, link_field);
2614                                                 if (!field) continue;
2615
2616                                                 osrfHash* value_field = field;
2617
2618                                                 osrfHash* kid_idl = osrfHashGet(oilsIDL(), osrfHashGet(kid_link, "class"));
2619                                                 if (!kid_idl) continue;
2620
2621                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
2622                                                         value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
2623                                                 }
2624                                                         
2625                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) { // might_have
2626                                                         value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
2627                                                 }
2628
2629                                                 osrfStringArray* link_map = osrfHashGet( kid_link, "map" );
2630
2631                                                 if (link_map->size > 0) {
2632                                                         jsonObject* _kid_key = jsonParseString("[]");
2633                                                         jsonObjectPush(
2634                                                                 _kid_key,
2635                                                                 jsonNewObject( osrfStringArrayGetString( link_map, 0 ) )
2636                                                         );
2637
2638                                                         jsonObjectSetKey(
2639                                                                 flesh_blob,
2640                                                                 osrfHashGet(kid_link, "class"),
2641                                                                 _kid_key
2642                                                         );
2643                                                 };
2644
2645                                                 osrfLogDebug(
2646                                                         OSRF_LOG_MARK,
2647                                                         "Link field: %s, remote class: %s, fkey: %s, reltype: %s",
2648                                                         osrfHashGet(kid_link, "field"),
2649                                                         osrfHashGet(kid_link, "class"),
2650                                                         osrfHashGet(kid_link, "key"),
2651                                                         osrfHashGet(kid_link, "reltype")
2652                                                 );
2653
2654                                                 jsonObject* fake_params = jsonParseString("[]");
2655                                                 jsonObjectPush(fake_params, jsonParseString("{}")); // search hash
2656                                                 jsonObjectPush(fake_params, jsonParseString("{}")); // order/flesh hash
2657
2658                                                 osrfLogDebug(OSRF_LOG_MARK, "Creating dummy params object...");
2659
2660                                                 char* search_key =
2661                                                 jsonObjectToSimpleString(
2662                                                         jsonObjectGetIndex(
2663                                                                 cur->item,
2664                                                                 atoi( osrfHashGet(value_field, "array_position") )
2665                                                         )
2666                                                 );
2667
2668                                                 if (!search_key) {
2669                                                         osrfLogDebug(OSRF_LOG_MARK, "Nothing to search for!");
2670                                                         continue;
2671                                                 }
2672                                                         
2673                                                 jsonObjectSetKey(
2674                                                         jsonObjectGetIndex(fake_params, 0),
2675                                                         osrfHashGet(kid_link, "key"),
2676                                                         jsonNewObject( search_key )
2677                                                 );
2678
2679                                                 free(search_key);
2680
2681
2682                                                 jsonObjectSetKey(
2683                                                         jsonObjectGetIndex(fake_params, 1),
2684                                                         "flesh",
2685                                                         jsonNewNumberObject( (double)(x - 1 + link_map->size) )
2686                                                 );
2687
2688                                                 if (flesh_blob)
2689                                                         jsonObjectSetKey( jsonObjectGetIndex(fake_params, 1), "flesh_fields", jsonObjectClone(flesh_blob) );
2690
2691                                                 if (jsonObjectGetKeyConst(order_hash, "order_by")) {
2692                                                         jsonObjectSetKey(
2693                                                                 jsonObjectGetIndex(fake_params, 1),
2694                                                                 "order_by",
2695                                                                 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "order_by"))
2696                                                         );
2697                                                 }
2698
2699                                                 if (jsonObjectGetKeyConst(order_hash, "select")) {
2700                                                         jsonObjectSetKey(
2701                                                                 jsonObjectGetIndex(fake_params, 1),
2702                                                                 "select",
2703                                                                 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "select"))
2704                                                         );
2705                                                 }
2706
2707                                                 jsonObject* kids = doFieldmapperSearch(ctx, kid_idl, fake_params, err);
2708
2709                                                 if(*err) {
2710                                                         jsonObjectFree( fake_params );
2711                                                         osrfStringArrayFree(link_fields);
2712                                                         jsonObjectIteratorFree(itr);
2713                                                         jsonObjectFree(res_list);
2714                                                         return jsonNULL;
2715                                                 }
2716
2717                                                 osrfLogDebug(OSRF_LOG_MARK, "Search for %s return %d linked objects", osrfHashGet(kid_link, "class"), kids->size);
2718
2719                                                 jsonObject* X = NULL;
2720                                                 if ( link_map->size > 0 && kids->size > 0 ) {
2721                                                         X = kids;
2722                                                         kids = jsonParseString("[]");
2723
2724                                                         jsonObjectNode* _k_node;
2725                                                         jsonObjectIterator* _k = jsonNewObjectIterator( X );
2726                                                         while ((_k_node = jsonObjectIteratorNext( _k ))) {
2727                                                                 jsonObjectPush(
2728                                                                         kids,
2729                                                                         jsonObjectClone(
2730                                                                                 jsonObjectGetIndex(
2731                                                                                         _k_node->item,
2732                                                                                         (unsigned long)atoi(
2733                                                                                                 osrfHashGet(
2734                                                                                                         osrfHashGet(
2735                                                                                                                 osrfHashGet(
2736                                                                                                                         osrfHashGet(
2737                                                                                                                                 oilsIDL(),
2738                                                                                                                                 osrfHashGet(kid_link, "class")
2739                                                                                                                         ),
2740                                                                                                                         "fields"
2741                                                                                                                 ),
2742                                                                                                                 osrfStringArrayGetString( link_map, 0 )
2743                                                                                                         ),
2744                                                                                                         "array_position"
2745                                                                                                 )
2746                                                                                         )
2747                                                                                 )
2748                                                                         )
2749                                                                 );
2750                                                         }
2751                                                 }
2752
2753                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_a" )) || !(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) {
2754                                                         osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
2755                                                         jsonObjectSetIndex(
2756                                                                 cur->item,
2757                                                                 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
2758                                                                 jsonObjectClone( jsonObjectGetIndex(kids, 0) )
2759                                                         );
2760                                                 }
2761
2762                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
2763                                                         osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
2764                                                         jsonObjectSetIndex(
2765                                                                 cur->item,
2766                                                                 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
2767                                                                 jsonObjectClone( kids )
2768                                                         );
2769                                                 }
2770
2771                                                 if (X) {
2772                                                         jsonObjectFree(kids);
2773                                                         kids = X;
2774                                                 }
2775
2776                                                 jsonObjectFree( kids );
2777                                                 jsonObjectFree( fake_params );
2778
2779                                                 osrfLogDebug(OSRF_LOG_MARK, "Fleshing of %s complete", osrfHashGet(kid_link, "field"));
2780                                                 osrfLogDebug(OSRF_LOG_MARK, "%s", jsonObjectToJSON(cur->item));
2781
2782                                         }
2783                                 }
2784                                 jsonObjectFree( flesh_blob );
2785                                 osrfStringArrayFree(link_fields);
2786                                 jsonObjectIteratorFree(itr);
2787                         }
2788                 }
2789         }
2790
2791         return res_list;
2792 }
2793
2794
2795 static jsonObject* doUpdate(osrfMethodContext* ctx, int* err ) {
2796
2797         osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
2798         jsonObject* target = jsonObjectGetIndex(ctx->params, 0);
2799
2800         if (!verifyObjectClass(ctx, target)) {
2801                 *err = -1;
2802                 return jsonNULL;
2803         }
2804
2805         if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
2806                 osrfAppSessionStatus(
2807                         ctx->session,
2808                         OSRF_STATUS_BADREQUEST,
2809                         "osrfMethodException",
2810                         ctx->request,
2811                         "No active transaction -- required for UPDATE"
2812                 );
2813                 *err = -1;
2814                 return jsonNULL;
2815         }
2816
2817         if (osrfHashGet( meta, "readonly" ) && strncasecmp("true", osrfHashGet( meta, "readonly" ), 4)) {
2818                 osrfAppSessionStatus(
2819                         ctx->session,
2820                         OSRF_STATUS_BADREQUEST,
2821                         "osrfMethodException",
2822                         ctx->request,
2823                         "Cannot UPDATE readonly class"
2824                 );
2825                 *err = -1;
2826                 return jsonNULL;
2827         }
2828
2829         dbhandle = writehandle;
2830
2831         char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
2832
2833         // Set the last_xact_id
2834         osrfHash* last_xact_id;
2835         if ((last_xact_id = oilsIDLFindPath("/%s/fields/last_xact_id", target->classname))) {
2836                 int index = atoi( osrfHashGet(last_xact_id, "array_position") );
2837                 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
2838                 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
2839         }       
2840
2841         char* pkey = osrfHashGet(meta, "primarykey");
2842         osrfHash* fields = osrfHashGet(meta, "fields");
2843
2844         char* id =
2845                 jsonObjectToSimpleString(
2846                         jsonObjectGetIndex(
2847                                 target,
2848                                 atoi( osrfHashGet( osrfHashGet( fields, pkey ), "array_position" ) )
2849                         )
2850                 );
2851
2852         osrfLogDebug(
2853                 OSRF_LOG_MARK,
2854                 "%s updating %s object with %s = %s",
2855                 MODULENAME,
2856                 osrfHashGet(meta, "fieldmapper"),
2857                 pkey,
2858                 id
2859         );
2860
2861         growing_buffer* sql = buffer_init(128);
2862         buffer_fadd(sql,"UPDATE %s SET", osrfHashGet(meta, "tablename"));
2863
2864         int i = 0;
2865         int first = 1;
2866         char* field_name;
2867         osrfStringArray* field_list = osrfHashKeys( fields );
2868         while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
2869
2870                 osrfHash* field = osrfHashGet( fields, field_name );
2871
2872                 if(!( strcmp( field_name, pkey ) )) continue;
2873                 if(!( strcmp( osrfHashGet(osrfHashGet(fields,field_name), "virtual"), "true" ) )) continue;
2874
2875                 jsonObject* field_object = jsonObjectGetIndex( target, atoi(osrfHashGet(field, "array_position")) );
2876
2877                 char* value;
2878                 if (field_object && field_object->classname) {
2879                         value = jsonObjectToSimpleString(
2880                                         jsonObjectGetIndex(
2881                                                 field_object,
2882                                                 atoi(
2883                                                         osrfHashGet(
2884                                                                 osrfHashGet(
2885                                                                         oilsIDLFindPath("/%s/fields", field_object->classname),
2886                                                                         (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
2887                                                                 ),
2888                                                                 "array_position"
2889                                                         )
2890                                                 )
2891                                         )
2892                                 );
2893
2894                 } else {
2895                         value = jsonObjectToSimpleString( field_object );
2896                 }
2897
2898                 osrfLogDebug( OSRF_LOG_MARK, "Updating %s object with %s = %s", osrfHashGet(meta, "fieldmapper"), field_name, value);
2899
2900                 if (!field_object || field_object->type == JSON_NULL) {
2901                         if ( !(!( strcmp( osrfHashGet(meta, "classname"), "au" ) ) && !( strcmp( field_name, "passwd" ) )) ) { // arg at the special case!
2902                                 if (first) first = 0;
2903                                 else buffer_add(sql, ",");
2904                                 buffer_fadd( sql, " %s = NULL", field_name );
2905                         }
2906                         
2907                 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
2908                         if (first) first = 0;
2909                         else buffer_add(sql, ",");
2910
2911                         if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
2912                                 buffer_fadd( sql, " %s = %ld", field_name, atol(value) );
2913                         } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
2914                                 buffer_fadd( sql, " %s = %f", field_name, atof(value) );
2915                         }
2916
2917                         osrfLogDebug( OSRF_LOG_MARK, "%s is of type %s", field_name, osrfHashGet(field, "datatype"));
2918
2919                 } else {
2920                         if ( dbi_conn_quote_string(dbhandle, &value) ) {
2921                                 if (first) first = 0;
2922                                 else buffer_add(sql, ",");
2923                                 buffer_fadd( sql, " %s = %s", field_name, value );
2924
2925                         } else {
2926                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
2927                                 osrfAppSessionStatus(
2928                                         ctx->session,
2929                                         OSRF_STATUS_INTERNALSERVERERROR,
2930                                         "osrfMethodException",
2931                                         ctx->request,
2932                                         "Error quoting string -- please see the error log for more details"
2933                                 );
2934                                 free(value);
2935                                 free(id);
2936                                 buffer_free(sql);
2937                                 *err = -1;
2938                                 return jsonNULL;
2939                         }
2940                 }
2941
2942                 free(value);
2943                 
2944         }
2945
2946         jsonObject* obj = jsonParseString(id);
2947
2948         if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
2949                 dbi_conn_quote_string(dbhandle, &id);
2950
2951         buffer_fadd( sql, " WHERE %s = %s;", pkey, id );
2952
2953         char* query = buffer_release(sql);
2954         osrfLogDebug(OSRF_LOG_MARK, "%s: Update SQL [%s]", MODULENAME, query);
2955
2956         dbi_result result = dbi_conn_query(dbhandle, query);
2957         free(query);
2958
2959         if (!result) {
2960                 jsonObjectFree(obj);
2961                 obj = jsonNewObject(NULL);
2962                 osrfLogError(
2963                         OSRF_LOG_MARK,
2964                         "%s ERROR updating %s object with %s = %s",
2965                         MODULENAME,
2966                         osrfHashGet(meta, "fieldmapper"),
2967                         pkey,
2968                         id
2969                 );
2970         }
2971
2972         free(id);
2973
2974         return obj;
2975 }
2976
2977 static jsonObject* doDelete(osrfMethodContext* ctx, int* err ) {
2978
2979         osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
2980
2981         if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
2982                 osrfAppSessionStatus(
2983                         ctx->session,
2984                         OSRF_STATUS_BADREQUEST,
2985                         "osrfMethodException",
2986                         ctx->request,
2987                         "No active transaction -- required for DELETE"
2988                 );
2989                 *err = -1;
2990                 return jsonNULL;
2991         }
2992
2993         if (osrfHashGet( meta, "readonly" ) && strncasecmp("true", osrfHashGet( meta, "readonly" ), 4)) {
2994                 osrfAppSessionStatus(
2995                         ctx->session,
2996                         OSRF_STATUS_BADREQUEST,
2997                         "osrfMethodException",
2998                         ctx->request,
2999                         "Cannot DELETE readonly class"
3000                 );
3001                 *err = -1;
3002                 return jsonNULL;
3003         }
3004
3005         dbhandle = writehandle;
3006
3007         jsonObject* obj;
3008
3009         char* pkey = osrfHashGet(meta, "primarykey");
3010
3011         char* id;
3012         if (jsonObjectGetIndex(ctx->params, 0)->classname) {
3013                 if (!verifyObjectClass(ctx, jsonObjectGetIndex( ctx->params, 0 ))) {
3014                         *err = -1;
3015                         return jsonNULL;
3016                 }
3017
3018                 id = jsonObjectToSimpleString(
3019                         jsonObjectGetIndex(
3020                                 jsonObjectGetIndex(ctx->params, 0),
3021                                 atoi( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "array_position") )
3022                         )
3023                 );
3024         } else {
3025                 id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
3026         }
3027
3028         osrfLogDebug(
3029                 OSRF_LOG_MARK,
3030                 "%s deleting %s object with %s = %s",
3031                 MODULENAME,
3032                 osrfHashGet(meta, "fieldmapper"),
3033                 pkey,
3034                 id
3035         );
3036
3037         obj = jsonParseString(id);
3038
3039         if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
3040                 dbi_conn_quote_string(writehandle, &id);
3041
3042         dbi_result result = dbi_conn_queryf(writehandle, "DELETE FROM %s WHERE %s = %s;", osrfHashGet(meta, "tablename"), pkey, id);
3043
3044         if (!result) {
3045                 jsonObjectFree(obj);
3046                 obj = jsonNewObject(NULL);
3047                 osrfLogError(
3048                         OSRF_LOG_MARK,
3049                         "%s ERROR deleting %s object with %s = %s",
3050                         MODULENAME,
3051                         osrfHashGet(meta, "fieldmapper"),
3052                         pkey,
3053                         id
3054                 );
3055         }
3056
3057         free(id);
3058
3059         return obj;
3060
3061 }
3062
3063
3064 static jsonObject* oilsMakeFieldmapperFromResult( dbi_result result, osrfHash* meta) {
3065         if(!(result && meta)) return jsonNULL;
3066
3067         jsonObject* object = jsonNewObject(NULL);
3068         jsonObjectSetClass(object, osrfHashGet(meta, "classname"));
3069
3070         osrfHash* fields = osrfHashGet(meta, "fields");
3071
3072         osrfLogInternal(OSRF_LOG_MARK, "Setting object class to %s ", object->classname);
3073
3074         osrfHash* _f;
3075         time_t _tmp_dt;
3076         char dt_string[256];
3077         struct tm gmdt;
3078
3079         int fmIndex;
3080         int columnIndex = 1;
3081         int attr;
3082         unsigned short type;
3083         const char* columnName;
3084
3085         /* cycle through the column list */
3086         while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
3087
3088                 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
3089
3090                 fmIndex = -1; // reset the position
3091                 
3092                 /* determine the field type and storage attributes */
3093                 type = dbi_result_get_field_type(result, columnName);
3094                 attr = dbi_result_get_field_attribs(result, columnName);
3095
3096                 /* fetch the fieldmapper index */
3097                 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
3098                         char* virt = (char*)osrfHashGet(_f, "virtual");
3099                         char* pos = (char*)osrfHashGet(_f, "array_position");
3100
3101                         if ( !virt || !pos || !(strcmp( virt, "true" )) ) continue;
3102
3103                         fmIndex = atoi( pos );
3104                         osrfLogInternal(OSRF_LOG_MARK, "... Found column at position [%s]...", pos);
3105                 } else {
3106                         continue;
3107                 }
3108
3109                 if (dbi_result_field_is_null(result, columnName)) {
3110                         jsonObjectSetIndex( object, fmIndex, jsonNewObject(NULL) );
3111                 } else {
3112
3113                         switch( type ) {
3114
3115                                 case DBI_TYPE_INTEGER :
3116
3117                                         if( attr & DBI_INTEGER_SIZE8 ) 
3118                                                 jsonObjectSetIndex( object, fmIndex, 
3119                                                         jsonNewNumberObject(dbi_result_get_longlong(result, columnName)));
3120                                         else 
3121                                                 jsonObjectSetIndex( object, fmIndex, 
3122                                                         jsonNewNumberObject(dbi_result_get_long(result, columnName)));
3123
3124                                         break;
3125
3126                                 case DBI_TYPE_DECIMAL :
3127                                         jsonObjectSetIndex( object, fmIndex, 
3128                                                         jsonNewNumberObject(dbi_result_get_double(result, columnName)));
3129                                         break;
3130
3131                                 case DBI_TYPE_STRING :
3132
3133
3134                                         jsonObjectSetIndex(
3135                                                 object,
3136                                                 fmIndex,
3137                                                 jsonNewObject( dbi_result_get_string(result, columnName) )
3138                                         );
3139
3140                                         break;
3141
3142                                 case DBI_TYPE_DATETIME :
3143
3144                                         memset(dt_string, '\0', sizeof(dt_string));
3145                                         memset(&gmdt, '\0', sizeof(gmdt));
3146                                         memset(&_tmp_dt, '\0', sizeof(_tmp_dt));
3147
3148                                         _tmp_dt = dbi_result_get_datetime(result, columnName);
3149
3150                                         localtime_r( &_tmp_dt, &gmdt );
3151
3152                                         if (!(attr & DBI_DATETIME_DATE)) {
3153                                                 strftime(dt_string, 255, "%T", &gmdt);
3154                                         } else if (!(attr & DBI_DATETIME_TIME)) {
3155                                                 strftime(dt_string, 255, "%F", &gmdt);
3156                                         } else {
3157                                                 strftime(dt_string, 255, "%FT%T%z", &gmdt);
3158                                         }
3159
3160                                         jsonObjectSetIndex( object, fmIndex, jsonNewObject(dt_string) );
3161
3162                                         break;
3163
3164                                 case DBI_TYPE_BINARY :
3165                                         osrfLogError( OSRF_LOG_MARK, 
3166                                                 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
3167                         }
3168                 }
3169         }
3170
3171         return object;
3172 }
3173
3174 static jsonObject* oilsMakeJSONFromResult( dbi_result result ) {
3175         if(!result) return jsonNULL;
3176
3177         jsonObject* object = jsonNewObject(NULL);
3178
3179         time_t _tmp_dt;
3180         char dt_string[256];
3181         struct tm gmdt;
3182
3183         int fmIndex;
3184         int columnIndex = 1;
3185         int attr;
3186         unsigned short type;
3187         const char* columnName;
3188
3189         /* cycle through the column list */
3190         while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
3191
3192                 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
3193
3194                 fmIndex = -1; // reset the position
3195                 
3196                 /* determine the field type and storage attributes */
3197                 type = dbi_result_get_field_type(result, columnName);
3198                 attr = dbi_result_get_field_attribs(result, columnName);
3199
3200                 if (dbi_result_field_is_null(result, columnName)) {
3201                         jsonObjectSetKey( object, columnName, jsonNewObject(NULL) );
3202                 } else {
3203
3204                         switch( type ) {
3205
3206                                 case DBI_TYPE_INTEGER :
3207
3208                                         if( attr & DBI_INTEGER_SIZE8 ) 
3209                                                 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_longlong(result, columnName)) );
3210                                         else 
3211                                                 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_long(result, columnName)) );
3212                                         break;
3213
3214                                 case DBI_TYPE_DECIMAL :
3215                                         jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_double(result, columnName)) );
3216                                         break;
3217
3218                                 case DBI_TYPE_STRING :
3219                                         jsonObjectSetKey( object, columnName, jsonNewObject(dbi_result_get_string(result, columnName)) );
3220                                         break;
3221
3222                                 case DBI_TYPE_DATETIME :
3223
3224                                         memset(dt_string, '\0', sizeof(dt_string));
3225                                         memset(&gmdt, '\0', sizeof(gmdt));
3226                                         memset(&_tmp_dt, '\0', sizeof(_tmp_dt));
3227
3228                                         _tmp_dt = dbi_result_get_datetime(result, columnName);
3229
3230                                         localtime_r( &_tmp_dt, &gmdt );
3231
3232                                         if (!(attr & DBI_DATETIME_DATE)) {
3233                                                 strftime(dt_string, 255, "%T", &gmdt);
3234                                         } else if (!(attr & DBI_DATETIME_TIME)) {
3235                                                 strftime(dt_string, 255, "%F", &gmdt);
3236                                         } else {
3237                                                 strftime(dt_string, 255, "%FT%T%z", &gmdt);
3238                                         }
3239
3240                                         jsonObjectSetKey( object, columnName, jsonNewObject(dt_string) );
3241                                         break;
3242
3243                                 case DBI_TYPE_BINARY :
3244                                         osrfLogError( OSRF_LOG_MARK, 
3245                                                 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
3246                         }
3247                 }
3248         }
3249
3250         return object;
3251 }
3252