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