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