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