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