]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/c-apps/oils_cstore.c
9feed5ce5a1f7d97223e76bd028306879ad74946
[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/utils.h"
4 #include "objson/object.h"
5 #include "opensrf/log.h"
6 #include "oils_utils.h"
7 #include "oils_constants.h"
8 #include "oils_event.h"
9 #include "oils_idl.h"
10 #include <dbi/dbi.h>
11
12 #include <time.h>
13 #include <stdlib.h>
14 #include <string.h>
15
16 #define OILS_AUTH_CACHE_PRFX "oils_cstore_"
17 #define MODULENAME "open-ils.cstore"
18 #define PERSIST_NS "http://open-ils.org/spec/opensrf/IDL/persistance/v1"
19 #define OBJECT_NS "http://open-ils.org/spec/opensrf/IDL/objects/v1"
20 #define BASE_NS "http://opensrf.org/spec/IDL/base/v1"
21
22 int osrfAppChildInit();
23 int osrfAppInitialize();
24
25 int verifyObjectClass ( osrfMethodContext*, jsonObject* );
26
27 int beginTransaction ( osrfMethodContext* );
28 int commitTransaction ( osrfMethodContext* );
29 int rollbackTransaction ( osrfMethodContext* );
30
31 int setSavepoint ( osrfMethodContext* );
32 int releaseSavepoint ( osrfMethodContext* );
33 int rollbackSavepoint ( osrfMethodContext* );
34
35 int dispatchCRUDMethod ( osrfMethodContext* );
36 jsonObject* doCreate ( osrfMethodContext*, int* );
37 jsonObject* doRetrieve ( osrfMethodContext*, int* );
38 jsonObject* doUpdate ( osrfMethodContext*, int* );
39 jsonObject* doDelete ( osrfMethodContext*, int* );
40 jsonObject* doSearch ( osrfMethodContext*, osrfHash*, jsonObject*, int* );
41 jsonObject* oilsMakeJSONFromResult( dbi_result, osrfHash* );
42
43 char* searchWriteSimplePredicate ( osrfHash*, const char*, const char*, const char* );
44 char* searchSimplePredicate ( const char*, osrfHash*, jsonObject* );
45 char* searchFunctionPredicate ( osrfHash*, jsonObjectNode* );
46 char* searchFieldTransformPredicate ( osrfHash*, jsonObjectNode* );
47 char* searchBETWEENPredicate ( osrfHash*, jsonObject* );
48 char* searchINPredicate ( osrfHash*, jsonObject* );
49 char* searchPredicate ( osrfHash*, jsonObject* );
50
51 void userDataFree( void* );
52 void sessionDataFree( char*, void* );
53
54 dbi_conn writehandle; /* our MASTER db connection */
55 dbi_conn dbhandle; /* our CURRENT db connection */
56 osrfHash readHandles;
57 jsonObject* jsonNULL = NULL; // 
58
59
60 /* parse and store the IDL here */
61 osrfHash* idl;
62
63 int osrfAppInitialize() {
64
65         // first we register all the transaction and savepoint methods
66         osrfAppRegisterMethod( MODULENAME, "open-ils.cstore.transaction.begin", "beginTransaction", "", 0, 0 );
67         osrfAppRegisterMethod( MODULENAME, "open-ils.cstore.transaction.commit", "commitTransaction", "", 0, 0 );
68         osrfAppRegisterMethod( MODULENAME, "open-ils.cstore.transaction.rollback", "rollbackTransaction", "", 0, 0 );
69
70         osrfAppRegisterMethod( MODULENAME, "open-ils.cstore.savepoint.set", "setSavepoint", "", 1, 0 );
71         osrfAppRegisterMethod( MODULENAME, "open-ils.cstore.savepoint.release", "releaseSavepoint", "", 1, 0 );
72         osrfAppRegisterMethod( MODULENAME, "open-ils.cstore.savepoint.rollback", "rollbackSavepoint", "", 1, 0 );
73
74
75         osrfLogInfo(OSRF_LOG_MARK, "Initializing the CStore Server...");
76         osrfLogInfo(OSRF_LOG_MARK, "Finding XML file...");
77
78         char * idl_filename = osrf_settings_host_value("/apps/%s/app_settings/IDL", MODULENAME);
79         osrfLogInfo(OSRF_LOG_MARK, "Found file:");
80         osrfLogInfo(OSRF_LOG_MARK, idl_filename);
81
82         idl = oilsIDLInit( idl_filename );
83
84         if (!idl) {
85                 osrfLogError(OSRF_LOG_MARK, "Problem loading the IDL.  Seacrest out!");
86                 exit(1);
87         }
88
89         osrfStringArray* global_methods = osrfNewStringArray(6);
90
91         osrfStringArrayAdd( global_methods, "create" );
92         osrfStringArrayAdd( global_methods, "retrieve" );
93         osrfStringArrayAdd( global_methods, "update" );
94         osrfStringArrayAdd( global_methods, "delete" );
95         osrfStringArrayAdd( global_methods, "search" );
96         osrfStringArrayAdd( global_methods, "id_list" );
97
98         int c_index = 0; 
99         char* classname;
100         osrfStringArray* classes = osrfHashKeys( idl );
101         osrfLogDebug(OSRF_LOG_MARK, "%d classes loaded", classes->size );
102         osrfLogDebug(OSRF_LOG_MARK, "At least %d methods will be generated", classes->size * global_methods->size);
103         
104         while ( (classname = osrfStringArrayGetString(classes, c_index++)) ) {
105                 osrfLogInfo(OSRF_LOG_MARK, "Generating class methods for %s", classname);
106                 
107                 osrfHash* idlClass = osrfHashGet(idl, classname);
108
109                 char* virt = osrfHashGet(idlClass, "virtual");
110                 if (virt && !strcmp( virt, "true")) {
111                         osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
112                         continue;
113                 }
114
115                 osrfLogDebug(OSRF_LOG_MARK, "HERE");
116                 
117                 int i = 0; 
118                 char* method_type;
119                 char* st_tmp;
120                 char* _fm;
121                 char* part;
122                 osrfHash* method_meta;
123                 while ( (method_type = osrfStringArrayGetString(global_methods, i++)) ) {
124                         osrfLogDebug(OSRF_LOG_MARK, "Using files to build %s class methods for %s", method_type, classname);
125
126                         if (!osrfHashGet(idlClass, "fieldmapper")) continue;
127
128                         method_meta = osrfNewHash();
129                         osrfHashSet(method_meta, idlClass, "class");
130
131                         _fm = strdup( (char*)osrfHashGet(idlClass, "fieldmapper") );
132                         part = strtok_r(_fm, ":", &st_tmp);
133
134                         growing_buffer* method_name =  buffer_init(64);
135                         buffer_fadd(method_name, "%s.direct.%s", MODULENAME, part);
136
137                         while ((part = strtok_r(NULL, ":", &st_tmp))) {
138                                 buffer_fadd(method_name, ".%s", part);
139                         }
140                         buffer_fadd(method_name, ".%s", method_type);
141
142
143                         char* method = buffer_data(method_name);
144                         buffer_free(method_name);
145                         free(_fm);
146
147                         osrfHashSet( method_meta, method, "methodname" );
148                         osrfHashSet( method_meta, method_type, "methodtype" );
149
150                         int flags = 0;
151                         if (!(strcmp( method_type, "search" )) || !(strcmp( method_type, "id_list" ))) {
152                                 flags = flags | OSRF_METHOD_STREAMING;
153                         }
154
155                         osrfAppRegisterExtendedMethod(
156                                 MODULENAME,
157                                 method,
158                                 "dispatchCRUDMethod",
159                                 "",
160                                 1,
161                                 flags,
162                                 (void*)method_meta
163                         );
164                 }
165         }
166
167         return 0;
168 }
169
170 /**
171  * Connects to the database 
172  */
173 int osrfAppChildInit() {
174
175         osrfLogDebug(OSRF_LOG_MARK, "Attempting to initialize libdbi...");
176         dbi_initialize(NULL);
177         osrfLogDebug(OSRF_LOG_MARK, "... libdbi initialized.");
178
179         char* driver    = osrf_settings_host_value("/apps/%s/app_settings/driver", MODULENAME);
180         char* user      = osrf_settings_host_value("/apps/%s/app_settings/database/user", MODULENAME);
181         char* host      = osrf_settings_host_value("/apps/%s/app_settings/database/host", MODULENAME);
182         char* port      = osrf_settings_host_value("/apps/%s/app_settings/database/port", MODULENAME);
183         char* db        = osrf_settings_host_value("/apps/%s/app_settings/database/db", MODULENAME);
184         char* pw        = osrf_settings_host_value("/apps/%s/app_settings/database/pw", MODULENAME);
185
186         osrfLogDebug(OSRF_LOG_MARK, "Attempting to load the database driver [%s]...", driver);
187         writehandle = dbi_conn_new(driver);
188
189         if(!writehandle) {
190                 osrfLogError(OSRF_LOG_MARK, "Error loading database driver [%s]", driver);
191                 return -1;
192         }
193         osrfLogDebug(OSRF_LOG_MARK, "Database driver [%s] seems OK", driver);
194
195         osrfLogInfo(OSRF_LOG_MARK, "%s connecting to database.  host=%s, "
196                 "port=%s, user=%s, pw=%s, db=%s", MODULENAME, host, port, user, pw, db );
197
198         if(host) dbi_conn_set_option(writehandle, "host", host );
199         if(port) dbi_conn_set_option_numeric( writehandle, "port", atoi(port) );
200         if(user) dbi_conn_set_option(writehandle, "username", user);
201         if(pw) dbi_conn_set_option(writehandle, "password", pw );
202         if(db) dbi_conn_set_option(writehandle, "dbname", db );
203
204         free(user);
205         free(host);
206         free(port);
207         free(db);
208         free(pw);
209
210         const char* err;
211         if (dbi_conn_connect(writehandle) < 0) {
212                 dbi_conn_error(writehandle, &err);
213                 osrfLogError( OSRF_LOG_MARK, "Error connecting to database: %s", err);
214                 return -1;
215         }
216
217         osrfLogInfo(OSRF_LOG_MARK, "%s successfully connected to the database", MODULENAME);
218
219         int attr;
220         unsigned short type;
221         int i = 0; 
222         char* classname;
223         osrfStringArray* classes = osrfHashKeys( idl );
224         
225         while ( (classname = osrfStringArrayGetString(classes, i++)) ) {
226                 osrfHash* class = osrfHashGet( idl, classname );
227                 osrfHash* fields = osrfHashGet( class, "fields" );
228
229                 char* virt = osrfHashGet(class, "virtual");
230                 if (virt && !strcmp( virt, "true")) {
231                         osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
232                         continue;
233                 }
234
235         
236                 growing_buffer* sql_buf = buffer_init(32);
237                 buffer_fadd( sql_buf, "SELECT * FROM %s WHERE 1=0;", osrfHashGet(class, "tablename") );
238
239                 char* sql = buffer_data(sql_buf);
240                 buffer_free(sql_buf);
241                 osrfLogDebug(OSRF_LOG_MARK, "%s Investigatory SQL = %s", MODULENAME, sql);
242
243                 dbi_result result = dbi_conn_query(writehandle, sql);
244                 free(sql);
245
246                 if (result) {
247
248                         int columnIndex = 1;
249                         const char* columnName;
250                         osrfHash* _f;
251                         while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
252
253                                 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
254
255                                 /* fetch the fieldmapper index */
256                                 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
257
258                                         osrfLogDebug(OSRF_LOG_MARK, "Found [%s] in IDL hash...", (char*)columnName);
259
260                                         /* determine the field type and storage attributes */
261                                         type = dbi_result_get_field_type(result, columnName);
262                                         attr = dbi_result_get_field_attribs(result, columnName);
263
264                                         switch( type ) {
265
266                                                 case DBI_TYPE_INTEGER :
267
268                                                         if ( !osrfHashGet(_f, "primitive") )
269                                                                 osrfHashSet(_f,"number", "primitive");
270
271                                                         if( attr & DBI_INTEGER_SIZE8 ) 
272                                                                 osrfHashSet(_f,"INT8", "datatype");
273                                                         else 
274                                                                 osrfHashSet(_f,"INT", "datatype");
275                                                         break;
276
277                                                 case DBI_TYPE_DECIMAL :
278                                                         if ( !osrfHashGet(_f, "primitive") )
279                                                                 osrfHashSet(_f,"number", "primitive");
280
281                                                         osrfHashSet(_f,"NUMERIC", "datatype");
282                                                         break;
283
284                                                 case DBI_TYPE_STRING :
285                                                         if ( !osrfHashGet(_f, "primitive") )
286                                                                 osrfHashSet(_f,"string", "primitive");
287                                                         osrfHashSet(_f,"TEXT", "datatype");
288                                                         break;
289
290                                                 case DBI_TYPE_DATETIME :
291                                                         if ( !osrfHashGet(_f, "primitive") )
292                                                                 osrfHashSet(_f,"string", "primitive");
293
294                                                         osrfHashSet(_f,"TIMESTAMP", "datatype");
295                                                         break;
296
297                                                 case DBI_TYPE_BINARY :
298                                                         if ( !osrfHashGet(_f, "primitive") )
299                                                                 osrfHashSet(_f,"string", "primitive");
300
301                                                         osrfHashSet(_f,"BYTEA", "datatype");
302                                         }
303
304                                         osrfLogDebug(
305                                                 OSRF_LOG_MARK,
306                                                 "Setting [%s] to primitive [%s] and datatype [%s]...",
307                                                 (char*)columnName,
308                                                 osrfHashGet(_f, "primitive"),
309                                                 osrfHashGet(_f, "datatype")
310                                         );
311                                 }
312                         }
313                         dbi_result_free(result);
314                 } else {
315                         osrfLogDebug(OSRF_LOG_MARK, "No data found for class [%s]...", (char*)classname);
316                 }
317         }
318
319         osrfStringArrayFree(classes);
320
321         return 0;
322 }
323
324 void userDataFree( void* blob ) {
325         osrfHashFree( (osrfHash*)blob );
326         return;
327 }
328
329 void sessionDataFree( char* key, void* item ) {
330         if (!(strcmp(key,"xact_id"))) {
331                 if (writehandle)
332                         dbi_conn_query(writehandle, "ROLLBACK;");
333                 free(item);
334         }
335
336         return;
337 }
338
339 int beginTransaction ( osrfMethodContext* ctx ) {
340         OSRF_METHOD_VERIFY_CONTEXT(ctx);
341
342         dbi_result result = dbi_conn_query(writehandle, "START TRANSACTION;");
343         if (!result) {
344                 osrfLogError(OSRF_LOG_MARK, "%s: Error starting transaction", MODULENAME );
345                 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error starting transaction" );
346                 return -1;
347         } else {
348                 jsonObject* ret = jsonNewObject(ctx->session->session_id);
349                 osrfAppRespondComplete( ctx, ret );
350                 jsonObjectFree(ret);
351                 
352                 if (!ctx->session->userData) {
353                         ctx->session->userData = osrfNewHash();
354                         ((osrfHash*)ctx->session->userData)->freeItem = &sessionDataFree;
355                 }
356
357                 osrfHashSet( (osrfHash*)ctx->session->userData, strdup( ctx->session->session_id ), "xact_id" );
358                 ctx->session->userDataFree = &userDataFree;
359                 
360         }
361         return 0;
362 }
363
364 int setSavepoint ( osrfMethodContext* ctx ) {
365         OSRF_METHOD_VERIFY_CONTEXT(ctx);
366
367         char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
368
369         if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
370                 osrfAppSessionStatus(
371                         ctx->session,
372                         OSRF_STATUS_INTERNALSERVERERROR,
373                         "osrfMethodException",
374                         ctx->request,
375                         "No active transaction -- required for savepoints"
376                 );
377                 return -1;
378         }
379
380         dbi_result result = dbi_conn_queryf(writehandle, "SAVEPOINT \"%s\";", spName);
381         if (!result) {
382                 osrfLogError(
383                         OSRF_LOG_MARK,
384                         "%s: Error creating savepoint %s in transaction %s",
385                         MODULENAME,
386                         spName,
387                         osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
388                 );
389                 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error creating savepoint" );
390                 return -1;
391         } else {
392                 jsonObject* ret = jsonNewObject(spName);
393                 osrfAppRespondComplete( ctx, ret );
394                 jsonObjectFree(ret);
395         }
396         return 0;
397 }
398
399 int releaseSavepoint ( osrfMethodContext* ctx ) {
400         OSRF_METHOD_VERIFY_CONTEXT(ctx);
401
402         char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
403
404         if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
405                 osrfAppSessionStatus(
406                         ctx->session,
407                         OSRF_STATUS_INTERNALSERVERERROR,
408                         "osrfMethodException",
409                         ctx->request,
410                         "No active transaction -- required for savepoints"
411                 );
412                 return -1;
413         }
414
415         dbi_result result = dbi_conn_queryf(writehandle, "RELEASE SAVEPOINT \"%s\";", spName);
416         if (!result) {
417                 osrfLogError(
418                         OSRF_LOG_MARK,
419                         "%s: Error releasing savepoint %s in transaction %s",
420                         MODULENAME,
421                         spName,
422                         osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
423                 );
424                 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error releasing savepoint" );
425                 return -1;
426         } else {
427                 jsonObject* ret = jsonNewObject(spName);
428                 osrfAppRespondComplete( ctx, ret );
429                 jsonObjectFree(ret);
430         }
431         return 0;
432 }
433
434 int rollbackSavepoint ( osrfMethodContext* ctx ) {
435         OSRF_METHOD_VERIFY_CONTEXT(ctx);
436
437         char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
438
439         if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
440                 osrfAppSessionStatus(
441                         ctx->session,
442                         OSRF_STATUS_INTERNALSERVERERROR,
443                         "osrfMethodException",
444                         ctx->request,
445                         "No active transaction -- required for savepoints"
446                 );
447                 return -1;
448         }
449
450         dbi_result result = dbi_conn_queryf(writehandle, "ROLLBACK TO SAVEPOINT \"%s\";", spName);
451         if (!result) {
452                 osrfLogError(
453                         OSRF_LOG_MARK,
454                         "%s: Error rolling back savepoint %s in transaction %s",
455                         MODULENAME,
456                         spName,
457                         osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
458                 );
459                 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back savepoint" );
460                 return -1;
461         } else {
462                 jsonObject* ret = jsonNewObject(spName);
463                 osrfAppRespondComplete( ctx, ret );
464                 jsonObjectFree(ret);
465         }
466         return 0;
467 }
468
469 int commitTransaction ( osrfMethodContext* ctx ) {
470         OSRF_METHOD_VERIFY_CONTEXT(ctx);
471
472         if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
473                 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to commit" );
474                 return -1;
475         }
476
477         dbi_result result = dbi_conn_query(writehandle, "COMMIT;");
478         if (!result) {
479                 osrfLogError(OSRF_LOG_MARK, "%s: Error committing transaction", MODULENAME );
480                 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error committing transaction" );
481                 return -1;
482         } else {
483                 osrfHashRemove(ctx->session->userData, "xact_id");
484                 jsonObject* ret = jsonNewObject(ctx->session->session_id);
485                 osrfAppRespondComplete( ctx, ret );
486                 jsonObjectFree(ret);
487         }
488         return 0;
489 }
490
491 int rollbackTransaction ( osrfMethodContext* ctx ) {
492         OSRF_METHOD_VERIFY_CONTEXT(ctx);
493
494         if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
495                 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to roll back" );
496                 return -1;
497         }
498
499         dbi_result result = dbi_conn_query(writehandle, "ROLLBACK;");
500         if (!result) {
501                 osrfLogError(OSRF_LOG_MARK, "%s: Error rolling back transaction", MODULENAME );
502                 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back transaction" );
503                 return -1;
504         } else {
505                 osrfHashRemove(ctx->session->userData, "xact_id");
506                 jsonObject* ret = jsonNewObject(ctx->session->session_id);
507                 osrfAppRespondComplete( ctx, ret );
508                 jsonObjectFree(ret);
509         }
510         return 0;
511 }
512
513 int dispatchCRUDMethod ( osrfMethodContext* ctx ) {
514         OSRF_METHOD_VERIFY_CONTEXT(ctx);
515
516         osrfHash* meta = (osrfHash*) ctx->method->userData;
517         osrfHash* class_obj = osrfHashGet( meta, "class" );
518         
519         int err = 0;
520
521         jsonObject * obj = NULL;
522         if (!strcmp( (char*)osrfHashGet(meta, "methodtype"), "create"))
523                 obj = doCreate(ctx, &err);
524
525         if (!strcmp( (char*)osrfHashGet(meta, "methodtype"), "retrieve"))
526                 obj = doRetrieve(ctx, &err);
527
528         if (!strcmp( (char*)osrfHashGet(meta, "methodtype"), "update"))
529                 obj = doUpdate(ctx, &err);
530
531         if (!strcmp( (char*)osrfHashGet(meta, "methodtype"), "delete"))
532                 obj = doDelete(ctx, &err);
533
534         if (!strcmp( (char*)osrfHashGet(meta, "methodtype"), "search")) {
535
536                 obj = doSearch(ctx, class_obj, ctx->params, &err);
537                 if(err) return err;
538
539                 jsonObjectNode* cur;
540                 jsonObjectIterator* itr = jsonNewObjectIterator( obj );
541                 while ((cur = jsonObjectIteratorNext( itr ))) {
542                         osrfAppRespond( ctx, jsonObjectClone(cur->item) );
543                 }
544                 jsonObjectIteratorFree(itr);
545                 osrfAppRespondComplete( ctx, NULL );
546
547         } else if (!strcmp( (char*)osrfHashGet(meta, "methodtype"), "id_list")) {
548
549                 jsonObject* _p = jsonObjectClone( ctx->params );
550                 if (jsonObjectGetIndex( _p, 1 )) {
551                         jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh" );
552                         jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh_columns" );
553                 } else {
554                         jsonObjectSetIndex( _p, 1, jsonParseString("{}") );
555                 }
556
557                 growing_buffer* sel_list = buffer_init(16);
558                 buffer_fadd(sel_list, "{ \"%s\":[\"%s\"] }", osrfHashGet( class_obj, "classname" ), osrfHashGet( class_obj, "primarykey" ));
559                 char* _s = buffer_data(sel_list);
560                 buffer_free(sel_list);
561
562                 jsonObjectSetKey( jsonObjectGetIndex( _p, 1 ), "select", jsonParseString(_s) );
563                 osrfLogDebug(OSRF_LOG_MARK, "%s: Select qualifer set to [%s]", MODULENAME, _s);
564                 free(_s);
565
566                 obj = doSearch(ctx, class_obj, _p, &err);
567                 if(err) return err;
568
569                 jsonObjectNode* cur;
570                 jsonObjectIterator* itr = jsonNewObjectIterator( obj );
571                 while ((cur = jsonObjectIteratorNext( itr ))) {
572                         osrfAppRespond(
573                                 ctx,
574                                 jsonObjectClone(
575                                         jsonObjectGetIndex(
576                                                 cur->item,
577                                                 atoi(
578                                                         osrfHashGet(
579                                                                 osrfHashGet(
580                                                                         osrfHashGet( class_obj, "fields" ),
581                                                                         osrfHashGet( class_obj, "primarykey")
582                                                                 ),
583                                                                 "array_position"
584                                                         )
585                                                 )
586                                         )
587                                 )
588                         );
589                 }
590                 jsonObjectIteratorFree(itr);
591                 osrfAppRespondComplete( ctx, NULL );
592                 
593         } else {
594                 osrfAppRespondComplete( ctx, obj );
595         }
596
597         jsonObjectFree(obj);
598
599         return err;
600 }
601
602 int verifyObjectClass ( osrfMethodContext* ctx, jsonObject* param ) {
603         
604         osrfHash* meta = (osrfHash*) ctx->method->userData;
605         osrfHash* class = osrfHashGet( meta, "class" );
606         
607         if ((strcmp( osrfHashGet(class, "classname"), param->classname ))) {
608
609                 growing_buffer* msg = buffer_init(128);
610                 buffer_fadd(
611                         msg,
612                         "%s: %s method for type %s was passed a %s",
613                         MODULENAME,
614                         osrfHashGet(meta, "methodtype"),
615                         osrfHashGet(class, "classname"),
616                         param->classname
617                 );
618
619                 char* m = buffer_data(msg);
620                 osrfAppSessionStatus( ctx->session, OSRF_STATUS_BADREQUEST, "osrfMethodException", ctx->request, m );
621
622                 buffer_free(msg);
623                 free(m);
624
625                 return 0;
626         }
627         return 1;
628 }
629
630 jsonObject* doCreate(osrfMethodContext* ctx, int* err ) {
631
632         osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
633         jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
634         jsonObject* options = jsonObjectGetIndex( ctx->params, 1 );
635
636         if (!verifyObjectClass(ctx, target)) {
637                 *err = -1;
638                 return jsonNULL;
639         }
640
641         osrfLogDebug( OSRF_LOG_MARK, "Object seems to be of the correct type" );
642
643         if (!ctx->session || !ctx->session->userData || !osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
644                 osrfLogError( OSRF_LOG_MARK, "No active transaction -- required for CREATE" );
645
646                 osrfAppSessionStatus(
647                         ctx->session,
648                         OSRF_STATUS_BADREQUEST,
649                         "osrfMethodException",
650                         ctx->request,
651                         "No active transaction -- required for CREATE"
652                 );
653                 *err = -1;
654                 return jsonNULL;
655         }
656
657         char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
658
659         // Set the last_xact_id
660         osrfHash* last_xact_id;
661         if ((last_xact_id = oilsIDLFindPath("/%s/fields/last_xact_id", target->classname))) {
662                 int index = atoi( osrfHashGet(last_xact_id, "array_position") );
663                 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
664                 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
665         }       
666
667         osrfLogDebug( OSRF_LOG_MARK, "There is a transaction running..." );
668
669         dbhandle = writehandle;
670
671         osrfHash* fields = osrfHashGet(meta, "fields");
672         char* pkey = osrfHashGet(meta, "primarykey");
673         char* seq = osrfHashGet(meta, "sequence");
674
675         growing_buffer* table_buf = buffer_init(128);
676         growing_buffer* col_buf = buffer_init(128);
677         growing_buffer* val_buf = buffer_init(128);
678
679         buffer_fadd(table_buf,"INSERT INTO %s", osrfHashGet(meta, "tablename"));
680         buffer_add(col_buf,"(");
681         buffer_add(val_buf,"VALUES (");
682
683
684         int i = 0;
685         int first = 1;
686         char* field_name;
687         osrfStringArray* field_list = osrfHashKeys( fields );
688         while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
689
690                 osrfHash* field = osrfHashGet( fields, field_name );
691
692                 if(!( strcmp( osrfHashGet(osrfHashGet(fields,field_name), "virtual"), "true" ) )) continue;
693
694                 int pos = atoi(osrfHashGet(field, "array_position"));
695                 char* value = jsonObjectToSimpleString( jsonObjectGetIndex( target, pos ) );
696
697                 if (first) {
698                         first = 0;
699                 } else {
700                         buffer_add(col_buf, ",");
701                         buffer_add(val_buf, ",");
702                 }
703
704                 buffer_add(col_buf, field_name);
705
706                 if (!jsonObjectGetIndex(target, pos) || jsonObjectGetIndex(target, pos)->type == JSON_NULL) {
707                         buffer_add( val_buf, "DEFAULT" );
708                         
709                 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
710                         if ( !strcmp(osrfHashGet(field, "datatype"), "INT8") ) {
711                                 buffer_fadd( val_buf, "%lld", atol(value) );
712                                 
713                         } else if ( !strcmp(osrfHashGet(field, "datatype"), "INT") ) {
714                                 buffer_fadd( val_buf, "%ld", atoll(value) );
715                                 
716                         } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
717                                 buffer_fadd( val_buf, "%f", atof(value) );
718                         }
719                 } else {
720                         if ( dbi_conn_quote_string(writehandle, &value) ) {
721                                 buffer_fadd( val_buf, "%s", value );
722
723                         } else {
724                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
725                                 osrfAppSessionStatus(
726                                         ctx->session,
727                                         OSRF_STATUS_INTERNALSERVERERROR,
728                                         "osrfMethodException",
729                                         ctx->request,
730                                         "Error quoting string -- please see the error log for more details"
731                                 );
732                                 free(value);
733                                 buffer_free(table_buf);
734                                 buffer_free(col_buf);
735                                 buffer_free(val_buf);
736                                 *err = -1;
737                                 return jsonNULL;
738                         }
739                 }
740
741                 free(value);
742                 
743         }
744
745
746         buffer_add(col_buf,")");
747         buffer_add(val_buf,")");
748
749         growing_buffer* sql = buffer_init(128);
750         buffer_fadd(
751                 sql,
752                 "%s %s %s;",
753                 buffer_data(table_buf),
754                 buffer_data(col_buf),
755                 buffer_data(val_buf)
756         );
757         buffer_free(table_buf);
758         buffer_free(col_buf);
759         buffer_free(val_buf);
760
761         char* query = buffer_data(sql);
762         buffer_free(sql);
763
764         osrfLogDebug(OSRF_LOG_MARK, "%s: Insert SQL [%s]", MODULENAME, query);
765
766         
767         dbi_result result = dbi_conn_query(writehandle, query);
768
769         jsonObject* obj = NULL;
770
771         if (!result) {
772                 obj = jsonNewObject(NULL);
773                 osrfLogError(
774                         OSRF_LOG_MARK,
775                         "%s ERROR inserting %s object using query [%s]",
776                         MODULENAME,
777                         osrfHashGet(meta, "fieldmapper"),
778                         query
779                 );
780                 osrfAppSessionStatus(
781                         ctx->session,
782                         OSRF_STATUS_INTERNALSERVERERROR,
783                         "osrfMethodException",
784                         ctx->request,
785                         "INSERT error -- please see the error log for more details"
786                 );
787                 *err = -1;
788         } else {
789
790                 int pos = atoi(osrfHashGet( osrfHashGet(fields, pkey), "array_position" ));
791                 char* id = jsonObjectToSimpleString(jsonObjectGetIndex(target, pos));
792                 if (!id) {
793                         unsigned long long new_id = dbi_conn_sequence_last(writehandle, seq);
794                         growing_buffer* _id = buffer_init(10);
795                         buffer_fadd(_id, "%lld", new_id);
796                         id = buffer_data(_id);
797                         buffer_free(_id);
798                 }
799
800                 if (    !options
801                         || !jsonObjectGetKey( options, "quiet")
802                         || strcmp( jsonObjectToSimpleString(jsonObjectGetKey( options, "quiet")), "true" )
803                 ) {
804
805                         jsonObject* fake_params = jsonParseString("[]");
806                         jsonObjectPush(fake_params, jsonParseString("{}"));
807
808                         jsonObjectSetKey(
809                                 jsonObjectGetIndex(fake_params, 0),
810                                 osrfHashGet(meta, "primarykey"),
811                                 jsonNewObject(id)
812                         );
813
814                         jsonObject* list = doSearch( ctx,meta, fake_params, err);
815
816                         if(*err) {
817                                 jsonObjectFree( fake_params );
818                                 obj = jsonNULL;
819                         } else {
820                                 obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
821                         }
822
823                         jsonObjectFree( list );
824                         jsonObjectFree( fake_params );
825
826                 } else {
827                         obj = jsonNewObject(id);
828                 }
829
830         }
831
832         free(query);
833
834         return obj;
835
836 }
837
838
839 jsonObject* doRetrieve(osrfMethodContext* ctx, int* err ) {
840
841         osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
842
843         jsonObject* obj;
844
845         char* id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
846         jsonObject* order_hash = jsonObjectGetIndex(ctx->params, 1);
847
848         osrfLogDebug(
849                 OSRF_LOG_MARK,
850                 "%s retrieving %s object with id %s",
851                 MODULENAME,
852                 osrfHashGet(meta, "fieldmapper"),
853                 id
854         );
855
856         jsonObject* fake_params = jsonParseString("[]");
857         jsonObjectPush(fake_params, jsonParseString("{}"));
858
859         jsonObjectSetKey(
860                 jsonObjectGetIndex(fake_params, 0),
861                 osrfHashGet(meta, "primarykey"),
862                 jsonParseString(id)
863         );
864
865         if (order_hash) jsonObjectPush(fake_params, jsonObjectClone(order_hash) );
866
867         jsonObject* list = doSearch( ctx,meta, fake_params, err);
868
869         if(*err) {
870                 jsonObjectFree( fake_params );
871                 return jsonNULL;
872         }
873
874         obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
875
876         jsonObjectFree( list );
877         jsonObjectFree( fake_params );
878
879         return obj;
880 }
881
882 char* jsonNumberToDBString ( osrfHash* field, jsonObject* value ) {
883         growing_buffer* val_buf = buffer_init(32);
884
885         if ( !strncmp(osrfHashGet(field, "datatype"), "INT", 3) ) {
886                 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%ld", (long)jsonObjectGetNumber(value) );
887                 else buffer_fadd( val_buf, "%ld", atol(jsonObjectToSimpleString(value)) );
888
889         } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
890                 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%f",  jsonObjectGetNumber(value) );
891                 else buffer_fadd( val_buf, "%f", atof(jsonObjectToSimpleString(value)) );
892         }
893
894         char* pred = buffer_data(val_buf);
895         buffer_free(val_buf);
896
897         return pred;
898 }
899
900 char* searchINPredicate (osrfHash* field, jsonObject* node) {
901         growing_buffer* sql_buf = buffer_init(32);
902         
903         buffer_fadd(
904                 sql_buf,
905                 "%s IN (",
906                 osrfHashGet(field, "name")
907         );
908
909         int in_item_index = 0;
910         int in_item_first = 1;
911         jsonObject* in_item;
912         while ( (in_item = jsonObjectGetIndex(node, in_item_index++)) ) {
913
914                 if (in_item_first)
915                         in_item_first = 0;
916                 else
917                         buffer_add(sql_buf, ", ");
918
919                 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
920                         char* val = jsonNumberToDBString( field, in_item );
921                         buffer_fadd( sql_buf, "%s", val );
922                         free(val);
923
924                 } else {
925                         char* key_string = jsonObjectToSimpleString(in_item);
926                         if ( dbi_conn_quote_string(dbhandle, &key_string) ) {
927                                 buffer_fadd( sql_buf, "%s", key_string );
928                                 free(key_string);
929                         } else {
930                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, key_string);
931                                 free(key_string);
932                                 buffer_free(sql_buf);
933                                 return NULL;
934                         }
935                 }
936         }
937
938         buffer_add(
939                 sql_buf,
940                 ")"
941         );
942
943         char* pred = buffer_data(sql_buf);
944         buffer_free(sql_buf);
945
946         return pred;
947 }
948
949 char* searchValueTransform( jsonObject* array ) {
950         growing_buffer* sql_buf = buffer_init(32);
951
952         char* val = NULL;
953         int func_item_index = 0;
954         int func_item_first = 2;
955         jsonObject* func_item;
956         while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
957
958                 val = jsonObjectToSimpleString(func_item);
959
960                 if (func_item_first == 2) {
961                         buffer_fadd(sql_buf, "%s( ", val);
962                         free(val);
963                         func_item_first--;
964                         continue;
965                 }
966
967                 if (func_item_first)
968                         func_item_first--;
969                 else
970                         buffer_add(sql_buf, ", ");
971
972                 if ( dbi_conn_quote_string(dbhandle, &val) ) {
973                         buffer_fadd( sql_buf, "%s", val );
974                         free(val);
975                 } else {
976                         osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
977                         free(val);
978                         buffer_free(sql_buf);
979                         return NULL;
980                 }
981         }
982
983         buffer_add(
984                 sql_buf,
985                 " )"
986         );
987
988         char* pred = buffer_data(sql_buf);
989         buffer_free(sql_buf);
990
991         return pred;
992 }
993
994 char* searchFunctionPredicate (osrfHash* field, jsonObjectNode* node) {
995         growing_buffer* sql_buf = buffer_init(32);
996
997         char* val = searchValueTransform(node->item);
998         
999         buffer_fadd(
1000                 sql_buf,
1001                 "%s %s %s",
1002                 osrfHashGet(field, "name"),
1003                 node->key,
1004                 val
1005         );
1006
1007         char* pred = buffer_data(sql_buf);
1008         buffer_free(sql_buf);
1009         free(val);
1010
1011         return pred;
1012 }
1013
1014 char* searchFieldTransformPredicate (osrfHash* field, jsonObjectNode* node) {
1015         growing_buffer* sql_buf = buffer_init(32);
1016         
1017         char* field_transform = jsonObjectToSimpleString( jsonObjectGetKey( node->item, "transform" ) );
1018         char* value = NULL;
1019
1020         if (jsonObjectGetKey( node->item, "value" )->type == JSON_ARRAY) {
1021                 value = searchValueTransform(jsonObjectGetKey( node->item, "value" ));
1022         } else if (jsonObjectGetKey( node->item, "value" )->type != JSON_NULL) {
1023                 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1024                         value = jsonNumberToDBString( field, jsonObjectGetKey( node->item, "value" ) );
1025                 } else {
1026                         value = jsonObjectToSimpleString(jsonObjectGetKey( node->item, "value" ));
1027                         if ( !dbi_conn_quote_string(dbhandle, &value) ) {
1028                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, value);
1029                                 free(value);
1030                                 return NULL;
1031                         }
1032                 }
1033         }
1034
1035         buffer_fadd(
1036                 sql_buf,
1037                 "%s(%s) %s %s",
1038                 field_transform,
1039                 osrfHashGet(field, "name"),
1040                 node->key,
1041                 value
1042         );
1043
1044         char* pred = buffer_data(sql_buf);
1045         buffer_free(sql_buf);
1046
1047         return pred;
1048 }
1049
1050 char* searchSimplePredicate (const char* orig_op, osrfHash* field, jsonObject* node) {
1051
1052         char* val = NULL;
1053
1054         if (node->type != JSON_NULL) {
1055                 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1056                         val = jsonNumberToDBString( field, node );
1057                 } else {
1058                         val = jsonObjectToSimpleString(node);
1059                 }
1060         }
1061
1062         char* pred = searchWriteSimplePredicate( field, osrfHashGet(field, "name"), orig_op, val );
1063
1064         if (val) free(val);
1065
1066         return pred;
1067 }
1068
1069 char* searchWriteSimplePredicate ( osrfHash* field, const char* left, const char* orig_op, const char* right ) {
1070
1071         char* val = NULL;
1072         char* op = NULL;
1073         if (right == NULL) {
1074                 val = strdup("NULL");
1075
1076                 if (strcmp( orig_op, "=" ))
1077                         op = strdup("IS NOT");
1078                 else
1079                         op = strdup("IS");
1080
1081         } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1082                 val = strdup(right);
1083                 op = strdup(orig_op);
1084
1085         } else {
1086                 val = strdup(right);
1087                 if ( !dbi_conn_quote_string(dbhandle, &val) ) {
1088                         osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1089                         free(val);
1090                         return NULL;
1091                 }
1092                 op = strdup(orig_op);
1093         }
1094
1095         growing_buffer* sql_buf = buffer_init(16);
1096         buffer_fadd( sql_buf, "%s %s %s", left, op, val );
1097         free(val);
1098         free(op);
1099
1100         char* pred = buffer_data(sql_buf);
1101         buffer_free(sql_buf);
1102
1103         return pred;
1104
1105 }
1106
1107 char* searchBETWEENPredicate (osrfHash* field, jsonObject* node) {
1108
1109         char* x_string;
1110         char* y_string;
1111
1112         if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1113                 x_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,0));
1114                 y_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,1));
1115
1116         } else {
1117                 x_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,0));
1118                 y_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,1));
1119                 if ( !(dbi_conn_quote_string(dbhandle, &x_string) && dbi_conn_quote_string(dbhandle, &y_string)) ) {
1120                         osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key strings [%s] and [%s]", MODULENAME, x_string, y_string);
1121                         free(x_string);
1122                         free(y_string);
1123                         return NULL;
1124                 }
1125         }
1126
1127         growing_buffer* sql_buf = buffer_init(32);
1128         buffer_fadd( sql_buf, "%s BETWEEN %s AND %s", osrfHashGet(field, "name"), x_string, y_string );
1129         free(x_string);
1130         free(y_string);
1131
1132         char* pred = buffer_data(sql_buf);
1133         buffer_free(sql_buf);
1134
1135         return pred;
1136 }
1137
1138 char* searchPredicate ( osrfHash* field, jsonObject* node ) {
1139
1140         char* pred = NULL;
1141         if (node->type == JSON_ARRAY) { // equality IN search
1142                 pred = searchINPredicate( field, node );
1143         } else if (node->type == JSON_HASH) { // non-equality search
1144                 jsonObjectNode* pred_node;
1145                 jsonObjectIterator* pred_itr = jsonNewObjectIterator( node );
1146                 while ( (pred_node = jsonObjectIteratorNext( pred_itr )) ) {
1147                         if ( !(strcasecmp( pred_node->key,"between" )) )
1148                                 pred = searchBETWEENPredicate( field, pred_node->item );
1149                         else if ( !(strcasecmp( pred_node->key,"in" )) )
1150                                 pred = searchINPredicate( field, pred_node->item );
1151                         else if ( pred_node->item->type == JSON_ARRAY )
1152                                 pred = searchFunctionPredicate( field, pred_node );
1153                         else if ( pred_node->item->type == JSON_HASH )
1154                                 pred = searchFieldTransformPredicate( field, pred_node );
1155                         else 
1156                                 pred = searchSimplePredicate( pred_node->key, field, pred_node->item );
1157
1158                         break;
1159                 }
1160         } else if (node->type == JSON_NULL) { // IS NULL search
1161                 growing_buffer* _p = buffer_init(16);
1162                 buffer_fadd(
1163                         _p,
1164                         "%s IS NULL",
1165                         osrfHashGet(field, "name")
1166                 );
1167                 pred = buffer_data(_p);
1168                 buffer_free(_p);
1169         } else { // equality search
1170                 pred = searchSimplePredicate( "=", field, node );
1171         }
1172
1173         return pred;
1174
1175 }
1176
1177 jsonObject* doSearch(osrfMethodContext* ctx, osrfHash* meta, jsonObject* params, int* err ) {
1178
1179         // XXX for now...
1180         dbhandle = writehandle;
1181
1182         osrfHash* links = osrfHashGet(meta, "links");
1183         osrfHash* fields = osrfHashGet(meta, "fields");
1184         char* core_class = osrfHashGet(meta, "classname");
1185
1186         jsonObjectNode* node = NULL;
1187         jsonObjectNode* snode = NULL;
1188         jsonObject* _tmp;
1189         jsonObject* obj;
1190         jsonObject* search_hash = jsonObjectGetIndex(params, 0);
1191         jsonObject* order_hash = jsonObjectGetIndex(params, 1);
1192
1193         growing_buffer* sql_buf = buffer_init(128);
1194         buffer_add(sql_buf, "SELECT");
1195
1196         int first = 1;
1197         if ( (_tmp = jsonObjectGetKey( order_hash, "select" )) ) {
1198
1199                 jsonObjectIterator* class_itr = jsonNewObjectIterator( _tmp );
1200                 while ( (snode = jsonObjectIteratorNext( class_itr )) ) {
1201
1202                         osrfHash* idlClass = osrfHashGet( idl, snode->key );
1203                         if (!idlClass) continue;
1204                         char* cname = osrfHashGet(idlClass, "classname");
1205
1206                         if (strcmp(core_class,snode->key)) continue;
1207
1208                         jsonObjectIterator* select_itr = jsonNewObjectIterator( snode->item );
1209                         while ( (node = jsonObjectIteratorNext( select_itr )) ) {
1210                                 osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), jsonObjectToSimpleString(node->item) );
1211                                 char* fname = osrfHashGet(field, "name");
1212
1213                                 if (!field) continue;
1214
1215                                 if (first) {
1216                                         first = 0;
1217                                 } else {
1218                                         buffer_add(sql_buf, ",");
1219                                 }
1220
1221                                 buffer_fadd(sql_buf, " \"%s\".%s", cname, fname, cname, fname);
1222                         }
1223                 }
1224
1225                 if (first) buffer_add(sql_buf, " *");
1226
1227         } else {
1228                 buffer_add(sql_buf, " *");
1229         }
1230
1231         buffer_fadd(sql_buf, " FROM %s AS \"%s\" WHERE ", osrfHashGet(meta, "tablename"), core_class );
1232
1233
1234         char* pred;
1235         first = 1;
1236         jsonObjectIterator* search_itr = jsonNewObjectIterator( search_hash );
1237         while ( (node = jsonObjectIteratorNext( search_itr )) ) {
1238                 osrfHash* field = osrfHashGet( fields, node->key );
1239
1240                 if (!field) continue;
1241
1242                 if (first) {
1243                         first = 0;
1244                 } else {
1245                         buffer_add(sql_buf, " AND ");
1246                 }
1247
1248                 pred = searchPredicate( field, node->item);
1249                 buffer_fadd( sql_buf, "%s", pred );
1250                 free(pred);
1251         }
1252
1253         jsonObjectIteratorFree(search_itr);
1254
1255         if (order_hash) {
1256                 char* string;
1257                 if ( (_tmp = jsonObjectGetKey( jsonObjectGetKey( order_hash, "order_by" ), core_class ) ) ){
1258                         string = jsonObjectToSimpleString(_tmp);
1259                         buffer_fadd(
1260                                 sql_buf,
1261                                 " ORDER BY %s",
1262                                 string
1263                         );
1264                         free(string);
1265                 }
1266
1267                 if ( (_tmp = jsonObjectGetKey( order_hash, "limit" )) ){
1268                         string = jsonObjectToSimpleString(_tmp);
1269                         buffer_fadd(
1270                                 sql_buf,
1271                                 " LIMIT %d",
1272                                 atoi(string)
1273                         );
1274                         free(string);
1275                 }
1276
1277                 _tmp = jsonObjectGetKey( order_hash, "offset" );
1278                 if (_tmp) {
1279                         string = jsonObjectToSimpleString(_tmp);
1280                         buffer_fadd(
1281                                 sql_buf,
1282                                 " OFFSET %d",
1283                                 atoi(string)
1284                         );
1285                         free(string);
1286                 }
1287         }
1288
1289         buffer_add(sql_buf, ";");
1290
1291         char* sql = buffer_data(sql_buf);
1292         buffer_free(sql_buf);
1293         
1294         osrfLogDebug(OSRF_LOG_MARK, "%s SQL =  %s", MODULENAME, sql);
1295         dbi_result result = dbi_conn_query(dbhandle, sql);
1296
1297         jsonObject* res_list = jsonParseString("[]");
1298         if(result) {
1299                 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
1300
1301                 if (dbi_result_first_row(result)) {
1302                         /* JSONify the result */
1303                         osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
1304                         do {
1305                                 obj = oilsMakeJSONFromResult( result, meta );
1306                                 jsonObjectPush(res_list, obj);
1307                         } while (dbi_result_next_row(result));
1308                 } else {
1309                         osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
1310                 }
1311
1312                 /* clean up the query */
1313                 dbi_result_free(result); 
1314
1315         } else {
1316                 osrfLogError(OSRF_LOG_MARK, "%s: Error retrieving %s with query [%s]", MODULENAME, osrfHashGet(meta, "fieldmapper"), sql);
1317                 osrfAppSessionStatus(
1318                         ctx->session,
1319                         OSRF_STATUS_INTERNALSERVERERROR,
1320                         "osrfMethodException",
1321                         ctx->request,
1322                         "Severe query error -- see error log for more details"
1323                 );
1324                 *err = -1;
1325                 free(sql);
1326                 jsonObjectFree(res_list);
1327                 return jsonNULL;
1328
1329         }
1330
1331         free(sql);
1332
1333         if (res_list->size && order_hash) {
1334                 _tmp = jsonObjectGetKey( order_hash, "flesh" );
1335                 if (_tmp) {
1336                         int x = (int)jsonObjectGetNumber(_tmp);
1337
1338                         jsonObject* flesh_blob = NULL;
1339                         if ((flesh_blob = jsonObjectGetKey( order_hash, "flesh_fields" )) && x > 0) {
1340
1341                                 flesh_blob = jsonObjectClone( flesh_blob );
1342                                 jsonObject* flesh_fields = jsonObjectGetKey( flesh_blob, core_class );
1343
1344                                 osrfStringArray* link_fields = NULL;
1345
1346                                 if (flesh_fields) {
1347                                         if (flesh_fields->size == 1) {
1348                                                 char* _t = jsonObjectToSimpleString( jsonObjectGetIndex( flesh_fields, 0 ) );
1349                                                 if (!strcmp(_t,"*")) link_fields = osrfHashKeys( links );
1350                                                 free(_t);
1351                                         }
1352
1353                                         if (!link_fields) {
1354                                                 jsonObjectNode* _f;
1355                                                 link_fields = osrfNewStringArray(1);
1356                                                 jsonObjectIterator* _i = jsonNewObjectIterator( flesh_fields );
1357                                                 while ((_f = jsonObjectIteratorNext( _i ))) {
1358                                                         osrfStringArrayAdd( link_fields, jsonObjectToSimpleString( _f->item ) );
1359                                                 }
1360                                         }
1361                                 }
1362
1363                                 jsonObjectNode* cur;
1364                                 jsonObjectIterator* itr = jsonNewObjectIterator( res_list );
1365                                 while ((cur = jsonObjectIteratorNext( itr ))) {
1366
1367                                         int i = 0;
1368                                         char* link_field;
1369                                         
1370                                         while ( (link_field = osrfStringArrayGetString(link_fields, i++)) ) {
1371
1372                                                 osrfLogDebug(OSRF_LOG_MARK, "Starting to flesh %s", link_field);
1373
1374                                                 osrfHash* kid_link = osrfHashGet(links, link_field);
1375                                                 if (!kid_link) continue;
1376
1377                                                 osrfHash* field = osrfHashGet(fields, link_field);
1378                                                 if (!field) continue;
1379
1380                                                 osrfHash* value_field = field;
1381
1382                                                 osrfHash* kid_idl = osrfHashGet(idl, osrfHashGet(kid_link, "class"));
1383                                                 if (!kid_idl) continue;
1384
1385                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
1386                                                         value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
1387                                                 }
1388                                                         
1389                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) { // might_have
1390                                                         value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
1391                                                 }
1392
1393                                                 osrfStringArray* link_map = osrfHashGet( kid_link, "map" );
1394
1395                                                 if (link_map->size > 0) {
1396                                                         jsonObject* _kid_key = jsonParseString("[]");
1397                                                         jsonObjectPush(
1398                                                                 _kid_key,
1399                                                                 jsonNewObject( osrfStringArrayGetString( link_map, 0 ) )
1400                                                         );
1401
1402                                                         jsonObjectSetKey(
1403                                                                 flesh_blob,
1404                                                                 osrfHashGet(kid_link, "class"),
1405                                                                 _kid_key
1406                                                         );
1407                                                 };
1408
1409                                                 osrfLogDebug(
1410                                                         OSRF_LOG_MARK,
1411                                                         "Link field: %s, remote class: %s, fkey: %s, reltype: %s",
1412                                                         osrfHashGet(kid_link, "field"),
1413                                                         osrfHashGet(kid_link, "class"),
1414                                                         osrfHashGet(kid_link, "key"),
1415                                                         osrfHashGet(kid_link, "reltype")
1416                                                 );
1417
1418                                                 jsonObject* fake_params = jsonParseString("[]");
1419                                                 jsonObjectPush(fake_params, jsonParseString("{}")); // search hash
1420                                                 jsonObjectPush(fake_params, jsonParseString("{}")); // order/flesh hash
1421
1422                                                 osrfLogDebug(OSRF_LOG_MARK, "Creating dummy params object...");
1423
1424                                                 char* search_key =
1425                                                 jsonObjectToSimpleString(
1426                                                         jsonObjectGetIndex(
1427                                                                 cur->item,
1428                                                                 atoi( osrfHashGet(value_field, "array_position") )
1429                                                         )
1430                                                 );
1431
1432                                                 if (!search_key) {
1433                                                         osrfLogDebug(OSRF_LOG_MARK, "Nothing to search for!");
1434                                                         continue;
1435                                                 }
1436                                                         
1437                                                 jsonObjectSetKey(
1438                                                         jsonObjectGetIndex(fake_params, 0),
1439                                                         osrfHashGet(kid_link, "key"),
1440                                                         jsonNewObject( search_key )
1441                                                 );
1442
1443                                                 free(search_key);
1444
1445
1446                                                 jsonObjectSetKey(
1447                                                         jsonObjectGetIndex(fake_params, 1),
1448                                                         "flesh",
1449                                                         jsonNewNumberObject( (double)(x - 1 + link_map->size) )
1450                                                 );
1451
1452                                                 if (flesh_blob)
1453                                                         jsonObjectSetKey( jsonObjectGetIndex(fake_params, 1), "flesh_fields", jsonObjectClone(flesh_blob) );
1454
1455                                                 if (jsonObjectGetKey(order_hash, "order_by")) {
1456                                                         jsonObjectSetKey(
1457                                                                 jsonObjectGetIndex(fake_params, 1),
1458                                                                 "order_by",
1459                                                                 jsonObjectClone(jsonObjectGetKey(order_hash, "order_by"))
1460                                                         );
1461                                                 }
1462
1463                                                 if (jsonObjectGetKey(order_hash, "select")) {
1464                                                         jsonObjectSetKey(
1465                                                                 jsonObjectGetIndex(fake_params, 1),
1466                                                                 "select",
1467                                                                 jsonObjectClone(jsonObjectGetKey(order_hash, "select"))
1468                                                         );
1469                                                 }
1470
1471                                                 jsonObject* kids = doSearch(ctx, kid_idl, fake_params, err);
1472
1473                                                 if(*err) {
1474                                                         jsonObjectFree( fake_params );
1475                                                         osrfStringArrayFree(link_fields);
1476                                                         jsonObjectIteratorFree(itr);
1477                                                         jsonObjectFree(res_list);
1478                                                         return jsonNULL;
1479                                                 }
1480
1481                                                 osrfLogDebug(OSRF_LOG_MARK, "Search for %s return %d linked objects", osrfHashGet(kid_link, "class"), kids->size);
1482
1483                                                 jsonObject* X = NULL;
1484                                                 if ( link_map->size > 0 && kids->size > 0 ) {
1485                                                         X = kids;
1486                                                         kids = jsonParseString("[]");
1487
1488                                                         jsonObjectNode* _k_node;
1489                                                         jsonObjectIterator* _k = jsonNewObjectIterator( X );
1490                                                         while ((_k_node = jsonObjectIteratorNext( _k ))) {
1491                                                                 jsonObjectPush(
1492                                                                         kids,
1493                                                                         jsonObjectClone(
1494                                                                                 jsonObjectGetIndex(
1495                                                                                         _k_node->item,
1496                                                                                         (unsigned long)atoi(
1497                                                                                                 osrfHashGet(
1498                                                                                                         osrfHashGet(
1499                                                                                                                 osrfHashGet(
1500                                                                                                                         osrfHashGet(
1501                                                                                                                                 idl,
1502                                                                                                                                 osrfHashGet(kid_link, "class")
1503                                                                                                                         ),
1504                                                                                                                         "fields"
1505                                                                                                                 ),
1506                                                                                                                 osrfStringArrayGetString( link_map, 0 )
1507                                                                                                         ),
1508                                                                                                         "array_position"
1509                                                                                                 )
1510                                                                                         )
1511                                                                                 )
1512                                                                         )
1513                                                                 );
1514                                                         }
1515                                                 }
1516
1517                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_a" ))) {
1518                                                         osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
1519                                                         jsonObjectSetIndex(
1520                                                                 cur->item,
1521                                                                 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
1522                                                                 jsonObjectClone( jsonObjectGetIndex(kids, 0) )
1523                                                         );
1524                                                 }
1525
1526                                                 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
1527                                                         osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
1528                                                         jsonObjectSetIndex(
1529                                                                 cur->item,
1530                                                                 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
1531                                                                 jsonObjectClone( kids )
1532                                                         );
1533                                                 }
1534
1535                                                 if (X) {
1536                                                         jsonObjectFree(kids);
1537                                                         kids = X;
1538                                                 }
1539
1540                                                 jsonObjectFree( kids );
1541                                                 jsonObjectFree( fake_params );
1542
1543                                                 osrfLogDebug(OSRF_LOG_MARK, "Fleshing of %s complete", osrfHashGet(kid_link, "field"));
1544                                                 osrfLogDebug(OSRF_LOG_MARK, "%s", jsonObjectToJSON(cur->item));
1545
1546                                         }
1547                                 }
1548                                 jsonObjectFree( flesh_blob );
1549                                 osrfStringArrayFree(link_fields);
1550                                 jsonObjectIteratorFree(itr);
1551                         }
1552                 }
1553         }
1554
1555         return res_list;
1556 }
1557
1558
1559 jsonObject* doUpdate(osrfMethodContext* ctx, int* err ) {
1560
1561         osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1562         jsonObject* target = jsonObjectGetIndex(ctx->params, 0);
1563
1564         if (!verifyObjectClass(ctx, target)) {
1565                 *err = -1;
1566                 return jsonNULL;
1567         }
1568
1569         if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
1570                 osrfAppSessionStatus(
1571                         ctx->session,
1572                         OSRF_STATUS_BADREQUEST,
1573                         "osrfMethodException",
1574                         ctx->request,
1575                         "No active transaction -- required for UPDATE"
1576                 );
1577                 *err = -1;
1578                 return jsonNULL;
1579         }
1580
1581         dbhandle = writehandle;
1582
1583         char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
1584
1585         // Set the last_xact_id
1586         osrfHash* last_xact_id;
1587         if ((last_xact_id = oilsIDLFindPath("/%s/fields/last_xact_id", target->classname))) {
1588                 int index = atoi( osrfHashGet(last_xact_id, "array_position") );
1589                 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
1590                 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
1591         }       
1592
1593         char* pkey = osrfHashGet(meta, "primarykey");
1594         osrfHash* fields = osrfHashGet(meta, "fields");
1595
1596         char* id =
1597                 jsonObjectToSimpleString(
1598                         jsonObjectGetIndex(
1599                                 target,
1600                                 atoi( osrfHashGet( osrfHashGet( fields, pkey ), "array_position" ) )
1601                         )
1602                 );
1603
1604         osrfLogDebug(
1605                 OSRF_LOG_MARK,
1606                 "%s updating %s object with %s = %s",
1607                 MODULENAME,
1608                 osrfHashGet(meta, "fieldmapper"),
1609                 pkey,
1610                 id
1611         );
1612
1613         growing_buffer* sql = buffer_init(128);
1614         buffer_fadd(sql,"UPDATE %s SET", osrfHashGet(meta, "tablename"));
1615
1616         int i = 0;
1617         int first = 1;
1618         char* field_name;
1619         osrfStringArray* field_list = osrfHashKeys( fields );
1620         while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
1621
1622                 osrfHash* field = osrfHashGet( fields, field_name );
1623
1624                 if(!( strcmp( field_name, pkey ) )) continue;
1625                 if(!( strcmp( osrfHashGet(osrfHashGet(fields,field_name), "virtual"), "true" ) )) continue;
1626
1627                 int pos = atoi(osrfHashGet(field, "array_position"));
1628                 char* value = jsonObjectToSimpleString( jsonObjectGetIndex( target, pos ) );
1629
1630                 osrfLogDebug( OSRF_LOG_MARK, "Updating %s object with %s = %s", osrfHashGet(meta, "fieldmapper"), field_name, value);
1631
1632                 if (!jsonObjectGetIndex(target, pos) || jsonObjectGetIndex(target, pos)->type == JSON_NULL) {
1633                         if ( !(!( strcmp( osrfHashGet(meta, "classname"), "au" ) ) && !( strcmp( field_name, "passwd" ) )) ) { // arg at the special case!
1634                                 if (first) first = 0;
1635                                 else buffer_add(sql, ",");
1636                                 buffer_fadd( sql, " %s = NULL", field_name );
1637                         }
1638                         
1639                 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1640                         if (first) first = 0;
1641                         else buffer_add(sql, ",");
1642
1643                         if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
1644                                 buffer_fadd( sql, " %s = %ld", field_name, atol(value) );
1645                         } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
1646                                 buffer_fadd( sql, " %s = %f", field_name, atof(value) );
1647                         }
1648
1649                         osrfLogDebug( OSRF_LOG_MARK, "%s is of type %s", field_name, osrfHashGet(field, "datatype"));
1650
1651                 } else {
1652                         if ( dbi_conn_quote_string(dbhandle, &value) ) {
1653                                 if (first) first = 0;
1654                                 else buffer_add(sql, ",");
1655                                 buffer_fadd( sql, " %s = %s", field_name, value );
1656
1657                         } else {
1658                                 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
1659                                 osrfAppSessionStatus(
1660                                         ctx->session,
1661                                         OSRF_STATUS_INTERNALSERVERERROR,
1662                                         "osrfMethodException",
1663                                         ctx->request,
1664                                         "Error quoting string -- please see the error log for more details"
1665                                 );
1666                                 free(value);
1667                                 free(id);
1668                                 buffer_free(sql);
1669                                 *err = -1;
1670                                 return jsonNULL;
1671                         }
1672                 }
1673
1674                 free(value);
1675                 
1676         }
1677
1678         jsonObject* obj = jsonParseString(id);
1679
1680         if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
1681                 dbi_conn_quote_string(dbhandle, &id);
1682
1683         buffer_fadd( sql, " WHERE %s = %s;", pkey, id );
1684
1685         char* query = buffer_data(sql);
1686         buffer_free(sql);
1687
1688         osrfLogDebug(OSRF_LOG_MARK, "%s: Update SQL [%s]", MODULENAME, query);
1689
1690         dbi_result result = dbi_conn_query(dbhandle, query);
1691         free(query);
1692
1693         if (!result) {
1694                 jsonObjectFree(obj);
1695                 obj = jsonNewObject(NULL);
1696                 osrfLogError(
1697                         OSRF_LOG_MARK,
1698                         "%s ERROR updating %s object with %s = %s",
1699                         MODULENAME,
1700                         osrfHashGet(meta, "fieldmapper"),
1701                         pkey,
1702                         id
1703                 );
1704         }
1705
1706         free(id);
1707
1708         return obj;
1709 }
1710
1711 jsonObject* doDelete(osrfMethodContext* ctx, int* err ) {
1712
1713         osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1714
1715         if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
1716                 osrfAppSessionStatus(
1717                         ctx->session,
1718                         OSRF_STATUS_BADREQUEST,
1719                         "osrfMethodException",
1720                         ctx->request,
1721                         "No active transaction -- required for DELETE"
1722                 );
1723                 *err = -1;
1724                 return jsonNULL;
1725         }
1726
1727         dbhandle = writehandle;
1728
1729         jsonObject* obj;
1730
1731         char* pkey = osrfHashGet(meta, "primarykey");
1732
1733         char* id;
1734         if (jsonObjectGetIndex(ctx->params, 0)->classname) {
1735                 if (!verifyObjectClass(ctx, jsonObjectGetIndex( ctx->params, 0 ))) {
1736                         *err = -1;
1737                         return jsonNULL;
1738                 }
1739
1740                 id = jsonObjectToSimpleString(
1741                         jsonObjectGetIndex(
1742                                 jsonObjectGetIndex(ctx->params, 0),
1743                                 atoi( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "array_position") )
1744                         )
1745                 );
1746         } else {
1747                 id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
1748         }
1749
1750         osrfLogDebug(
1751                 OSRF_LOG_MARK,
1752                 "%s deleting %s object with %s = %s",
1753                 MODULENAME,
1754                 osrfHashGet(meta, "fieldmapper"),
1755                 pkey,
1756                 id
1757         );
1758
1759         obj = jsonParseString(id);
1760
1761         if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
1762                 dbi_conn_quote_string(writehandle, &id);
1763
1764         dbi_result result = dbi_conn_queryf(writehandle, "DELETE FROM %s WHERE %s = %s;", osrfHashGet(meta, "tablename"), pkey, id);
1765
1766         if (!result) {
1767                 jsonObjectFree(obj);
1768                 obj = jsonNewObject(NULL);
1769                 osrfLogError(
1770                         OSRF_LOG_MARK,
1771                         "%s ERROR deleting %s object with %s = %s",
1772                         MODULENAME,
1773                         osrfHashGet(meta, "fieldmapper"),
1774                         pkey,
1775                         id
1776                 );
1777         }
1778
1779         free(id);
1780
1781         return obj;
1782
1783 }
1784
1785
1786 jsonObject* oilsMakeJSONFromResult( dbi_result result, osrfHash* meta) {
1787         if(!(result && meta)) return jsonNULL;
1788
1789         jsonObject* object = jsonParseString("[]");
1790         jsonObjectSetClass(object, osrfHashGet(meta, "classname"));
1791
1792         osrfHash* fields = osrfHashGet(meta, "fields");
1793
1794         osrfLogInternal(OSRF_LOG_MARK, "Setting object class to %s ", object->classname);
1795
1796         osrfHash* _f;
1797         time_t _tmp_dt;
1798         char dt_string[256];
1799         struct tm gmdt;
1800
1801         int fmIndex;
1802         int columnIndex = 1;
1803         int attr;
1804         unsigned short type;
1805         const char* columnName;
1806
1807         /* cycle through the column list */
1808         while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
1809
1810                 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
1811
1812                 fmIndex = -1; // reset the position
1813                 
1814                 /* determine the field type and storage attributes */
1815                 type = dbi_result_get_field_type(result, columnName);
1816                 attr = dbi_result_get_field_attribs(result, columnName);
1817
1818                 /* fetch the fieldmapper index */
1819                 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
1820                         char* virt = (char*)osrfHashGet(_f, "virtual");
1821                         char* pos = (char*)osrfHashGet(_f, "array_position");
1822
1823                         if ( !virt || !pos || !(strcmp( virt, "true" )) ) continue;
1824
1825                         fmIndex = atoi( pos );
1826                         osrfLogInternal(OSRF_LOG_MARK, "... Found column at position [%s]...", pos);
1827                 } else {
1828                         continue;
1829                 }
1830
1831                 if (dbi_result_field_is_null(result, columnName)) {
1832                         jsonObjectSetIndex( object, fmIndex, jsonNewObject(NULL) );
1833                 } else {
1834
1835                         switch( type ) {
1836
1837                                 case DBI_TYPE_INTEGER :
1838
1839                                         if( attr & DBI_INTEGER_SIZE8 ) 
1840                                                 jsonObjectSetIndex( object, fmIndex, 
1841                                                         jsonNewNumberObject(dbi_result_get_longlong(result, columnName)));
1842                                         else 
1843                                                 jsonObjectSetIndex( object, fmIndex, 
1844                                                         jsonNewNumberObject(dbi_result_get_long(result, columnName)));
1845
1846                                         break;
1847
1848                                 case DBI_TYPE_DECIMAL :
1849                                         jsonObjectSetIndex( object, fmIndex, 
1850                                                         jsonNewNumberObject(dbi_result_get_double(result, columnName)));
1851                                         break;
1852
1853                                 case DBI_TYPE_STRING :
1854
1855
1856                                         jsonObjectSetIndex(
1857                                                 object,
1858                                                 fmIndex,
1859                                                 jsonNewObject( dbi_result_get_string(result, columnName) )
1860                                         );
1861
1862                                         break;
1863
1864                                 case DBI_TYPE_DATETIME :
1865
1866                                         memset(dt_string, '\0', 256);
1867                                         memset(&gmdt, '\0', sizeof(gmdt));
1868                                         memset(&_tmp_dt, '\0', sizeof(_tmp_dt));
1869
1870                                         _tmp_dt = dbi_result_get_datetime(result, columnName);
1871
1872                                         localtime_r( &_tmp_dt, &gmdt );
1873
1874                                         if (!(attr & DBI_DATETIME_DATE)) {
1875                                                 strftime(dt_string, 255, "%T", &gmdt);
1876                                         } else if (!(attr & DBI_DATETIME_TIME)) {
1877                                                 strftime(dt_string, 255, "%F", &gmdt);
1878                                         } else {
1879                                                 strftime(dt_string, 255, "%FT%T%z", &gmdt);
1880                                         }
1881
1882                                         jsonObjectSetIndex( object, fmIndex, jsonNewObject(dt_string) );
1883
1884                                         break;
1885
1886                                 case DBI_TYPE_BINARY :
1887                                         osrfLogError( OSRF_LOG_MARK, 
1888                                                 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
1889                         }
1890                 }
1891         }
1892
1893         return object;
1894 }
1895