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"
16 # define MODULENAME "open-ils.reporter-store"
19 # define MODULENAME "open-ils.pcrud"
21 # define MODULENAME "open-ils.cstore"
26 #define DISABLE_I18N 2
27 #define SELECT_DISTINCT 1
31 int osrfAppChildInit();
32 int osrfAppInitialize();
33 void osrfAppChildExit();
35 static int verifyObjectClass ( osrfMethodContext*, const jsonObject* );
37 int beginTransaction ( osrfMethodContext* );
38 int commitTransaction ( osrfMethodContext* );
39 int rollbackTransaction ( osrfMethodContext* );
41 int setSavepoint ( osrfMethodContext* );
42 int releaseSavepoint ( osrfMethodContext* );
43 int rollbackSavepoint ( osrfMethodContext* );
45 int doJSONSearch ( osrfMethodContext* );
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 );
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*,
65 jsonObject*, const char*, osrfMethodContext* );
66 static char* searchPredicate ( const char*, osrfHash*, jsonObject*, osrfMethodContext* );
67 static char* searchJOIN ( const jsonObject*, osrfHash* );
68 static char* searchWHERE ( const jsonObject*, osrfHash*, int, osrfMethodContext* );
69 static char* buildSELECT ( jsonObject*, jsonObject*, osrfHash*, osrfMethodContext* );
71 char* SELECT ( osrfMethodContext*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, int );
73 void userDataFree( void* );
74 static void sessionDataFree( char*, void* );
75 static char* getSourceDefinition( osrfHash* );
76 static int str_is_true( const char* str );
77 static int obj_is_true( const jsonObject* obj );
80 static jsonObject* verifyUserPCRUD( osrfMethodContext* );
81 static int verifyObjectPCRUD( osrfMethodContext*, const jsonObject* );
84 static dbi_conn writehandle; /* our MASTER db connection */
85 static dbi_conn dbhandle; /* our CURRENT db connection */
86 //static osrfHash * readHandles;
87 static jsonObject* jsonNULL = NULL; //
88 static int max_flesh_depth = 100;
90 /* called when this process is about to exit */
91 void osrfAppChildExit() {
92 osrfLogDebug(OSRF_LOG_MARK, "Child is exiting, disconnecting from database...");
95 if (writehandle == dbhandle) same = 1;
97 dbi_conn_query(writehandle, "ROLLBACK;");
98 dbi_conn_close(writehandle);
101 if (dbhandle && !same)
102 dbi_conn_close(dbhandle);
104 // XXX add cleanup of readHandles whenever that gets used
109 int osrfAppInitialize() {
111 osrfLogInfo(OSRF_LOG_MARK, "Initializing the CStore Server...");
112 osrfLogInfo(OSRF_LOG_MARK, "Finding XML file...");
114 if (!oilsIDLInit( osrf_settings_host_value("/IDL") )) return 1; /* return non-zero to indicate error */
116 growing_buffer* method_name = buffer_init(64);
118 // Generic search thingy
119 buffer_add(method_name, MODULENAME);
120 buffer_add(method_name, ".json_query");
121 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
122 "doJSONSearch", "", 1, OSRF_METHOD_STREAMING );
125 // first we register all the transaction and savepoint methods
126 buffer_reset(method_name);
127 OSRF_BUFFER_ADD(method_name, MODULENAME);
128 OSRF_BUFFER_ADD(method_name, ".transaction.begin");
129 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
130 "beginTransaction", "", 0, 0 );
132 buffer_reset(method_name);
133 OSRF_BUFFER_ADD(method_name, MODULENAME);
134 OSRF_BUFFER_ADD(method_name, ".transaction.commit");
135 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
136 "commitTransaction", "", 0, 0 );
138 buffer_reset(method_name);
139 OSRF_BUFFER_ADD(method_name, MODULENAME);
140 OSRF_BUFFER_ADD(method_name, ".transaction.rollback");
141 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
142 "rollbackTransaction", "", 0, 0 );
144 buffer_reset(method_name);
145 OSRF_BUFFER_ADD(method_name, MODULENAME);
146 OSRF_BUFFER_ADD(method_name, ".savepoint.set");
147 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
148 "setSavepoint", "", 1, 0 );
150 buffer_reset(method_name);
151 OSRF_BUFFER_ADD(method_name, MODULENAME);
152 OSRF_BUFFER_ADD(method_name, ".savepoint.release");
153 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
154 "releaseSavepoint", "", 1, 0 );
156 buffer_reset(method_name);
157 OSRF_BUFFER_ADD(method_name, MODULENAME);
158 OSRF_BUFFER_ADD(method_name, ".savepoint.rollback");
159 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
160 "rollbackSavepoint", "", 1, 0 );
162 buffer_free(method_name);
164 static const char* global_method[] = {
172 const int global_method_count
173 = sizeof( global_method ) / sizeof ( global_method[0] );
177 osrfStringArray* classes = osrfHashKeys( oilsIDL() );
178 osrfLogDebug(OSRF_LOG_MARK, "%d classes loaded", classes->size );
179 osrfLogDebug(OSRF_LOG_MARK,
180 "At least %d methods will be generated", classes->size * global_method_count);
182 while ( (classname = osrfStringArrayGetString(classes, c_index++)) ) {
183 osrfLogInfo(OSRF_LOG_MARK, "Generating class methods for %s", classname);
185 osrfHash* idlClass = osrfHashGet(oilsIDL(), classname);
187 if (!osrfStringArrayContains( osrfHashGet(idlClass, "controller"), MODULENAME )) {
188 osrfLogInfo(OSRF_LOG_MARK, "%s is not listed as a controller for %s, moving on", MODULENAME, classname);
192 if ( str_is_true( osrfHashGet(idlClass, "virtual") ) ) {
193 osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
197 // Look up some other attributes of the current class
198 const char* idlClass_fieldmapper = osrfHashGet(idlClass, "fieldmapper");
199 const char* readonly = osrfHashGet(idlClass, "readonly");
201 osrfHash* idlClass_permacrud = osrfHashGet(idlClass, "permacrud");
205 for( i = 0; i < global_method_count; ++i ) {
206 const char* method_type = global_method[ i ];
207 osrfLogDebug(OSRF_LOG_MARK,
208 "Using files to build %s class methods for %s", method_type, classname);
210 if (!idlClass_fieldmapper) continue;
213 if (!idlClass_permacrud) continue;
215 const char* tmp_method = method_type;
216 if ( *tmp_method == 'i' || *tmp_method == 's') {
217 tmp_method = "retrieve";
219 if (!osrfHashGet( idlClass_permacrud, tmp_method )) continue;
222 if ( str_is_true( readonly ) &&
223 ( *method_type == 'c' || *method_type == 'u' || *method_type == 'd')
226 osrfHash* method_meta = osrfNewHash();
227 osrfHashSet(method_meta, idlClass, "class");
229 method_name = buffer_init(64);
231 buffer_fadd(method_name, "%s.%s.%s", MODULENAME, method_type, classname);
235 char* _fm = strdup( idlClass_fieldmapper );
236 part = strtok_r(_fm, ":", &st_tmp);
238 buffer_fadd(method_name, "%s.direct.%s", MODULENAME, part);
240 while ((part = strtok_r(NULL, ":", &st_tmp))) {
241 OSRF_BUFFER_ADD_CHAR(method_name, '.');
242 OSRF_BUFFER_ADD(method_name, part);
244 OSRF_BUFFER_ADD_CHAR(method_name, '.');
245 OSRF_BUFFER_ADD(method_name, method_type);
249 char* method = buffer_release(method_name);
251 osrfHashSet( method_meta, method, "methodname" );
252 osrfHashSet( method_meta, strdup(method_type), "methodtype" );
255 if (*method_type == 'i' || *method_type == 's') {
256 flags = flags | OSRF_METHOD_STREAMING;
259 osrfAppRegisterExtendedMethod(
262 "dispatchCRUDMethod",
276 static char* getSourceDefinition( osrfHash* class ) {
278 char* tabledef = osrfHashGet(class, "tablename");
281 tabledef = strdup(tabledef);
283 tabledef = osrfHashGet(class, "source_definition");
285 growing_buffer* tablebuf = buffer_init(128);
286 buffer_fadd( tablebuf, "(%s)", tabledef );
287 tabledef = buffer_release(tablebuf);
289 const char* classname = osrfHashGet( class, "classname" );
294 "%s ERROR No tablename or source_definition for class \"%s\"",
305 * Connects to the database
307 int osrfAppChildInit() {
309 osrfLogDebug(OSRF_LOG_MARK, "Attempting to initialize libdbi...");
310 dbi_initialize(NULL);
311 osrfLogDebug(OSRF_LOG_MARK, "... libdbi initialized.");
313 char* driver = osrf_settings_host_value("/apps/%s/app_settings/driver", MODULENAME);
314 char* user = osrf_settings_host_value("/apps/%s/app_settings/database/user", MODULENAME);
315 char* host = osrf_settings_host_value("/apps/%s/app_settings/database/host", MODULENAME);
316 char* port = osrf_settings_host_value("/apps/%s/app_settings/database/port", MODULENAME);
317 char* db = osrf_settings_host_value("/apps/%s/app_settings/database/db", MODULENAME);
318 char* pw = osrf_settings_host_value("/apps/%s/app_settings/database/pw", MODULENAME);
319 char* md = osrf_settings_host_value("/apps/%s/app_settings/max_query_recursion", MODULENAME);
321 osrfLogDebug(OSRF_LOG_MARK, "Attempting to load the database driver [%s]...", driver);
322 writehandle = dbi_conn_new(driver);
325 osrfLogError(OSRF_LOG_MARK, "Error loading database driver [%s]", driver);
328 osrfLogDebug(OSRF_LOG_MARK, "Database driver [%s] seems OK", driver);
330 osrfLogInfo(OSRF_LOG_MARK, "%s connecting to database. host=%s, "
331 "port=%s, user=%s, pw=%s, db=%s", MODULENAME, host, port, user, pw, db );
333 if(host) dbi_conn_set_option(writehandle, "host", host );
334 if(port) dbi_conn_set_option_numeric( writehandle, "port", atoi(port) );
335 if(user) dbi_conn_set_option(writehandle, "username", user);
336 if(pw) dbi_conn_set_option(writehandle, "password", pw );
337 if(db) dbi_conn_set_option(writehandle, "dbname", db );
339 if(md) max_flesh_depth = atoi(md);
340 if(max_flesh_depth < 0) max_flesh_depth = 1;
341 if(max_flesh_depth > 1000) max_flesh_depth = 1000;
350 if (dbi_conn_connect(writehandle) < 0) {
352 if (dbi_conn_connect(writehandle) < 0) {
353 dbi_conn_error(writehandle, &err);
354 osrfLogError( OSRF_LOG_MARK, "Error connecting to database: %s", err);
359 osrfLogInfo(OSRF_LOG_MARK, "%s successfully connected to the database", MODULENAME);
365 osrfStringArray* classes = osrfHashKeys( oilsIDL() );
367 while ( (classname = osrfStringArrayGetString(classes, i++)) ) {
368 osrfHash* class = osrfHashGet( oilsIDL(), classname );
369 osrfHash* fields = osrfHashGet( class, "fields" );
371 if( str_is_true( osrfHashGet(class, "virtual") ) ) {
372 osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
376 char* tabledef = getSourceDefinition(class);
378 tabledef = strdup( "(null)" );
380 growing_buffer* sql_buf = buffer_init(32);
381 buffer_fadd( sql_buf, "SELECT * FROM %s AS x WHERE 1=0;", tabledef );
385 char* sql = buffer_release(sql_buf);
386 osrfLogDebug(OSRF_LOG_MARK, "%s Investigatory SQL = %s", MODULENAME, sql);
388 dbi_result result = dbi_conn_query(writehandle, sql);
394 const char* columnName;
396 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
398 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
400 /* fetch the fieldmapper index */
401 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
403 osrfLogDebug(OSRF_LOG_MARK, "Found [%s] in IDL hash...", (char*)columnName);
405 /* determine the field type and storage attributes */
406 type = dbi_result_get_field_type(result, columnName);
407 attr = dbi_result_get_field_attribs(result, columnName);
411 case DBI_TYPE_INTEGER :
413 if ( !osrfHashGet(_f, "primitive") )
414 osrfHashSet(_f,"number", "primitive");
416 if( attr & DBI_INTEGER_SIZE8 )
417 osrfHashSet(_f,"INT8", "datatype");
419 osrfHashSet(_f,"INT", "datatype");
422 case DBI_TYPE_DECIMAL :
423 if ( !osrfHashGet(_f, "primitive") )
424 osrfHashSet(_f,"number", "primitive");
426 osrfHashSet(_f,"NUMERIC", "datatype");
429 case DBI_TYPE_STRING :
430 if ( !osrfHashGet(_f, "primitive") )
431 osrfHashSet(_f,"string", "primitive");
432 osrfHashSet(_f,"TEXT", "datatype");
435 case DBI_TYPE_DATETIME :
436 if ( !osrfHashGet(_f, "primitive") )
437 osrfHashSet(_f,"string", "primitive");
439 osrfHashSet(_f,"TIMESTAMP", "datatype");
442 case DBI_TYPE_BINARY :
443 if ( !osrfHashGet(_f, "primitive") )
444 osrfHashSet(_f,"string", "primitive");
446 osrfHashSet(_f,"BYTEA", "datatype");
451 "Setting [%s] to primitive [%s] and datatype [%s]...",
453 osrfHashGet(_f, "primitive"),
454 osrfHashGet(_f, "datatype")
458 dbi_result_free(result);
460 osrfLogDebug(OSRF_LOG_MARK, "No data found for class [%s]...", (char*)classname);
464 osrfStringArrayFree(classes);
469 void userDataFree( void* blob ) {
470 osrfHashFree( (osrfHash*)blob );
474 static void sessionDataFree( char* key, void* item ) {
475 if (!(strcmp(key,"xact_id"))) {
477 dbi_conn_query(writehandle, "ROLLBACK;");
484 int beginTransaction ( osrfMethodContext* ctx ) {
485 if(osrfMethodVerifyContext( ctx )) {
486 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
491 jsonObject* user = verifyUserPCRUD( ctx );
492 if (!user) return -1;
493 jsonObjectFree(user);
496 dbi_result result = dbi_conn_query(writehandle, "START TRANSACTION;");
498 osrfLogError(OSRF_LOG_MARK, "%s: Error starting transaction", MODULENAME );
499 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error starting transaction" );
502 jsonObject* ret = jsonNewObject(ctx->session->session_id);
503 osrfAppRespondComplete( ctx, ret );
506 if (!ctx->session->userData) {
507 ctx->session->userData = osrfNewHash();
508 osrfHashSetCallback((osrfHash*)ctx->session->userData, &sessionDataFree);
511 osrfHashSet( (osrfHash*)ctx->session->userData, strdup( ctx->session->session_id ), "xact_id" );
512 ctx->session->userDataFree = &userDataFree;
518 int setSavepoint ( osrfMethodContext* ctx ) {
519 if(osrfMethodVerifyContext( ctx )) {
520 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
527 jsonObject* user = verifyUserPCRUD( ctx );
528 if (!user) return -1;
529 jsonObjectFree(user);
532 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
533 osrfAppSessionStatus(
535 OSRF_STATUS_INTERNALSERVERERROR,
536 "osrfMethodException",
538 "No active transaction -- required for savepoints"
543 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
545 dbi_result result = dbi_conn_queryf(writehandle, "SAVEPOINT \"%s\";", spName);
549 "%s: Error creating savepoint %s in transaction %s",
552 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
554 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error creating savepoint" );
558 jsonObject* ret = jsonNewObject(spName);
559 osrfAppRespondComplete( ctx, ret );
566 int releaseSavepoint ( osrfMethodContext* ctx ) {
567 if(osrfMethodVerifyContext( ctx )) {
568 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
575 jsonObject* user = verifyUserPCRUD( ctx );
576 if (!user) return -1;
577 jsonObjectFree(user);
580 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
581 osrfAppSessionStatus(
583 OSRF_STATUS_INTERNALSERVERERROR,
584 "osrfMethodException",
586 "No active transaction -- required for savepoints"
591 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
593 dbi_result result = dbi_conn_queryf(writehandle, "RELEASE SAVEPOINT \"%s\";", spName);
597 "%s: Error releasing savepoint %s in transaction %s",
600 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
602 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error releasing savepoint" );
606 jsonObject* ret = jsonNewObject(spName);
607 osrfAppRespondComplete( ctx, ret );
614 int rollbackSavepoint ( osrfMethodContext* ctx ) {
615 if(osrfMethodVerifyContext( ctx )) {
616 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
623 jsonObject* user = verifyUserPCRUD( ctx );
624 if (!user) return -1;
625 jsonObjectFree(user);
628 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
629 osrfAppSessionStatus(
631 OSRF_STATUS_INTERNALSERVERERROR,
632 "osrfMethodException",
634 "No active transaction -- required for savepoints"
639 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
641 dbi_result result = dbi_conn_queryf(writehandle, "ROLLBACK TO SAVEPOINT \"%s\";", spName);
645 "%s: Error rolling back savepoint %s in transaction %s",
648 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
650 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back savepoint" );
654 jsonObject* ret = jsonNewObject(spName);
655 osrfAppRespondComplete( ctx, ret );
662 int commitTransaction ( osrfMethodContext* ctx ) {
663 if(osrfMethodVerifyContext( ctx )) {
664 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
669 jsonObject* user = verifyUserPCRUD( ctx );
670 if (!user) return -1;
671 jsonObjectFree(user);
674 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
675 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to commit" );
679 dbi_result result = dbi_conn_query(writehandle, "COMMIT;");
681 osrfLogError(OSRF_LOG_MARK, "%s: Error committing transaction", MODULENAME );
682 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error committing transaction" );
685 osrfHashRemove(ctx->session->userData, "xact_id");
686 jsonObject* ret = jsonNewObject(ctx->session->session_id);
687 osrfAppRespondComplete( ctx, ret );
693 int rollbackTransaction ( osrfMethodContext* ctx ) {
694 if(osrfMethodVerifyContext( ctx )) {
695 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
700 jsonObject* user = verifyUserPCRUD( ctx );
701 if (!user) return -1;
702 jsonObjectFree(user);
705 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
706 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to roll back" );
710 dbi_result result = dbi_conn_query(writehandle, "ROLLBACK;");
712 osrfLogError(OSRF_LOG_MARK, "%s: Error rolling back transaction", MODULENAME );
713 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back transaction" );
716 osrfHashRemove(ctx->session->userData, "xact_id");
717 jsonObject* ret = jsonNewObject(ctx->session->session_id);
718 osrfAppRespondComplete( ctx, ret );
724 int dispatchCRUDMethod ( osrfMethodContext* ctx ) {
725 if(osrfMethodVerifyContext( ctx )) {
726 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
730 osrfHash* meta = (osrfHash*) ctx->method->userData;
731 osrfHash* class_obj = osrfHashGet( meta, "class" );
735 const char* methodtype = osrfHashGet(meta, "methodtype");
736 jsonObject * obj = NULL;
738 if (!strcmp(methodtype, "create")) {
739 obj = doCreate(ctx, &err);
740 osrfAppRespondComplete( ctx, obj );
742 else if (!strcmp(methodtype, "retrieve")) {
743 obj = doRetrieve(ctx, &err);
744 osrfAppRespondComplete( ctx, obj );
746 else if (!strcmp(methodtype, "update")) {
747 obj = doUpdate(ctx, &err);
748 osrfAppRespondComplete( ctx, obj );
750 else if (!strcmp(methodtype, "delete")) {
751 obj = doDelete(ctx, &err);
752 osrfAppRespondComplete( ctx, obj );
754 else if (!strcmp(methodtype, "search")) {
756 jsonObject* _p = jsonObjectClone( ctx->params );
759 _p = jsonParseString("[]");
760 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 1)));
761 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 2)));
764 obj = doFieldmapperSearch(ctx, class_obj, _p, &err);
770 jsonIterator* itr = jsonNewIterator( obj );
771 while ((cur = jsonIteratorNext( itr ))) {
773 if(!verifyObjectPCRUD(ctx, cur)) continue;
775 osrfAppRespond( ctx, cur );
777 jsonIteratorFree(itr);
778 osrfAppRespondComplete( ctx, NULL );
780 } else if (!strcmp(methodtype, "id_list")) {
782 jsonObject* _p = jsonObjectClone( ctx->params );
785 _p = jsonParseString("[]");
786 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 1)));
787 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 2)));
790 if (jsonObjectGetIndex( _p, 1 )) {
791 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "select" );
792 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "no_i18n" );
793 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh" );
794 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh_columns" );
796 jsonObjectSetIndex( _p, 1, jsonNewObjectType(JSON_HASH) );
799 jsonObjectSetKey( jsonObjectGetIndex( _p, 1 ), "no_i18n", jsonNewBoolObject( 1 ) );
802 jsonObjectGetIndex( _p, 1 ),
805 "{ \"%s\":[\"%s\"] }",
806 osrfHashGet( class_obj, "classname" ),
807 osrfHashGet( class_obj, "primarykey" )
811 obj = doFieldmapperSearch(ctx, class_obj, _p, &err);
817 jsonIterator* itr = jsonNewIterator( obj );
818 while ((cur = jsonIteratorNext( itr ))) {
820 if(!verifyObjectPCRUD(ctx, cur)) continue;
824 oilsFMGetObject( cur, osrfHashGet( class_obj, "primarykey" ) )
827 jsonIteratorFree(itr);
828 osrfAppRespondComplete( ctx, NULL );
831 osrfAppRespondComplete( ctx, obj );
839 static int verifyObjectClass ( osrfMethodContext* ctx, const jsonObject* param ) {
842 osrfHash* meta = (osrfHash*) ctx->method->userData;
843 osrfHash* class = osrfHashGet( meta, "class" );
845 if (!param->classname || (strcmp( osrfHashGet(class, "classname"), param->classname ))) {
847 growing_buffer* msg = buffer_init(128);
850 "%s: %s method for type %s was passed a %s",
852 osrfHashGet(meta, "methodtype"),
853 osrfHashGet(class, "classname"),
857 char* m = buffer_release(msg);
858 osrfAppSessionStatus( ctx->session, OSRF_STATUS_BADREQUEST, "osrfMethodException", ctx->request, m );
866 ret = verifyObjectPCRUD( ctx, param );
874 static jsonObject* verifyUserPCRUD( osrfMethodContext* ctx ) {
875 char* auth = jsonObjectToSimpleString( jsonObjectGetIndex( ctx->params, 0 ) );
876 jsonObject* auth_object = jsonNewObject(auth);
877 jsonObject* user = oilsUtilsQuickReq("open-ils.auth","open-ils.auth.session.retrieve", auth_object);
878 jsonObjectFree(auth_object);
880 if (!user->classname || strcmp(user->classname, "au")) {
882 growing_buffer* msg = buffer_init(128);
885 "%s: permacrud received a bad auth token: %s",
890 char* m = buffer_release(msg);
891 osrfAppSessionStatus( ctx->session, OSRF_STATUS_UNAUTHORIZED, "osrfMethodException", ctx->request, m );
894 jsonObjectFree(user);
903 static int verifyObjectPCRUD ( osrfMethodContext* ctx, const jsonObject* obj ) {
905 dbhandle = writehandle;
907 osrfHash* meta = (osrfHash*) ctx->method->userData;
908 osrfHash* class = osrfHashGet( meta, "class" );
909 char* method_type = strdup( osrfHashGet(meta, "methodtype") );
912 if ( ( *method_type == 's' || *method_type == 'i' ) ) {
914 method_type = strdup("retrieve"); // search and id_list are equivelant to retrieve for this
915 } else if ( *method_type == 'u' || *method_type == 'd' ) {
916 fetch = 1; // MUST go to the db for the object for update and delete
919 osrfHash* pcrud = osrfHashGet( osrfHashGet(class, "permacrud"), method_type );
923 // No permacrud for this method type on this class
925 growing_buffer* msg = buffer_init(128);
928 "%s: %s on class %s has no permacrud IDL entry",
930 osrfHashGet(meta, "methodtype"),
931 osrfHashGet(class, "classname")
934 char* m = buffer_release(msg);
935 osrfAppSessionStatus( ctx->session, OSRF_STATUS_FORBIDDEN, "osrfMethodException", ctx->request, m );
942 jsonObject* user = verifyUserPCRUD( ctx );
945 int userid = atoi( oilsFMGetString( user, "id" ) );
946 jsonObjectFree(user);
948 osrfStringArray* permission = osrfHashGet(pcrud, "permission");
949 osrfStringArray* local_context = osrfHashGet(pcrud, "local_context");
950 osrfHash* foreign_context = osrfHashGet(pcrud, "foreign_context");
952 osrfStringArray* context_org_array = osrfNewStringArray(1);
955 char* pkey_value = NULL;
956 if ( str_is_true( osrfHashGet(pcrud, "global_required") ) ) {
957 osrfLogDebug( OSRF_LOG_MARK, "global-level permissions required, fetching top of the org tree" );
959 // check for perm at top of org tree
960 jsonObject* _tmp_params = jsonParseString("[{\"parent_ou\":null}]");
961 jsonObject* _list = doFieldmapperSearch(ctx, osrfHashGet( oilsIDL(), "aou" ), _tmp_params, &err);
963 jsonObject* _tree_top = jsonObjectGetIndex(_list, 0);
966 jsonObjectFree(_tmp_params);
967 jsonObjectFree(_list);
969 growing_buffer* msg = buffer_init(128);
970 OSRF_BUFFER_ADD( msg, MODULENAME );
971 OSRF_BUFFER_ADD( msg,
972 ": Internal error, could not find the top of the org tree (parent_ou = NULL)" );
974 char* m = buffer_release(msg);
975 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, m );
981 osrfStringArrayAdd( context_org_array, oilsFMGetString( _tree_top, "id" ) );
982 osrfLogDebug( OSRF_LOG_MARK, "top of the org tree is %s", osrfStringArrayGetString(context_org_array, 0) );
984 jsonObjectFree(_tmp_params);
985 jsonObjectFree(_list);
988 osrfLogDebug( OSRF_LOG_MARK, "global-level permissions not required, fetching context org ids" );
989 char* pkey = osrfHashGet(class, "primarykey");
990 jsonObject *param = NULL;
992 if (obj->classname) {
993 pkey_value = oilsFMGetString( obj, pkey );
994 if (!fetch) param = jsonObjectClone(obj);
995 osrfLogDebug( OSRF_LOG_MARK, "Object supplied, using primary key value of %s", pkey_value );
997 pkey_value = jsonObjectToSimpleString( obj );
999 osrfLogDebug( OSRF_LOG_MARK, "Object not supplied, using primary key value of %s and retrieving from the database", pkey_value );
1003 jsonObject* _tmp_params = jsonParseStringFmt("[{\"%s\":\"%s\"}]", pkey, pkey_value);
1004 jsonObject* _list = doFieldmapperSearch(
1011 param = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1013 jsonObjectFree(_tmp_params);
1014 jsonObjectFree(_list);
1018 osrfLogDebug( OSRF_LOG_MARK, "Object not found in the database with primary key %s of %s", pkey, pkey_value );
1020 growing_buffer* msg = buffer_init(128);
1023 "%s: no object found with primary key %s of %s",
1029 char* m = buffer_release(msg);
1030 osrfAppSessionStatus(
1032 OSRF_STATUS_INTERNALSERVERERROR,
1033 "osrfMethodException",
1039 if (pkey_value) free(pkey_value);
1044 if (local_context->size > 0) {
1045 osrfLogDebug( OSRF_LOG_MARK, "%d class-local context field(s) specified", local_context->size);
1047 char* lcontext = NULL;
1048 while ( (lcontext = osrfStringArrayGetString(local_context, i++)) ) {
1049 osrfStringArrayAdd( context_org_array, oilsFMGetString( param, lcontext ) );
1052 "adding class-local field %s (value: %s) to the context org list",
1054 osrfStringArrayGetString(context_org_array, context_org_array->size - 1)
1059 osrfStringArray* class_list;
1061 if (foreign_context) {
1062 class_list = osrfHashKeys( foreign_context );
1063 osrfLogDebug( OSRF_LOG_MARK, "%d foreign context classes(s) specified", class_list->size);
1065 if (class_list->size > 0) {
1068 char* class_name = NULL;
1069 while ( (class_name = osrfStringArrayGetString(class_list, i++)) ) {
1070 osrfHash* fcontext = osrfHashGet(foreign_context, class_name);
1074 "%d foreign context fields(s) specified for class %s",
1075 ((osrfStringArray*)osrfHashGet(fcontext,"context"))->size,
1079 char* foreign_pkey = osrfHashGet(fcontext, "field");
1080 char* foreign_pkey_value = oilsFMGetString(param, osrfHashGet(fcontext, "fkey"));
1082 jsonObject* _tmp_params = jsonParseStringFmt(
1083 "[{\"%s\":\"%s\"}]",
1088 jsonObject* _list = doFieldmapperSearch(
1090 osrfHashGet( oilsIDL(), class_name ),
1095 jsonObject* _fparam = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1096 jsonObjectFree(_tmp_params);
1097 jsonObjectFree(_list);
1099 osrfStringArray* jump_list = osrfHashGet(fcontext, "jump");
1101 if (_fparam && jump_list) {
1104 while ( (flink = osrfStringArrayGetString(jump_list, k++)) && _fparam ) {
1105 free(foreign_pkey_value);
1107 osrfHash* foreign_link_hash = oilsIDLFindPath( "/%s/links/%s", _fparam->classname, flink );
1109 foreign_pkey_value = oilsFMGetString(_fparam, flink);
1110 foreign_pkey = osrfHashGet( foreign_link_hash, "key" );
1112 _tmp_params = jsonParseStringFmt(
1113 "[{\"%s\":\"%s\"}]",
1118 _list = doFieldmapperSearch(
1120 osrfHashGet( oilsIDL(), osrfHashGet( foreign_link_hash, "class" ) ),
1125 _fparam = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1126 jsonObjectFree(_tmp_params);
1127 jsonObjectFree(_list);
1134 growing_buffer* msg = buffer_init(128);
1137 "%s: no object found with primary key %s of %s",
1143 char* m = buffer_release(msg);
1144 osrfAppSessionStatus(
1146 OSRF_STATUS_INTERNALSERVERERROR,
1147 "osrfMethodException",
1153 osrfStringArrayFree(class_list);
1154 free(foreign_pkey_value);
1155 jsonObjectFree(param);
1160 free(foreign_pkey_value);
1163 char* foreign_field = NULL;
1164 while ( (foreign_field = osrfStringArrayGetString(osrfHashGet(fcontext,"context"), j++)) ) {
1165 osrfStringArrayAdd( context_org_array, oilsFMGetString( _fparam, foreign_field ) );
1168 "adding foreign class %s field %s (value: %s) to the context org list",
1171 osrfStringArrayGetString(context_org_array, context_org_array->size - 1)
1175 jsonObjectFree(_fparam);
1178 osrfStringArrayFree(class_list);
1182 jsonObjectFree(param);
1185 char* context_org = NULL;
1189 if (permission->size == 0) {
1190 osrfLogDebug( OSRF_LOG_MARK, "No permission specified for this action, passing through" );
1195 while ( (perm = osrfStringArrayGetString(permission, i++)) ) {
1197 while ( (context_org = osrfStringArrayGetString(context_org_array, j++)) ) {
1203 "Checking object permission [%s] for user %d on object %s (class %s) at org %d",
1207 osrfHashGet(class, "classname"),
1211 result = dbi_conn_queryf(
1213 "SELECT permission.usr_has_object_perm(%d, '%s', '%s', '%s', %d) AS has_perm;",
1216 osrfHashGet(class, "classname"),
1224 "Recieved a result for object permission [%s] for user %d on object %s (class %s) at org %d",
1228 osrfHashGet(class, "classname"),
1232 if (dbi_result_first_row(result)) {
1233 jsonObject* return_val = oilsMakeJSONFromResult( result );
1234 char* has_perm = jsonObjectToSimpleString( jsonObjectGetKeyConst(return_val, "has_perm") );
1238 "Status of object permission [%s] for user %d on object %s (class %s) at org %d is %s",
1242 osrfHashGet(class, "classname"),
1247 if ( *has_perm == 't' ) OK = 1;
1249 jsonObjectFree(return_val);
1252 dbi_result_free(result);
1257 osrfLogDebug( OSRF_LOG_MARK, "Checking non-object permission [%s] for user %d at org %d", perm, userid, atoi(context_org) );
1258 result = dbi_conn_queryf(
1260 "SELECT permission.usr_has_perm(%d, '%s', %d) AS has_perm;",
1267 osrfLogDebug( OSRF_LOG_MARK, "Received a result for permission [%s] for user %d at org %d", perm, userid, atoi(context_org) );
1268 if (dbi_result_first_row(result)) {
1269 jsonObject* return_val = oilsMakeJSONFromResult( result );
1270 char* has_perm = jsonObjectToSimpleString( jsonObjectGetKeyConst(return_val, "has_perm") );
1271 osrfLogDebug( OSRF_LOG_MARK, "Status of permission [%s] for user %d at org %d is [%s]", perm, userid, atoi(context_org), has_perm );
1272 if ( *has_perm == 't' ) OK = 1;
1274 jsonObjectFree(return_val);
1277 dbi_result_free(result);
1285 if (pkey_value) free(pkey_value);
1286 osrfStringArrayFree(context_org_array);
1293 static jsonObject* doCreate(osrfMethodContext* ctx, int* err ) {
1295 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1297 jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
1298 jsonObject* options = jsonObjectGetIndex( ctx->params, 2 );
1300 jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
1301 jsonObject* options = jsonObjectGetIndex( ctx->params, 1 );
1304 if (!verifyObjectClass(ctx, target)) {
1309 osrfLogDebug( OSRF_LOG_MARK, "Object seems to be of the correct type" );
1311 if (!ctx->session || !ctx->session->userData || !osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
1312 osrfLogError( OSRF_LOG_MARK, "No active transaction -- required for CREATE" );
1314 osrfAppSessionStatus(
1316 OSRF_STATUS_BADREQUEST,
1317 "osrfMethodException",
1319 "No active transaction -- required for CREATE"
1325 // The following test is harmless but redundant. If a class is
1326 // readonly, we don't register a create method for it.
1327 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
1328 osrfAppSessionStatus(
1330 OSRF_STATUS_BADREQUEST,
1331 "osrfMethodException",
1333 "Cannot INSERT readonly class"
1340 char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
1342 // Set the last_xact_id
1343 int index = oilsIDL_ntop( target->classname, "last_xact_id" );
1345 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
1346 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
1349 osrfLogDebug( OSRF_LOG_MARK, "There is a transaction running..." );
1351 dbhandle = writehandle;
1353 osrfHash* fields = osrfHashGet(meta, "fields");
1354 char* pkey = osrfHashGet(meta, "primarykey");
1355 char* seq = osrfHashGet(meta, "sequence");
1357 growing_buffer* table_buf = buffer_init(128);
1358 growing_buffer* col_buf = buffer_init(128);
1359 growing_buffer* val_buf = buffer_init(128);
1361 OSRF_BUFFER_ADD(table_buf, "INSERT INTO ");
1362 OSRF_BUFFER_ADD(table_buf, osrfHashGet(meta, "tablename"));
1363 OSRF_BUFFER_ADD_CHAR( col_buf, '(' );
1364 buffer_add(val_buf,"VALUES (");
1370 osrfStringArray* field_list = osrfHashKeys( fields );
1371 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
1373 osrfHash* field = osrfHashGet( fields, field_name );
1375 if( str_is_true( osrfHashGet( field, "virtual" ) ) )
1378 const jsonObject* field_object = oilsFMGetObject( target, field_name );
1381 if (field_object && field_object->classname) {
1382 value = oilsFMGetString(
1384 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
1387 value = jsonObjectToSimpleString( field_object );
1394 OSRF_BUFFER_ADD_CHAR( col_buf, ',' );
1395 OSRF_BUFFER_ADD_CHAR( val_buf, ',' );
1398 buffer_add(col_buf, field_name);
1400 if (!field_object || field_object->type == JSON_NULL) {
1401 buffer_add( val_buf, "DEFAULT" );
1403 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1404 if ( !strcmp(osrfHashGet(field, "datatype"), "INT8") ) {
1405 buffer_fadd( val_buf, "%lld", atoll(value) );
1407 } else if ( !strcmp(osrfHashGet(field, "datatype"), "INT") ) {
1408 buffer_fadd( val_buf, "%d", atoi(value) );
1410 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
1411 buffer_fadd( val_buf, "%f", atof(value) );
1414 if ( dbi_conn_quote_string(writehandle, &value) ) {
1415 OSRF_BUFFER_ADD( val_buf, value );
1418 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
1419 osrfAppSessionStatus(
1421 OSRF_STATUS_INTERNALSERVERERROR,
1422 "osrfMethodException",
1424 "Error quoting string -- please see the error log for more details"
1427 buffer_free(table_buf);
1428 buffer_free(col_buf);
1429 buffer_free(val_buf);
1440 OSRF_BUFFER_ADD_CHAR( col_buf, ')' );
1441 OSRF_BUFFER_ADD_CHAR( val_buf, ')' );
1443 char* table_str = buffer_release(table_buf);
1444 char* col_str = buffer_release(col_buf);
1445 char* val_str = buffer_release(val_buf);
1446 growing_buffer* sql = buffer_init(128);
1447 buffer_fadd( sql, "%s %s %s;", table_str, col_str, val_str );
1452 char* query = buffer_release(sql);
1454 osrfLogDebug(OSRF_LOG_MARK, "%s: Insert SQL [%s]", MODULENAME, query);
1457 dbi_result result = dbi_conn_query(writehandle, query);
1459 jsonObject* obj = NULL;
1462 obj = jsonNewObject(NULL);
1465 "%s ERROR inserting %s object using query [%s]",
1467 osrfHashGet(meta, "fieldmapper"),
1470 osrfAppSessionStatus(
1472 OSRF_STATUS_INTERNALSERVERERROR,
1473 "osrfMethodException",
1475 "INSERT error -- please see the error log for more details"
1480 char* id = oilsFMGetString(target, pkey);
1482 unsigned long long new_id = dbi_conn_sequence_last(writehandle, seq);
1483 growing_buffer* _id = buffer_init(10);
1484 buffer_fadd(_id, "%lld", new_id);
1485 id = buffer_release(_id);
1488 // Find quietness specification, if present
1489 char* quiet_str = NULL;
1491 const jsonObject* quiet_obj = jsonObjectGetKeyConst( options, "quiet" );
1493 quiet_str = jsonObjectToSimpleString( quiet_obj );
1496 if( str_is_true( quiet_str ) ) { // if quietness is specified
1497 obj = jsonNewObject(id);
1501 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
1502 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH));
1505 jsonObjectGetIndex(fake_params, 0),
1510 jsonObject* list = doFieldmapperSearch( ctx,meta, fake_params, err);
1513 jsonObjectFree( fake_params );
1516 obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
1519 jsonObjectFree( list );
1520 jsonObjectFree( fake_params );
1523 if(quiet_str) free(quiet_str);
1534 static jsonObject* doRetrieve(osrfMethodContext* ctx, int* err ) {
1544 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1546 char* id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, id_pos));
1547 jsonObject* order_hash = jsonObjectGetIndex(ctx->params, order_pos);
1551 "%s retrieving %s object with primary key value of %s",
1553 osrfHashGet(meta, "fieldmapper"),
1558 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
1559 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH));
1562 jsonObjectGetIndex(fake_params, 0),
1563 osrfHashGet(meta, "primarykey"),
1564 jsonObjectClone(jsonObjectGetIndex(ctx->params, id_pos))
1568 if (order_hash) jsonObjectPush(fake_params, jsonObjectClone(order_hash) );
1570 jsonObject* list = doFieldmapperSearch( ctx,meta, fake_params, err);
1573 jsonObjectFree( fake_params );
1577 jsonObject* obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
1579 jsonObjectFree( list );
1580 jsonObjectFree( fake_params );
1583 if(!verifyObjectPCRUD(ctx, obj)) {
1584 jsonObjectFree(obj);
1587 growing_buffer* msg = buffer_init(128);
1588 OSRF_BUFFER_ADD( msg, MODULENAME );
1589 OSRF_BUFFER_ADD( msg, ": Insufficient permissions to retrieve object" );
1591 char* m = buffer_release(msg);
1592 osrfAppSessionStatus( ctx->session, OSRF_STATUS_NOTALLOWED, "osrfMethodException", ctx->request, m );
1603 static char* jsonNumberToDBString ( osrfHash* field, const jsonObject* value ) {
1604 growing_buffer* val_buf = buffer_init(32);
1606 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
1607 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%ld", (long)jsonObjectGetNumber(value) );
1609 char* val_str = jsonObjectToSimpleString(value);
1610 buffer_fadd( val_buf, "%ld", atol(val_str) );
1614 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
1615 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%f", jsonObjectGetNumber(value) );
1617 char* val_str = jsonObjectToSimpleString(value);
1618 buffer_fadd( val_buf, "%f", atof(val_str) );
1623 return buffer_release(val_buf);
1626 static char* searchINPredicate (const char* class, osrfHash* field,
1627 jsonObject* node, const char* op, osrfMethodContext* ctx ) {
1628 growing_buffer* sql_buf = buffer_init(32);
1634 osrfHashGet(field, "name")
1638 buffer_add(sql_buf, "IN (");
1639 } else if (!(strcasecmp(op,"not in"))) {
1640 buffer_add(sql_buf, "NOT IN (");
1642 buffer_add(sql_buf, "IN (");
1645 if (node->type == JSON_HASH) {
1646 // subquery predicate
1647 char* subpred = SELECT(
1649 jsonObjectGetKey( node, "select" ),
1650 jsonObjectGetKey( node, "from" ),
1651 jsonObjectGetKey( node, "where" ),
1652 jsonObjectGetKey( node, "having" ),
1653 jsonObjectGetKey( node, "order_by" ),
1654 jsonObjectGetKey( node, "limit" ),
1655 jsonObjectGetKey( node, "offset" ),
1659 buffer_add(sql_buf, subpred);
1662 } else if (node->type == JSON_ARRAY) {
1663 // litteral value list
1664 int in_item_index = 0;
1665 int in_item_first = 1;
1666 jsonObject* in_item;
1667 while ( (in_item = jsonObjectGetIndex(node, in_item_index++)) ) {
1672 buffer_add(sql_buf, ", ");
1674 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1675 char* val = jsonNumberToDBString( field, in_item );
1676 OSRF_BUFFER_ADD( sql_buf, val );
1680 char* key_string = jsonObjectToSimpleString(in_item);
1681 if ( dbi_conn_quote_string(dbhandle, &key_string) ) {
1682 OSRF_BUFFER_ADD( sql_buf, key_string );
1685 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, key_string);
1687 buffer_free(sql_buf);
1694 OSRF_BUFFER_ADD_CHAR( sql_buf, ')' );
1696 return buffer_release(sql_buf);
1699 // Receive a JSON_ARRAY representing a function call. The first
1700 // entry in the array is the function name. The rest are parameters.
1701 static char* searchValueTransform( const jsonObject* array ) {
1702 growing_buffer* sql_buf = buffer_init(32);
1705 jsonObject* func_item;
1707 // Get the function name
1708 if( array->size > 0 ) {
1709 func_item = jsonObjectGetIndex( array, 0 );
1710 val = jsonObjectToSimpleString( func_item );
1711 OSRF_BUFFER_ADD( sql_buf, val );
1712 OSRF_BUFFER_ADD( sql_buf, "( " );
1716 // Get the parameters
1717 int func_item_index = 1; // We already grabbed the zeroth entry
1718 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1720 // Add a separator comma, if we need one
1721 if( func_item_index > 2 )
1722 buffer_add( sql_buf, ", " );
1724 // Add the current parameter
1725 if (func_item->type == JSON_NULL) {
1726 buffer_add( sql_buf, "NULL" );
1728 val = jsonObjectToSimpleString(func_item);
1729 if ( dbi_conn_quote_string(dbhandle, &val) ) {
1730 OSRF_BUFFER_ADD( sql_buf, val );
1733 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1734 buffer_free(sql_buf);
1741 buffer_add( sql_buf, " )" );
1743 return buffer_release(sql_buf);
1746 static char* searchFunctionPredicate (const char* class, osrfHash* field,
1747 const jsonObject* node, const char* node_key) {
1748 growing_buffer* sql_buf = buffer_init(32);
1750 char* val = searchValueTransform(node);
1756 osrfHashGet(field, "name"),
1763 return buffer_release(sql_buf);
1766 // class is a class name
1767 // field is a field definition as stored in the IDL
1768 // node comes from the method parameter, and represents an entry in the SELECT list
1769 static char* searchFieldTransform (const char* class, osrfHash* field, const jsonObject* node) {
1770 growing_buffer* sql_buf = buffer_init(32);
1772 char* field_transform = jsonObjectToSimpleString( jsonObjectGetKeyConst( node, "transform" ) );
1773 char* transform_subcolumn = jsonObjectToSimpleString( jsonObjectGetKeyConst( node, "result_field" ) );
1775 if(transform_subcolumn)
1776 OSRF_BUFFER_ADD_CHAR( sql_buf, '(' ); // enclose transform in parentheses
1778 if (field_transform) {
1779 buffer_fadd( sql_buf, "%s(\"%s\".%s", field_transform, class, osrfHashGet(field, "name"));
1780 const jsonObject* array = jsonObjectGetKeyConst( node, "params" );
1783 int func_item_index = 0;
1784 jsonObject* func_item;
1785 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1787 char* val = jsonObjectToSimpleString(func_item);
1790 buffer_add( sql_buf, ",NULL" );
1791 } else if ( dbi_conn_quote_string(dbhandle, &val) ) {
1792 OSRF_BUFFER_ADD_CHAR( sql_buf, ',' );
1793 OSRF_BUFFER_ADD( sql_buf, val );
1795 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1796 free(transform_subcolumn);
1797 free(field_transform);
1799 buffer_free(sql_buf);
1806 buffer_add( sql_buf, " )" );
1809 buffer_fadd( sql_buf, "\"%s\".%s", class, osrfHashGet(field, "name"));
1812 if (transform_subcolumn)
1813 buffer_fadd( sql_buf, ").\"%s\"", transform_subcolumn );
1815 if (field_transform) free(field_transform);
1816 if (transform_subcolumn) free(transform_subcolumn);
1818 return buffer_release(sql_buf);
1821 static char* searchFieldTransformPredicate (const char* class, osrfHash* field, jsonObject* node, const char* node_key) {
1822 char* field_transform = searchFieldTransform( class, field, node );
1825 if (!jsonObjectGetKeyConst( node, "value" )) {
1826 value = searchWHERE( node, osrfHashGet( oilsIDL(), class ), AND_OP_JOIN, NULL );
1827 } else if (jsonObjectGetKeyConst( node, "value" )->type == JSON_ARRAY) {
1828 value = searchValueTransform(jsonObjectGetKeyConst( node, "value" ));
1829 } else if (jsonObjectGetKeyConst( node, "value" )->type == JSON_HASH) {
1830 value = searchWHERE( jsonObjectGetKeyConst( node, "value" ), osrfHashGet( oilsIDL(), class ), AND_OP_JOIN, NULL );
1831 } else if (jsonObjectGetKeyConst( node, "value" )->type != JSON_NULL) {
1832 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1833 value = jsonNumberToDBString( field, jsonObjectGetKeyConst( node, "value" ) );
1835 value = jsonObjectToSimpleString(jsonObjectGetKeyConst( node, "value" ));
1836 if ( !dbi_conn_quote_string(dbhandle, &value) ) {
1837 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, value);
1839 free(field_transform);
1845 growing_buffer* sql_buf = buffer_init(32);
1856 free(field_transform);
1858 return buffer_release(sql_buf);
1861 static char* searchSimplePredicate (const char* orig_op, const char* class,
1862 osrfHash* field, const jsonObject* node) {
1866 if (node->type != JSON_NULL) {
1867 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1868 val = jsonNumberToDBString( field, node );
1870 val = jsonObjectToSimpleString(node);
1874 char* pred = searchWriteSimplePredicate( class, field, osrfHashGet(field, "name"), orig_op, val );
1881 static char* searchWriteSimplePredicate ( const char* class, osrfHash* field,
1882 const char* left, const char* orig_op, const char* right ) {
1886 if (right == NULL) {
1887 val = strdup("NULL");
1889 if (strcmp( orig_op, "=" ))
1890 op = strdup("IS NOT");
1894 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1895 val = strdup(right);
1896 op = strdup(orig_op);
1899 val = strdup(right);
1900 if ( !dbi_conn_quote_string(dbhandle, &val) ) {
1901 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1905 op = strdup(orig_op);
1908 growing_buffer* sql_buf = buffer_init(16);
1909 buffer_fadd( sql_buf, "\"%s\".%s %s %s", class, left, op, val );
1913 return buffer_release(sql_buf);
1916 static char* searchBETWEENPredicate (const char* class, osrfHash* field, jsonObject* node) {
1921 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1922 x_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,0));
1923 y_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,1));
1926 x_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,0));
1927 y_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,1));
1928 if ( !(dbi_conn_quote_string(dbhandle, &x_string) && dbi_conn_quote_string(dbhandle, &y_string)) ) {
1929 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key strings [%s] and [%s]", MODULENAME, x_string, y_string);
1936 growing_buffer* sql_buf = buffer_init(32);
1937 buffer_fadd( sql_buf, "%s BETWEEN %s AND %s", osrfHashGet(field, "name"), x_string, y_string );
1941 return buffer_release(sql_buf);
1944 static char* searchPredicate ( const char* class, osrfHash* field,
1945 jsonObject* node, osrfMethodContext* ctx ) {
1948 if (node->type == JSON_ARRAY) { // equality IN search
1949 pred = searchINPredicate( class, field, node, NULL, ctx );
1950 } else if (node->type == JSON_HASH) { // non-equality search
1951 jsonObject* pred_node;
1952 jsonIterator* pred_itr = jsonNewIterator( node );
1953 while ( (pred_node = jsonIteratorNext( pred_itr )) ) {
1954 if ( !(strcasecmp( pred_itr->key,"between" )) )
1955 pred = searchBETWEENPredicate( class, field, pred_node );
1956 else if ( !(strcasecmp( pred_itr->key,"in" )) || !(strcasecmp( pred_itr->key,"not in" )) )
1957 pred = searchINPredicate( class, field, pred_node, pred_itr->key, ctx );
1958 else if ( pred_node->type == JSON_ARRAY )
1959 pred = searchFunctionPredicate( class, field, pred_node, pred_itr->key );
1960 else if ( pred_node->type == JSON_HASH )
1961 pred = searchFieldTransformPredicate( class, field, pred_node, pred_itr->key );
1963 pred = searchSimplePredicate( pred_itr->key, class, field, pred_node );
1967 jsonIteratorFree(pred_itr);
1968 } else if (node->type == JSON_NULL) { // IS NULL search
1969 growing_buffer* _p = buffer_init(64);
1972 "\"%s\".%s IS NULL",
1974 osrfHashGet(field, "name")
1976 pred = buffer_release(_p);
1977 } else { // equality search
1978 pred = searchSimplePredicate( "=", class, field, node );
1997 field : call_number,
2013 static char* searchJOIN ( const jsonObject* join_hash, osrfHash* leftmeta ) {
2015 const jsonObject* working_hash;
2016 jsonObject* freeable_hash = NULL;
2018 if (join_hash->type == JSON_STRING) {
2019 // create a wrapper around a copy of the original
2020 char* _tmp = jsonObjectToSimpleString( join_hash );
2021 freeable_hash = jsonNewObjectType(JSON_HASH);
2022 jsonObjectSetKey(freeable_hash, _tmp, NULL);
2024 working_hash = freeable_hash;
2027 if( join_hash->type != JSON_HASH ) {
2030 "%s: JOIN failed; expected JSON object type not found",
2035 working_hash = join_hash;
2038 growing_buffer* join_buf = buffer_init(128);
2039 const char* leftclass = osrfHashGet(leftmeta, "classname");
2041 jsonObject* snode = NULL;
2042 jsonIterator* search_itr = jsonNewIterator( working_hash );
2044 while ( (snode = jsonIteratorNext( search_itr )) ) {
2045 const char* class = search_itr->key;
2046 osrfHash* idlClass = osrfHashGet( oilsIDL(), class );
2050 "%s: JOIN failed. No class \"%s\" defined in IDL",
2054 jsonIteratorFree( search_itr );
2055 buffer_free( join_buf );
2057 jsonObjectFree( freeable_hash );
2061 char* fkey = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "fkey" ) );
2062 char* field = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "field" ) );
2064 if (field && !fkey) {
2065 fkey = (char*)oilsIDLFindPath("/%s/links/%s/key", class, field);
2069 "%s: JOIN failed. No link defined from %s.%s to %s",
2075 buffer_free(join_buf);
2077 jsonObjectFree(freeable_hash);
2079 jsonIteratorFree(search_itr);
2082 fkey = strdup( fkey );
2084 } else if (!field && fkey) {
2085 field = (char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, fkey );
2089 "%s: JOIN failed. No link defined from %s.%s to %s",
2095 buffer_free(join_buf);
2097 jsonObjectFree(freeable_hash);
2099 jsonIteratorFree(search_itr);
2102 field = strdup( field );
2104 } else if (!field && !fkey) {
2105 osrfHash* _links = oilsIDL_links( leftclass );
2107 // For each link defined for the left class:
2108 // see if the link references the joined class
2109 osrfHashIterator* itr = osrfNewHashIterator( _links );
2110 osrfHash* curr_link = NULL;
2111 while( (curr_link = osrfHashIteratorNext( itr ) ) ) {
2112 const char* other_class = osrfHashGet( curr_link, "class" );
2113 if( other_class && !strcmp( other_class, class ) ) {
2115 // Found a link between the classes
2116 fkey = strdup( osrfHashIteratorKey( itr ) );
2117 const char* other_key = osrfHashGet( curr_link, "key" );
2118 field = other_key ? strdup( other_key ) : NULL;
2122 osrfHashIteratorFree( itr );
2124 if (!field || !fkey) {
2125 // Do another such search, with the classes reversed
2126 _links = oilsIDL_links( class );
2128 // For each link defined for the joined class:
2129 // see if the link references the left class
2130 osrfHashIterator* itr = osrfNewHashIterator( _links );
2131 osrfHash* curr_link = NULL;
2132 while( (curr_link = osrfHashIteratorNext( itr ) ) ) {
2133 const char* other_class = osrfHashGet( curr_link, "class" );
2134 if( other_class && !strcmp( other_class, leftclass ) ) {
2136 // Found a link between the classes
2137 fkey = strdup( osrfHashIteratorKey( itr ) );
2138 const char* other_key = osrfHashGet( curr_link, "key" );
2139 field = other_key ? strdup( other_key ) : NULL;
2143 osrfHashIteratorFree( itr );
2146 if (!field || !fkey) {
2149 "%s: JOIN failed. No link defined between %s and %s",
2156 buffer_free(join_buf);
2158 jsonObjectFree(freeable_hash);
2159 jsonIteratorFree(search_itr);
2165 char* type = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "type" ) );
2167 if ( !strcasecmp(type,"left") ) {
2168 buffer_add(join_buf, " LEFT JOIN");
2169 } else if ( !strcasecmp(type,"right") ) {
2170 buffer_add(join_buf, " RIGHT JOIN");
2171 } else if ( !strcasecmp(type,"full") ) {
2172 buffer_add(join_buf, " FULL JOIN");
2174 buffer_add(join_buf, " INNER JOIN");
2177 buffer_add(join_buf, " INNER JOIN");
2181 char* table = getSourceDefinition(idlClass);
2185 jsonIteratorFree( search_itr );
2186 buffer_free( join_buf );
2188 jsonObjectFree( freeable_hash );
2192 buffer_fadd(join_buf, " %s AS \"%s\" ON ( \"%s\".%s = \"%s\".%s",
2193 table, class, class, field, leftclass, fkey);
2196 const jsonObject* filter = jsonObjectGetKeyConst( snode, "filter" );
2198 char* filter_op = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "filter_op" ) );
2200 if (!strcasecmp("or",filter_op)) {
2201 buffer_add( join_buf, " OR " );
2203 buffer_add( join_buf, " AND " );
2206 buffer_add( join_buf, " AND " );
2209 char* jpred = searchWHERE( filter, idlClass, AND_OP_JOIN, NULL );
2210 OSRF_BUFFER_ADD_CHAR( join_buf, ' ' );
2211 OSRF_BUFFER_ADD( join_buf, jpred );
2216 buffer_add(join_buf, " ) ");
2218 const jsonObject* join_filter = jsonObjectGetKeyConst( snode, "join" );
2220 char* jpred = searchJOIN( join_filter, idlClass );
2221 OSRF_BUFFER_ADD_CHAR( join_buf, ' ' );
2222 OSRF_BUFFER_ADD( join_buf, jpred );
2231 jsonObjectFree(freeable_hash);
2232 jsonIteratorFree(search_itr);
2234 return buffer_release(join_buf);
2239 { +class : { -or|-and : { field : { op : value }, ... } ... }, ... }
2240 { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }
2241 [ { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }, ... ]
2245 static char* searchWHERE ( const jsonObject* search_hash, osrfHash* meta, int opjoin_type, osrfMethodContext* ctx ) {
2249 "%s: Entering searchWHERE; search_hash addr = %p, meta addr = %p, opjoin_type = %d, ctx addr = %p",
2257 growing_buffer* sql_buf = buffer_init(128);
2259 jsonObject* node = NULL;
2262 if ( search_hash->type == JSON_ARRAY ) {
2263 osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_ARRAY", MODULENAME);
2264 jsonIterator* search_itr = jsonNewIterator( search_hash );
2265 while ( (node = jsonIteratorNext( search_itr )) ) {
2269 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2270 else buffer_add(sql_buf, " AND ");
2273 char* subpred = searchWHERE( node, meta, opjoin_type, ctx );
2274 buffer_fadd(sql_buf, "( %s )", subpred);
2277 jsonIteratorFree(search_itr);
2279 } else if ( search_hash->type == JSON_HASH ) {
2280 osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_HASH", MODULENAME);
2281 jsonIterator* search_itr = jsonNewIterator( search_hash );
2282 while ( (node = jsonIteratorNext( search_itr )) ) {
2287 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2288 else buffer_add(sql_buf, " AND ");
2291 if ( !strncmp("+",search_itr->key,1) ) {
2292 if ( node->type == JSON_STRING ) {
2293 char* subpred = jsonObjectToSimpleString( node );
2294 buffer_fadd(sql_buf, " \"%s\".%s ", search_itr->key + 1, subpred);
2297 char* subpred = searchWHERE( node, osrfHashGet( oilsIDL(), search_itr->key + 1 ), AND_OP_JOIN, ctx );
2298 buffer_fadd(sql_buf, "( %s )", subpred);
2301 } else if ( !strcasecmp("-or",search_itr->key) ) {
2302 char* subpred = searchWHERE( node, meta, OR_OP_JOIN, ctx );
2303 buffer_fadd(sql_buf, "( %s )", subpred);
2305 } else if ( !strcasecmp("-and",search_itr->key) ) {
2306 char* subpred = searchWHERE( node, meta, AND_OP_JOIN, ctx );
2307 buffer_fadd(sql_buf, "( %s )", subpred);
2309 } else if ( !strcasecmp("-exists",search_itr->key) ) {
2310 char* subpred = SELECT(
2312 jsonObjectGetKey( node, "select" ),
2313 jsonObjectGetKey( node, "from" ),
2314 jsonObjectGetKey( node, "where" ),
2315 jsonObjectGetKey( node, "having" ),
2316 jsonObjectGetKey( node, "order_by" ),
2317 jsonObjectGetKey( node, "limit" ),
2318 jsonObjectGetKey( node, "offset" ),
2322 buffer_fadd(sql_buf, "EXISTS ( %s )", subpred);
2324 } else if ( !strcasecmp("-not-exists",search_itr->key) ) {
2325 char* subpred = SELECT(
2327 jsonObjectGetKey( node, "select" ),
2328 jsonObjectGetKey( node, "from" ),
2329 jsonObjectGetKey( node, "where" ),
2330 jsonObjectGetKey( node, "having" ),
2331 jsonObjectGetKey( node, "order_by" ),
2332 jsonObjectGetKey( node, "limit" ),
2333 jsonObjectGetKey( node, "offset" ),
2337 buffer_fadd(sql_buf, "NOT EXISTS ( %s )", subpred);
2341 char* class = osrfHashGet(meta, "classname");
2342 osrfHash* fields = osrfHashGet(meta, "fields");
2343 osrfHash* field = osrfHashGet( fields, search_itr->key );
2347 char* table = getSourceDefinition(meta);
2349 table = strdup( "(?)" );
2352 "%s: Attempt to reference non-existent column %s on %s (%s)",
2358 buffer_free(sql_buf);
2360 jsonIteratorFree(search_itr);
2364 char* subpred = searchPredicate( class, field, node, ctx );
2365 buffer_add( sql_buf, subpred );
2369 jsonIteratorFree(search_itr);
2372 // ERROR ... only hash and array allowed at this level
2373 char* predicate_string = jsonObjectToJSON( search_hash );
2376 "%s: Invalid predicate structure: %s",
2380 buffer_free(sql_buf);
2381 free(predicate_string);
2386 return buffer_release(sql_buf);
2390 /* method context */ osrfMethodContext* ctx,
2392 /* SELECT */ jsonObject* selhash,
2393 /* FROM */ jsonObject* join_hash,
2394 /* WHERE */ jsonObject* search_hash,
2395 /* HAVING */ jsonObject* having_hash,
2396 /* ORDER BY */ jsonObject* order_hash,
2397 /* LIMIT */ jsonObject* limit,
2398 /* OFFSET */ jsonObject* offset,
2399 /* flags */ int flags
2401 const char* locale = osrf_message_get_last_locale();
2403 // in case we don't get a select list
2404 jsonObject* defaultselhash = NULL;
2406 // general tmp objects
2407 const jsonObject* tmp_const;
2408 jsonObject* selclass = NULL;
2409 jsonObject* selfield = NULL;
2410 jsonObject* snode = NULL;
2411 jsonObject* onode = NULL;
2413 char* string = NULL;
2414 int from_function = 0;
2419 // the core search class
2420 char* core_class = NULL;
2422 // metadata about the core search class
2423 osrfHash* core_meta = NULL;
2425 // punt if there's no core class
2426 if (!join_hash || ( join_hash->type == JSON_HASH && !join_hash->size )) {
2429 "%s: FROM clause is missing or empty",
2433 osrfAppSessionStatus(
2435 OSRF_STATUS_INTERNALSERVERERROR,
2436 "osrfMethodException",
2438 "FROM clause is missing or empty in JSON query"
2443 // get the core class -- the only key of the top level FROM clause, or a string
2444 if (join_hash->type == JSON_HASH) {
2445 jsonIterator* tmp_itr = jsonNewIterator( join_hash );
2446 snode = jsonIteratorNext( tmp_itr );
2448 core_class = strdup( tmp_itr->key );
2451 jsonObject* extra = jsonIteratorNext( tmp_itr );
2453 jsonIteratorFree( tmp_itr );
2456 // There shouldn't be more than one entry in join_hash
2460 "%s: Malformed FROM clause: extra entry in JSON_HASH",
2464 osrfAppSessionStatus(
2466 OSRF_STATUS_INTERNALSERVERERROR,
2467 "osrfMethodException",
2469 "Malformed FROM clause in JSON query"
2472 return NULL; // Malformed join_hash; extra entry
2474 } else if (join_hash->type == JSON_ARRAY) {
2476 core_class = jsonObjectToSimpleString( jsonObjectGetIndex(join_hash, 0) );
2479 } else if (join_hash->type == JSON_STRING) {
2480 core_class = jsonObjectToSimpleString( join_hash );
2486 if (!from_function) {
2487 // Get the IDL class definition for the core class
2488 core_meta = osrfHashGet( oilsIDL(), core_class );
2489 if( !core_meta ) { // Didn't find it?
2492 "%s: SELECT clause references undefined class: \"%s\"",
2497 osrfAppSessionStatus(
2499 OSRF_STATUS_INTERNALSERVERERROR,
2500 "osrfMethodException",
2502 "SELECT clause references undefined class in JSON query"
2508 // Make sure the class isn't virtual
2509 if( str_is_true( osrfHashGet( core_meta, "virtual" ) ) ) {
2512 "%s: Core class is virtual: \"%s\"",
2517 osrfAppSessionStatus(
2519 OSRF_STATUS_INTERNALSERVERERROR,
2520 "osrfMethodException",
2522 "FROM clause references virtual class in JSON query"
2529 // if the select list is empty, or the core class field list is '*',
2530 // build the default select list ...
2532 selhash = defaultselhash = jsonNewObjectType(JSON_HASH);
2533 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2534 } else if( selhash->type != JSON_HASH ) {
2535 const char* json_type;
2536 switch ( selhash->type )
2539 json_type = "JSON_ARRAY";
2542 json_type = "JSON_STRING";
2545 json_type = "JSON_NUMBER";
2548 json_type = "JSON_NULL";
2551 json_type = "JSON_BOOL";
2554 json_type = "(unrecognized)";
2559 "%s: Expected JSON_HASH for SELECT clause; found %s",
2565 osrfAppSessionStatus(
2567 OSRF_STATUS_INTERNALSERVERERROR,
2568 "osrfMethodException",
2570 "Malformed SELECT clause in JSON query"
2574 } else if ( (tmp_const = jsonObjectGetKeyConst( selhash, core_class )) && tmp_const->type == JSON_STRING ) {
2575 char* _x = jsonObjectToSimpleString( tmp_const );
2576 if (!strncmp( "*", _x, 1 )) {
2577 jsonObjectRemoveKey( selhash, core_class );
2578 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2584 growing_buffer* sql_buf = buffer_init(128);
2586 // temp buffer for the SELECT list
2587 growing_buffer* select_buf = buffer_init(128);
2588 growing_buffer* order_buf = buffer_init(128);
2589 growing_buffer* group_buf = buffer_init(128);
2590 growing_buffer* having_buf = buffer_init(128);
2592 // Build a select list
2593 if(from_function) // From a function we select everything
2594 OSRF_BUFFER_ADD_CHAR( select_buf, '*' );
2597 // If we need to build a default list, prepare to do so
2598 jsonObject* _tmp = jsonObjectGetKey( selhash, core_class );
2599 if ( _tmp && !_tmp->size ) {
2601 osrfHash* core_fields = osrfHashGet( core_meta, "fields" );
2603 osrfHashIterator* field_itr = osrfNewHashIterator( core_fields );
2604 osrfHash* field_def;
2605 while( ( field_def = osrfHashIteratorNext( field_itr ) ) ) {
2606 if( ! str_is_true( osrfHashGet( field_def, "virtual" ) ) ) {
2607 // This field is not virtual, so add it to the list
2608 jsonObjectPush( _tmp, jsonNewObject( osrfHashIteratorKey( field_itr ) ) );
2611 osrfHashIteratorFree( field_itr );
2614 // Now build the actual select list
2616 jsonObject* is_agg = jsonObjectFindPath(selhash, "//aggregate");
2619 jsonIterator* selclass_itr = jsonNewIterator( selhash );
2620 while ( (selclass = jsonIteratorNext( selclass_itr )) ) { // For each class
2622 // round trip through the idl, just to be safe
2623 const char* cname = selclass_itr->key;
2624 osrfHash* idlClass = osrfHashGet( oilsIDL(), cname );
2626 // No such class. Skip it.
2629 // Make sure the target relation is in the join tree.
2631 // At this point join_hash is a step down from the join_hash we
2632 // received as a parameter. If the original was a JSON_STRING,
2633 // then json_hash is now NULL. If the original was a JSON_HASH,
2634 // then json_hash is now the first (and only) entry in it,
2635 // denoting the core class. We've already excluded the
2636 // possibility that the original was a JSON_ARRAY, because in
2637 // that case from_function would be non-NULL, and we wouldn't
2640 int class_in_from_clause; // boolean
2642 if ( ! strcmp( core_class, cname ))
2643 // This is the core class -- no problem
2644 class_in_from_clause = 1;
2647 // There's only one class in the FROM clause, and this isn't it
2648 class_in_from_clause = 0;
2649 else if (join_hash->type == JSON_STRING) {
2650 // There's only one class in the FROM clause
2651 string = jsonObjectToSimpleString(join_hash);
2652 if ( strcmp( string, cname ) )
2653 class_in_from_clause = 0; // This isn't it
2655 class_in_from_clause = 1; // This is it
2658 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", cname);
2659 if ( 0 == found->size )
2660 class_in_from_clause = 0; // Nowhere in the join tree
2662 class_in_from_clause = 1; // Found it
2663 jsonObjectFree( found );
2667 // If the class isn't in the FROM clause, bail out
2668 if( ! class_in_from_clause ) {
2671 "%s: SELECT clause references class not in FROM clause: \"%s\"",
2676 osrfAppSessionStatus(
2678 OSRF_STATUS_INTERNALSERVERERROR,
2679 "osrfMethodException",
2681 "Selected class not in FROM clause in JSON query"
2683 jsonIteratorFree( selclass_itr );
2684 jsonObjectFree( is_agg );
2685 buffer_free( sql_buf );
2686 buffer_free( select_buf );
2687 buffer_free( order_buf );
2688 buffer_free( group_buf );
2689 buffer_free( having_buf );
2694 // Look up some attributes of the current class, so that we
2695 // don't have to look them up again for each field
2696 osrfHash* class_field_set = osrfHashGet( idlClass, "fields" );
2697 char* class_pkey = osrfHashGet( idlClass, "primarykey" );
2698 char* class_tname = osrfHashGet( idlClass, "tablename" );
2700 // stitch together the column list ...
2701 jsonIterator* select_itr = jsonNewIterator( selclass );
2702 while ( (selfield = jsonIteratorNext( select_itr )) ) { // for each SELECT column
2704 // If we need a separator comma, add one
2708 OSRF_BUFFER_ADD_CHAR( select_buf, ',' );
2711 // ... if it's a string, just toss it on the pile
2712 if (selfield->type == JSON_STRING) {
2714 // again, just to be safe
2715 const char* col_name = selfield->value.s;
2716 osrfHash* field_def = osrfHashGet( class_field_set, col_name );
2717 if ( !field_def ) continue; // No such field in current class; skip it
2721 if (flags & DISABLE_I18N)
2724 i18n = osrfHashGet(field_def, "i18n");
2726 if( str_is_true( i18n ) ) {
2727 buffer_fadd( select_buf,
2728 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2729 class_tname, cname, col_name, class_pkey, cname, class_pkey, locale, col_name );
2731 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2734 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2737 // ... but it could be an object, in which case we check for a Field Transform
2740 char* col_name = jsonObjectToSimpleString( jsonObjectGetKeyConst( selfield, "column" ) );
2742 // Get the field definition from the IDL
2743 osrfHash* field_def = osrfHashGet( class_field_set, col_name );
2744 if ( !field_def ) continue; // No such field defined in IDL. Skip it.
2746 // Decide what to use as a column alias
2748 if ((tmp_const = jsonObjectGetKeyConst( selfield, "alias" ))) {
2749 _alias = jsonObjectToSimpleString( tmp_const );
2750 } else { // Use field name as the alias
2754 if (jsonObjectGetKeyConst( selfield, "transform" )) {
2755 char* transform_str = searchFieldTransform(cname, field_def, selfield);
2756 buffer_fadd(select_buf, " %s AS \"%s\"", transform_str, _alias);
2757 free(transform_str);
2762 if (flags & DISABLE_I18N)
2765 i18n = osrfHashGet(field_def, "i18n");
2767 if( str_is_true( i18n ) ) {
2768 buffer_fadd( select_buf,
2769 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2770 class_tname, cname, col_name, class_pkey, cname, class_pkey, locale, _alias);
2772 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, _alias);
2775 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, _alias);
2779 if( _alias != col_name )
2784 if (is_agg->size || (flags & SELECT_DISTINCT)) {
2786 const jsonObject* aggregate_obj = jsonObjectGetKey( selfield, "aggregate" );
2787 if ( ! obj_is_true( aggregate_obj ) ) {
2791 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
2794 buffer_fadd(group_buf, " %d", sel_pos);
2796 } else if (is_agg = jsonObjectGetKey( selfield, "having" )) {
2800 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
2803 _column = searchFieldTransform(cname, field, selfield);
2804 OSRF_BUFFER_ADD_CHAR(group_buf, ' ');
2805 OSRF_BUFFER_ADD(group_buf, _column);
2806 _column = searchFieldTransform(cname, field, selfield);
2812 } // end while -- iterating across SELECT columns
2814 jsonIteratorFree(select_itr);
2815 } // end while -- iterating across classes
2817 jsonIteratorFree(selclass_itr);
2819 if (is_agg) jsonObjectFree(is_agg);
2823 char* col_list = buffer_release(select_buf);
2825 if (from_function) table = searchValueTransform(join_hash);
2826 else table = getSourceDefinition(core_meta);
2830 osrfAppSessionStatus(
2832 OSRF_STATUS_INTERNALSERVERERROR,
2833 "osrfMethodException",
2835 "Unable to identify table for core class"
2838 buffer_free( sql_buf );
2839 buffer_free( order_buf );
2840 buffer_free( group_buf );
2841 buffer_free( having_buf );
2842 if( defaultselhash ) jsonObjectFree( defaultselhash );
2847 // Put it all together
2848 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\" ", col_list, table, core_class );
2852 if (!from_function) {
2853 // Now, walk the join tree and add that clause
2855 char* join_clause = searchJOIN( join_hash, core_meta );
2857 buffer_add(sql_buf, join_clause);
2861 osrfAppSessionStatus(
2863 OSRF_STATUS_INTERNALSERVERERROR,
2864 "osrfMethodException",
2866 "Unable to construct JOIN clause(s)"
2868 buffer_free( sql_buf );
2869 buffer_free( order_buf );
2870 buffer_free( group_buf );
2871 buffer_free( having_buf );
2872 if( defaultselhash ) jsonObjectFree( defaultselhash );
2878 // Build a WHERE clause, if there is one
2879 if ( search_hash ) {
2880 buffer_add(sql_buf, " WHERE ");
2882 // and it's on the WHERE clause
2883 char* pred = searchWHERE( search_hash, core_meta, AND_OP_JOIN, ctx );
2886 buffer_add(sql_buf, pred);
2890 osrfAppSessionStatus(
2892 OSRF_STATUS_INTERNALSERVERERROR,
2893 "osrfMethodException",
2895 "Severe query error in WHERE predicate -- see error log for more details"
2899 buffer_free(having_buf);
2900 buffer_free(group_buf);
2901 buffer_free(order_buf);
2902 buffer_free(sql_buf);
2903 if (defaultselhash) jsonObjectFree(defaultselhash);
2908 // Build a HAVING clause, if there is one
2909 if ( having_hash ) {
2910 buffer_add(sql_buf, " HAVING ");
2912 // and it's on the the WHERE clause
2913 char* pred = searchWHERE( having_hash, core_meta, AND_OP_JOIN, ctx );
2916 buffer_add(sql_buf, pred);
2920 osrfAppSessionStatus(
2922 OSRF_STATUS_INTERNALSERVERERROR,
2923 "osrfMethodException",
2925 "Severe query error in HAVING predicate -- see error log for more details"
2929 buffer_free(having_buf);
2930 buffer_free(group_buf);
2931 buffer_free(order_buf);
2932 buffer_free(sql_buf);
2933 if (defaultselhash) jsonObjectFree(defaultselhash);
2938 // Build an ORDER BY clause, if there is one
2940 jsonIterator* class_itr = jsonNewIterator( order_hash );
2941 while ( (snode = jsonIteratorNext( class_itr )) ) {
2943 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
2946 if ( snode->type == JSON_HASH ) {
2948 jsonIterator* order_itr = jsonNewIterator( snode );
2949 while ( (onode = jsonIteratorNext( order_itr )) ) {
2951 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
2954 char* direction = NULL;
2955 if ( onode->type == JSON_HASH ) {
2956 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
2957 string = searchFieldTransform(
2959 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
2963 growing_buffer* field_buf = buffer_init(16);
2964 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
2965 string = buffer_release(field_buf);
2968 if ( (tmp_const = jsonObjectGetKeyConst( onode, "direction" )) ) {
2969 direction = jsonObjectToSimpleString(tmp_const);
2970 if (!strncasecmp(direction, "d", 1)) {
2972 direction = " DESC";
2980 string = strdup(order_itr->key);
2981 direction = jsonObjectToSimpleString(onode);
2982 if (!strncasecmp(direction, "d", 1)) {
2984 direction = " DESC";
2994 buffer_add(order_buf, ", ");
2997 buffer_add(order_buf, string);
3001 buffer_add(order_buf, direction);
3005 // jsonIteratorFree(order_itr);
3007 } else if ( snode->type == JSON_ARRAY ) {
3009 jsonIterator* order_itr = jsonNewIterator( snode );
3010 while ( (onode = jsonIteratorNext( order_itr )) ) {
3012 char* _f = jsonObjectToSimpleString( onode );
3014 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, _f))
3020 buffer_add(order_buf, ", ");
3023 buffer_add(order_buf, _f);
3027 // jsonIteratorFree(order_itr);
3030 // IT'S THE OOOOOOOOOOOLD STYLE!
3032 osrfLogError(OSRF_LOG_MARK, "%s: Possible SQL injection attempt; direct order by is not allowed", MODULENAME);
3034 osrfAppSessionStatus(
3036 OSRF_STATUS_INTERNALSERVERERROR,
3037 "osrfMethodException",
3039 "Severe query error -- see error log for more details"
3044 buffer_free(having_buf);
3045 buffer_free(group_buf);
3046 buffer_free(order_buf);
3047 buffer_free(sql_buf);
3048 if (defaultselhash) jsonObjectFree(defaultselhash);
3049 jsonIteratorFree(class_itr);
3054 // jsonIteratorFree(class_itr);
3058 string = buffer_release(group_buf);
3061 OSRF_BUFFER_ADD( sql_buf, " GROUP BY " );
3062 OSRF_BUFFER_ADD( sql_buf, string );
3067 string = buffer_release(having_buf);
3070 OSRF_BUFFER_ADD( sql_buf, " HAVING " );
3071 OSRF_BUFFER_ADD( sql_buf, string );
3076 string = buffer_release(order_buf);
3079 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
3080 OSRF_BUFFER_ADD( sql_buf, string );
3086 string = jsonObjectToSimpleString(limit);
3087 buffer_fadd( sql_buf, " LIMIT %d", atoi(string) );
3092 string = jsonObjectToSimpleString(offset);
3093 buffer_fadd( sql_buf, " OFFSET %d", atoi(string) );
3097 if (!(flags & SUBSELECT)) OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
3100 if (defaultselhash) jsonObjectFree(defaultselhash);
3102 return buffer_release(sql_buf);
3106 static char* buildSELECT ( jsonObject* search_hash, jsonObject* order_hash, osrfHash* meta, osrfMethodContext* ctx ) {
3108 const char* locale = osrf_message_get_last_locale();
3110 osrfHash* fields = osrfHashGet(meta, "fields");
3111 char* core_class = osrfHashGet(meta, "classname");
3113 const jsonObject* join_hash = jsonObjectGetKeyConst( order_hash, "join" );
3115 jsonObject* node = NULL;
3116 jsonObject* snode = NULL;
3117 jsonObject* onode = NULL;
3118 const jsonObject* _tmp = NULL;
3119 jsonObject* selhash = NULL;
3120 jsonObject* defaultselhash = NULL;
3122 growing_buffer* sql_buf = buffer_init(128);
3123 growing_buffer* select_buf = buffer_init(128);
3125 if ( !(selhash = jsonObjectGetKey( order_hash, "select" )) ) {
3126 defaultselhash = jsonNewObjectType(JSON_HASH);
3127 selhash = defaultselhash;
3130 if ( !jsonObjectGetKeyConst(selhash,core_class) ) {
3131 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
3132 jsonObject* flist = jsonObjectGetKey( selhash, core_class );
3137 osrfStringArray* keys = osrfHashKeys( fields );
3138 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
3139 if( ! str_is_true( osrfHashGet( osrfHashGet( fields, field ), "virtual" ) ) )
3140 jsonObjectPush( flist, jsonNewObject( field ) );
3142 osrfStringArrayFree(keys);
3146 jsonIterator* class_itr = jsonNewIterator( selhash );
3147 while ( (snode = jsonIteratorNext( class_itr )) ) {
3149 char* cname = class_itr->key;
3150 osrfHash* idlClass = osrfHashGet( oilsIDL(), cname );
3151 if (!idlClass) continue;
3153 if (strcmp(core_class,class_itr->key)) {
3154 if (!join_hash) continue;
3156 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", class_itr->key);
3158 jsonObjectFree(found);
3162 jsonObjectFree(found);
3165 jsonIterator* select_itr = jsonNewIterator( snode );
3166 while ( (node = jsonIteratorNext( select_itr )) ) {
3167 char* item_str = jsonObjectToSimpleString(node);
3168 osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), item_str );
3170 char* fname = osrfHashGet(field, "name");
3172 if (!field) continue;
3177 OSRF_BUFFER_ADD_CHAR(select_buf, ',');
3182 const jsonObject* no_i18n_obj = jsonObjectGetKey( order_hash, "no_i18n" );
3183 if ( obj_is_true( no_i18n_obj ) ) // Suppress internationalization?
3186 i18n = osrfHashGet(field, "i18n");
3188 if( str_is_true( i18n ) ) {
3189 char* pkey = osrfHashGet(idlClass, "primarykey");
3190 char* tname = osrfHashGet(idlClass, "tablename");
3192 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);
3194 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
3197 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
3201 jsonIteratorFree(select_itr);
3204 jsonIteratorFree(class_itr);
3206 char* col_list = buffer_release(select_buf);
3207 char* table = getSourceDefinition(meta);
3209 table = strdup( "(null)" );
3211 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\"", col_list, table, core_class );
3216 char* join_clause = searchJOIN( join_hash, meta );
3217 OSRF_BUFFER_ADD_CHAR(sql_buf, ' ');
3218 OSRF_BUFFER_ADD(sql_buf, join_clause);
3222 osrfLogDebug(OSRF_LOG_MARK, "%s pre-predicate SQL = %s",
3223 MODULENAME, OSRF_BUFFER_C_STR(sql_buf));
3225 buffer_add(sql_buf, " WHERE ");
3227 char* pred = searchWHERE( search_hash, meta, AND_OP_JOIN, ctx );
3229 osrfAppSessionStatus(
3231 OSRF_STATUS_INTERNALSERVERERROR,
3232 "osrfMethodException",
3234 "Severe query error -- see error log for more details"
3236 buffer_free(sql_buf);
3237 if(defaultselhash) jsonObjectFree(defaultselhash);
3240 buffer_add(sql_buf, pred);
3245 char* string = NULL;
3246 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "order_by" )) ){
3248 growing_buffer* order_buf = buffer_init(128);
3251 jsonIterator* class_itr = jsonNewIterator( _tmp );
3252 while ( (snode = jsonIteratorNext( class_itr )) ) {
3254 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
3257 if ( snode->type == JSON_HASH ) {
3259 jsonIterator* order_itr = jsonNewIterator( snode );
3260 while ( (onode = jsonIteratorNext( order_itr )) ) {
3262 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
3265 char* direction = NULL;
3266 if ( onode->type == JSON_HASH ) {
3267 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
3268 string = searchFieldTransform(
3270 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
3274 growing_buffer* field_buf = buffer_init(16);
3275 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
3276 string = buffer_release(field_buf);
3279 if ( (_tmp = jsonObjectGetKeyConst( onode, "direction" )) ) {
3280 direction = jsonObjectToSimpleString(_tmp);
3281 if (!strncasecmp(direction, "d", 1)) {
3283 direction = " DESC";
3291 string = strdup(order_itr->key);
3292 direction = jsonObjectToSimpleString(onode);
3293 if (!strncasecmp(direction, "d", 1)) {
3295 direction = " DESC";
3305 buffer_add(order_buf, ", ");
3308 buffer_add(order_buf, string);
3312 buffer_add(order_buf, direction);
3317 jsonIteratorFree(order_itr);
3320 string = jsonObjectToSimpleString(snode);
3321 buffer_add(order_buf, string);
3328 jsonIteratorFree(class_itr);
3330 string = buffer_release(order_buf);
3333 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
3334 OSRF_BUFFER_ADD( sql_buf, string );
3340 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "limit" )) ){
3341 string = jsonObjectToSimpleString(_tmp);
3350 _tmp = jsonObjectGetKeyConst( order_hash, "offset" );
3352 string = jsonObjectToSimpleString(_tmp);
3362 if (defaultselhash) jsonObjectFree(defaultselhash);
3364 OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
3365 return buffer_release(sql_buf);
3368 int doJSONSearch ( osrfMethodContext* ctx ) {
3369 if(osrfMethodVerifyContext( ctx )) {
3370 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
3374 osrfLogDebug(OSRF_LOG_MARK, "Recieved query request");
3379 dbhandle = writehandle;
3381 jsonObject* hash = jsonObjectGetIndex(ctx->params, 0);
3385 if ( obj_is_true( jsonObjectGetKey( hash, "distinct" ) ) )
3386 flags |= SELECT_DISTINCT;
3388 if ( obj_is_true( jsonObjectGetKey( hash, "no_i18n" ) ) )
3389 flags |= DISABLE_I18N;
3391 osrfLogDebug(OSRF_LOG_MARK, "Building SQL ...");
3394 jsonObjectGetKey( hash, "select" ),
3395 jsonObjectGetKey( hash, "from" ),
3396 jsonObjectGetKey( hash, "where" ),
3397 jsonObjectGetKey( hash, "having" ),
3398 jsonObjectGetKey( hash, "order_by" ),
3399 jsonObjectGetKey( hash, "limit" ),
3400 jsonObjectGetKey( hash, "offset" ),
3409 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3410 dbi_result result = dbi_conn_query(dbhandle, sql);
3413 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3415 if (dbi_result_first_row(result)) {
3416 /* JSONify the result */
3417 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3420 jsonObject* return_val = oilsMakeJSONFromResult( result );
3421 osrfAppRespond( ctx, return_val );
3422 jsonObjectFree( return_val );
3423 } while (dbi_result_next_row(result));
3426 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
3429 osrfAppRespondComplete( ctx, NULL );
3431 /* clean up the query */
3432 dbi_result_free(result);
3436 osrfLogError(OSRF_LOG_MARK, "%s: Error with query [%s]", MODULENAME, sql);
3437 osrfAppSessionStatus(
3439 OSRF_STATUS_INTERNALSERVERERROR,
3440 "osrfMethodException",
3442 "Severe query error -- see error log for more details"
3450 static jsonObject* doFieldmapperSearch ( osrfMethodContext* ctx, osrfHash* meta,
3451 const jsonObject* params, int* err ) {
3454 dbhandle = writehandle;
3456 osrfHash* links = osrfHashGet(meta, "links");
3457 osrfHash* fields = osrfHashGet(meta, "fields");
3458 char* core_class = osrfHashGet(meta, "classname");
3459 char* pkey = osrfHashGet(meta, "primarykey");
3461 const jsonObject* _tmp;
3463 jsonObject* search_hash = jsonObjectGetIndex(params, 0);
3464 jsonObject* order_hash = jsonObjectGetIndex(params, 1);
3466 char* sql = buildSELECT( search_hash, order_hash, meta, ctx );
3468 osrfLogDebug(OSRF_LOG_MARK, "Problem building query, returning NULL");
3473 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3475 dbi_result result = dbi_conn_query(dbhandle, sql);
3476 if( NULL == result ) {
3477 osrfLogError(OSRF_LOG_MARK, "%s: Error retrieving %s with query [%s]",
3478 MODULENAME, osrfHashGet(meta, "fieldmapper"), sql);
3479 osrfAppSessionStatus(
3481 OSRF_STATUS_INTERNALSERVERERROR,
3482 "osrfMethodException",
3484 "Severe query error -- see error log for more details"
3491 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3494 jsonObject* res_list = jsonNewObjectType(JSON_ARRAY);
3495 osrfHash* dedup = osrfNewHash();
3497 if (dbi_result_first_row(result)) {
3498 /* JSONify the result */
3499 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3501 obj = oilsMakeFieldmapperFromResult( result, meta );
3502 char* pkey_val = oilsFMGetString( obj, pkey );
3503 if ( osrfHashGet( dedup, pkey_val ) ) {
3504 jsonObjectFree(obj);
3507 osrfHashSet( dedup, pkey_val, pkey_val );
3508 jsonObjectPush(res_list, obj);
3510 } while (dbi_result_next_row(result));
3512 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s",
3516 osrfHashFree(dedup);
3517 /* clean up the query */
3518 dbi_result_free(result);
3521 if (res_list->size && order_hash) {
3522 _tmp = jsonObjectGetKeyConst( order_hash, "flesh" );
3524 int x = (int)jsonObjectGetNumber(_tmp);
3525 if (x == -1 || x > max_flesh_depth) x = max_flesh_depth;
3527 const jsonObject* temp_blob;
3528 if ((temp_blob = jsonObjectGetKeyConst( order_hash, "flesh_fields" )) && x > 0) {
3530 jsonObject* flesh_blob = jsonObjectClone( temp_blob );
3531 const jsonObject* flesh_fields = jsonObjectGetKeyConst( flesh_blob, core_class );
3533 osrfStringArray* link_fields = NULL;
3536 if (flesh_fields->size == 1) {
3537 char* _t = jsonObjectToSimpleString( jsonObjectGetIndex( flesh_fields, 0 ) );
3538 if (!strcmp(_t,"*")) link_fields = osrfHashKeys( links );
3544 link_fields = osrfNewStringArray(1);
3545 jsonIterator* _i = jsonNewIterator( flesh_fields );
3546 while ((_f = jsonIteratorNext( _i ))) {
3547 osrfStringArrayAdd( link_fields, jsonObjectToSimpleString( _f ) );
3549 jsonIteratorFree(_i);
3554 jsonIterator* itr = jsonNewIterator( res_list );
3555 while ((cur = jsonIteratorNext( itr ))) {
3560 while ( (link_field = osrfStringArrayGetString(link_fields, i++)) ) {
3562 osrfLogDebug(OSRF_LOG_MARK, "Starting to flesh %s", link_field);
3564 osrfHash* kid_link = osrfHashGet(links, link_field);
3565 if (!kid_link) continue;
3567 osrfHash* field = osrfHashGet(fields, link_field);
3568 if (!field) continue;
3570 osrfHash* value_field = field;
3572 osrfHash* kid_idl = osrfHashGet(oilsIDL(), osrfHashGet(kid_link, "class"));
3573 if (!kid_idl) continue;
3575 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3576 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3579 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) { // might_have
3580 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3583 osrfStringArray* link_map = osrfHashGet( kid_link, "map" );
3585 if (link_map->size > 0) {
3586 jsonObject* _kid_key = jsonNewObjectType(JSON_ARRAY);
3589 jsonNewObject( osrfStringArrayGetString( link_map, 0 ) )
3594 osrfHashGet(kid_link, "class"),
3601 "Link field: %s, remote class: %s, fkey: %s, reltype: %s",
3602 osrfHashGet(kid_link, "field"),
3603 osrfHashGet(kid_link, "class"),
3604 osrfHashGet(kid_link, "key"),
3605 osrfHashGet(kid_link, "reltype")
3608 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
3609 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // search hash
3610 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // order/flesh hash
3612 osrfLogDebug(OSRF_LOG_MARK, "Creating dummy params object...");
3615 jsonObjectToSimpleString(
3618 atoi( osrfHashGet(value_field, "array_position") )
3623 osrfLogDebug(OSRF_LOG_MARK, "Nothing to search for!");
3628 jsonObjectGetIndex(fake_params, 0),
3629 osrfHashGet(kid_link, "key"),
3630 jsonNewObject( search_key )
3637 jsonObjectGetIndex(fake_params, 1),
3639 jsonNewNumberObject( (double)(x - 1 + link_map->size) )
3643 jsonObjectSetKey( jsonObjectGetIndex(fake_params, 1), "flesh_fields", jsonObjectClone(flesh_blob) );
3645 if (jsonObjectGetKeyConst(order_hash, "order_by")) {
3647 jsonObjectGetIndex(fake_params, 1),
3649 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "order_by"))
3653 if (jsonObjectGetKeyConst(order_hash, "select")) {
3655 jsonObjectGetIndex(fake_params, 1),
3657 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "select"))
3661 jsonObject* kids = doFieldmapperSearch(ctx, kid_idl, fake_params, err);
3664 jsonObjectFree( fake_params );
3665 osrfStringArrayFree(link_fields);
3666 jsonIteratorFree(itr);
3667 jsonObjectFree(res_list);
3668 jsonObjectFree(flesh_blob);
3672 osrfLogDebug(OSRF_LOG_MARK, "Search for %s return %d linked objects", osrfHashGet(kid_link, "class"), kids->size);
3674 jsonObject* X = NULL;
3675 if ( link_map->size > 0 && kids->size > 0 ) {
3677 kids = jsonNewObjectType(JSON_ARRAY);
3679 jsonObject* _k_node;
3680 jsonIterator* _k = jsonNewIterator( X );
3681 while ((_k_node = jsonIteratorNext( _k ))) {
3687 (unsigned long)atoi(
3693 osrfHashGet(kid_link, "class")
3697 osrfStringArrayGetString( link_map, 0 )
3706 jsonIteratorFree(_k);
3709 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_a" )) || !(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) {
3710 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3713 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3714 jsonObjectClone( jsonObjectGetIndex(kids, 0) )
3718 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3719 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3722 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3723 jsonObjectClone( kids )
3728 jsonObjectFree(kids);
3732 jsonObjectFree( kids );
3733 jsonObjectFree( fake_params );
3735 osrfLogDebug(OSRF_LOG_MARK, "Fleshing of %s complete", osrfHashGet(kid_link, "field"));
3736 osrfLogDebug(OSRF_LOG_MARK, "%s", jsonObjectToJSON(cur));
3740 jsonObjectFree( flesh_blob );
3741 osrfStringArrayFree(link_fields);
3742 jsonIteratorFree(itr);
3751 static jsonObject* doUpdate(osrfMethodContext* ctx, int* err ) {
3753 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3755 jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
3757 jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
3760 if (!verifyObjectClass(ctx, target)) {
3765 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3766 osrfAppSessionStatus(
3768 OSRF_STATUS_BADREQUEST,
3769 "osrfMethodException",
3771 "No active transaction -- required for UPDATE"
3777 // The following test is harmless but redundant. If a class is
3778 // readonly, we don't register an update method for it.
3779 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
3780 osrfAppSessionStatus(
3782 OSRF_STATUS_BADREQUEST,
3783 "osrfMethodException",
3785 "Cannot UPDATE readonly class"
3791 dbhandle = writehandle;
3793 char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
3795 // Set the last_xact_id
3796 int index = oilsIDL_ntop( target->classname, "last_xact_id" );
3798 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
3799 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
3802 char* pkey = osrfHashGet(meta, "primarykey");
3803 osrfHash* fields = osrfHashGet(meta, "fields");
3805 char* id = oilsFMGetString( target, pkey );
3809 "%s updating %s object with %s = %s",
3811 osrfHashGet(meta, "fieldmapper"),
3816 growing_buffer* sql = buffer_init(128);
3817 buffer_fadd(sql,"UPDATE %s SET", osrfHashGet(meta, "tablename"));
3822 osrfStringArray* field_list = osrfHashKeys( fields );
3823 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
3825 osrfHash* field = osrfHashGet( fields, field_name );
3827 if(!( strcmp( field_name, pkey ) )) continue;
3828 if( str_is_true( osrfHashGet(osrfHashGet(fields,field_name), "virtual") ) )
3831 const jsonObject* field_object = oilsFMGetObject( target, field_name );
3834 if (field_object && field_object->classname) {
3835 value = oilsFMGetString(
3837 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
3840 value = jsonObjectToSimpleString( field_object );
3843 osrfLogDebug( OSRF_LOG_MARK, "Updating %s object with %s = %s", osrfHashGet(meta, "fieldmapper"), field_name, value);
3845 if (!field_object || field_object->type == JSON_NULL) {
3846 if ( !(!( strcmp( osrfHashGet(meta, "classname"), "au" ) ) && !( strcmp( field_name, "passwd" ) )) ) { // arg at the special case!
3847 if (first) first = 0;
3848 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3849 buffer_fadd( sql, " %s = NULL", field_name );
3852 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
3853 if (first) first = 0;
3854 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3856 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
3857 buffer_fadd( sql, " %s = %ld", field_name, atol(value) );
3858 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
3859 buffer_fadd( sql, " %s = %f", field_name, atof(value) );
3862 osrfLogDebug( OSRF_LOG_MARK, "%s is of type %s", field_name, osrfHashGet(field, "datatype"));
3865 if ( dbi_conn_quote_string(dbhandle, &value) ) {
3866 if (first) first = 0;
3867 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3868 buffer_fadd( sql, " %s = %s", field_name, value );
3871 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
3872 osrfAppSessionStatus(
3874 OSRF_STATUS_INTERNALSERVERERROR,
3875 "osrfMethodException",
3877 "Error quoting string -- please see the error log for more details"
3891 jsonObject* obj = jsonNewObject(id);
3893 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
3894 dbi_conn_quote_string(dbhandle, &id);
3896 buffer_fadd( sql, " WHERE %s = %s;", pkey, id );
3898 char* query = buffer_release(sql);
3899 osrfLogDebug(OSRF_LOG_MARK, "%s: Update SQL [%s]", MODULENAME, query);
3901 dbi_result result = dbi_conn_query(dbhandle, query);
3905 jsonObjectFree(obj);
3906 obj = jsonNewObject(NULL);
3909 "%s ERROR updating %s object with %s = %s",
3911 osrfHashGet(meta, "fieldmapper"),
3922 static jsonObject* doDelete(osrfMethodContext* ctx, int* err ) {
3924 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3926 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3927 osrfAppSessionStatus(
3929 OSRF_STATUS_BADREQUEST,
3930 "osrfMethodException",
3932 "No active transaction -- required for DELETE"
3938 // The following test is harmless but redundant. If a class is
3939 // readonly, we don't register a delete method for it.
3940 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
3941 osrfAppSessionStatus(
3943 OSRF_STATUS_BADREQUEST,
3944 "osrfMethodException",
3946 "Cannot DELETE readonly class"
3952 dbhandle = writehandle;
3956 char* pkey = osrfHashGet(meta, "primarykey");
3964 if (jsonObjectGetIndex(ctx->params, _obj_pos)->classname) {
3965 if (!verifyObjectClass(ctx, jsonObjectGetIndex( ctx->params, _obj_pos ))) {
3970 id = oilsFMGetString( jsonObjectGetIndex(ctx->params, _obj_pos), pkey );
3973 if (!verifyObjectPCRUD( ctx, NULL )) {
3978 id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, _obj_pos));
3983 "%s deleting %s object with %s = %s",
3985 osrfHashGet(meta, "fieldmapper"),
3990 obj = jsonNewObject(id);
3992 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
3993 dbi_conn_quote_string(writehandle, &id);
3995 dbi_result result = dbi_conn_queryf(writehandle, "DELETE FROM %s WHERE %s = %s;", osrfHashGet(meta, "tablename"), pkey, id);
3998 jsonObjectFree(obj);
3999 obj = jsonNewObject(NULL);
4002 "%s ERROR deleting %s object with %s = %s",
4004 osrfHashGet(meta, "fieldmapper"),
4017 static jsonObject* oilsMakeFieldmapperFromResult( dbi_result result, osrfHash* meta) {
4018 if(!(result && meta)) return jsonNULL;
4020 jsonObject* object = jsonNewObject(NULL);
4021 jsonObjectSetClass(object, osrfHashGet(meta, "classname"));
4023 osrfHash* fields = osrfHashGet(meta, "fields");
4025 osrfLogInternal(OSRF_LOG_MARK, "Setting object class to %s ", object->classname);
4029 char dt_string[256];
4033 int columnIndex = 1;
4035 unsigned short type;
4036 const char* columnName;
4038 /* cycle through the column list */
4039 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
4041 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
4043 fmIndex = -1; // reset the position
4045 /* determine the field type and storage attributes */
4046 type = dbi_result_get_field_type(result, columnName);
4047 attr = dbi_result_get_field_attribs(result, columnName);
4049 /* fetch the fieldmapper index */
4050 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
4052 if ( str_is_true( osrfHashGet(_f, "virtual") ) )
4055 const char* pos = (char*)osrfHashGet(_f, "array_position");
4056 if ( !pos ) continue;
4058 fmIndex = atoi( pos );
4059 osrfLogInternal(OSRF_LOG_MARK, "... Found column at position [%s]...", pos);
4064 if (dbi_result_field_is_null(result, columnName)) {
4065 jsonObjectSetIndex( object, fmIndex, jsonNewObject(NULL) );
4070 case DBI_TYPE_INTEGER :
4072 if( attr & DBI_INTEGER_SIZE8 )
4073 jsonObjectSetIndex( object, fmIndex,
4074 jsonNewNumberObject(dbi_result_get_longlong(result, columnName)));
4076 jsonObjectSetIndex( object, fmIndex,
4077 jsonNewNumberObject(dbi_result_get_int(result, columnName)));
4081 case DBI_TYPE_DECIMAL :
4082 jsonObjectSetIndex( object, fmIndex,
4083 jsonNewNumberObject(dbi_result_get_double(result, columnName)));
4086 case DBI_TYPE_STRING :
4092 jsonNewObject( dbi_result_get_string(result, columnName) )
4097 case DBI_TYPE_DATETIME :
4099 memset(dt_string, '\0', sizeof(dt_string));
4100 memset(&gmdt, '\0', sizeof(gmdt));
4102 _tmp_dt = dbi_result_get_datetime(result, columnName);
4105 if (!(attr & DBI_DATETIME_DATE)) {
4106 gmtime_r( &_tmp_dt, &gmdt );
4107 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
4108 } else if (!(attr & DBI_DATETIME_TIME)) {
4109 localtime_r( &_tmp_dt, &gmdt );
4110 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
4112 localtime_r( &_tmp_dt, &gmdt );
4113 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
4116 jsonObjectSetIndex( object, fmIndex, jsonNewObject(dt_string) );
4120 case DBI_TYPE_BINARY :
4121 osrfLogError( OSRF_LOG_MARK,
4122 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
4130 static jsonObject* oilsMakeJSONFromResult( dbi_result result ) {
4131 if(!result) return jsonNULL;
4133 jsonObject* object = jsonNewObject(NULL);
4136 char dt_string[256];
4140 int columnIndex = 1;
4142 unsigned short type;
4143 const char* columnName;
4145 /* cycle through the column list */
4146 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
4148 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
4150 fmIndex = -1; // reset the position
4152 /* determine the field type and storage attributes */
4153 type = dbi_result_get_field_type(result, columnName);
4154 attr = dbi_result_get_field_attribs(result, columnName);
4156 if (dbi_result_field_is_null(result, columnName)) {
4157 jsonObjectSetKey( object, columnName, jsonNewObject(NULL) );
4162 case DBI_TYPE_INTEGER :
4164 if( attr & DBI_INTEGER_SIZE8 )
4165 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_longlong(result, columnName)) );
4167 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_int(result, columnName)) );
4170 case DBI_TYPE_DECIMAL :
4171 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_double(result, columnName)) );
4174 case DBI_TYPE_STRING :
4175 jsonObjectSetKey( object, columnName, jsonNewObject(dbi_result_get_string(result, columnName)) );
4178 case DBI_TYPE_DATETIME :
4180 memset(dt_string, '\0', sizeof(dt_string));
4181 memset(&gmdt, '\0', sizeof(gmdt));
4183 _tmp_dt = dbi_result_get_datetime(result, columnName);
4186 if (!(attr & DBI_DATETIME_DATE)) {
4187 gmtime_r( &_tmp_dt, &gmdt );
4188 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
4189 } else if (!(attr & DBI_DATETIME_TIME)) {
4190 localtime_r( &_tmp_dt, &gmdt );
4191 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
4193 localtime_r( &_tmp_dt, &gmdt );
4194 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
4197 jsonObjectSetKey( object, columnName, jsonNewObject(dt_string) );
4200 case DBI_TYPE_BINARY :
4201 osrfLogError( OSRF_LOG_MARK,
4202 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
4210 // Interpret a string as true or false
4211 static int str_is_true( const char* str ) {
4212 if( NULL == str || strcasecmp( str, "true" ) )
4218 // Interpret a jsonObject as true or false
4219 static int obj_is_true( const jsonObject* obj ) {
4222 else switch( obj->type )
4230 if( strcasecmp( obj->value.s, "true" ) )
4234 case JSON_NUMBER : // Support 1/0 for perl's sake
4235 if( jsonObjectGetNumber( obj ) == 1.0 )