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 );
78 static const char* json_type( int code );
81 static jsonObject* verifyUserPCRUD( osrfMethodContext* );
82 static int verifyObjectPCRUD( osrfMethodContext*, const jsonObject* );
85 static dbi_conn writehandle; /* our MASTER db connection */
86 static dbi_conn dbhandle; /* our CURRENT db connection */
87 //static osrfHash * readHandles;
88 static jsonObject* jsonNULL = NULL; //
89 static int max_flesh_depth = 100;
91 /* called when this process is about to exit */
92 void osrfAppChildExit() {
93 osrfLogDebug(OSRF_LOG_MARK, "Child is exiting, disconnecting from database...");
96 if (writehandle == dbhandle) same = 1;
98 dbi_conn_query(writehandle, "ROLLBACK;");
99 dbi_conn_close(writehandle);
102 if (dbhandle && !same)
103 dbi_conn_close(dbhandle);
105 // XXX add cleanup of readHandles whenever that gets used
110 int osrfAppInitialize() {
112 osrfLogInfo(OSRF_LOG_MARK, "Initializing the CStore Server...");
113 osrfLogInfo(OSRF_LOG_MARK, "Finding XML file...");
115 if (!oilsIDLInit( osrf_settings_host_value("/IDL") )) return 1; /* return non-zero to indicate error */
117 growing_buffer* method_name = buffer_init(64);
119 // Generic search thingy
120 buffer_add(method_name, MODULENAME);
121 buffer_add(method_name, ".json_query");
122 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
123 "doJSONSearch", "", 1, OSRF_METHOD_STREAMING );
126 // first we register all the transaction and savepoint methods
127 buffer_reset(method_name);
128 OSRF_BUFFER_ADD(method_name, MODULENAME);
129 OSRF_BUFFER_ADD(method_name, ".transaction.begin");
130 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
131 "beginTransaction", "", 0, 0 );
133 buffer_reset(method_name);
134 OSRF_BUFFER_ADD(method_name, MODULENAME);
135 OSRF_BUFFER_ADD(method_name, ".transaction.commit");
136 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
137 "commitTransaction", "", 0, 0 );
139 buffer_reset(method_name);
140 OSRF_BUFFER_ADD(method_name, MODULENAME);
141 OSRF_BUFFER_ADD(method_name, ".transaction.rollback");
142 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
143 "rollbackTransaction", "", 0, 0 );
145 buffer_reset(method_name);
146 OSRF_BUFFER_ADD(method_name, MODULENAME);
147 OSRF_BUFFER_ADD(method_name, ".savepoint.set");
148 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
149 "setSavepoint", "", 1, 0 );
151 buffer_reset(method_name);
152 OSRF_BUFFER_ADD(method_name, MODULENAME);
153 OSRF_BUFFER_ADD(method_name, ".savepoint.release");
154 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
155 "releaseSavepoint", "", 1, 0 );
157 buffer_reset(method_name);
158 OSRF_BUFFER_ADD(method_name, MODULENAME);
159 OSRF_BUFFER_ADD(method_name, ".savepoint.rollback");
160 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
161 "rollbackSavepoint", "", 1, 0 );
163 buffer_free(method_name);
165 static const char* global_method[] = {
173 const int global_method_count
174 = sizeof( global_method ) / sizeof ( global_method[0] );
178 osrfStringArray* classes = osrfHashKeys( oilsIDL() );
179 osrfLogDebug(OSRF_LOG_MARK, "%d classes loaded", classes->size );
180 osrfLogDebug(OSRF_LOG_MARK,
181 "At least %d methods will be generated", classes->size * global_method_count);
183 while ( (classname = osrfStringArrayGetString(classes, c_index++)) ) {
184 osrfLogInfo(OSRF_LOG_MARK, "Generating class methods for %s", classname);
186 osrfHash* idlClass = osrfHashGet(oilsIDL(), classname);
188 if (!osrfStringArrayContains( osrfHashGet(idlClass, "controller"), MODULENAME )) {
189 osrfLogInfo(OSRF_LOG_MARK, "%s is not listed as a controller for %s, moving on", MODULENAME, classname);
193 if ( str_is_true( osrfHashGet(idlClass, "virtual") ) ) {
194 osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
198 // Look up some other attributes of the current class
199 const char* idlClass_fieldmapper = osrfHashGet(idlClass, "fieldmapper");
200 const char* readonly = osrfHashGet(idlClass, "readonly");
202 osrfHash* idlClass_permacrud = osrfHashGet(idlClass, "permacrud");
206 for( i = 0; i < global_method_count; ++i ) {
207 const char* method_type = global_method[ i ];
208 osrfLogDebug(OSRF_LOG_MARK,
209 "Using files to build %s class methods for %s", method_type, classname);
211 if (!idlClass_fieldmapper) continue;
214 if (!idlClass_permacrud) continue;
216 const char* tmp_method = method_type;
217 if ( *tmp_method == 'i' || *tmp_method == 's') {
218 tmp_method = "retrieve";
220 if (!osrfHashGet( idlClass_permacrud, tmp_method )) continue;
223 if ( str_is_true( readonly ) &&
224 ( *method_type == 'c' || *method_type == 'u' || *method_type == 'd')
227 osrfHash* method_meta = osrfNewHash();
228 osrfHashSet(method_meta, idlClass, "class");
230 method_name = buffer_init(64);
232 buffer_fadd(method_name, "%s.%s.%s", MODULENAME, method_type, classname);
236 char* _fm = strdup( idlClass_fieldmapper );
237 part = strtok_r(_fm, ":", &st_tmp);
239 buffer_fadd(method_name, "%s.direct.%s", MODULENAME, part);
241 while ((part = strtok_r(NULL, ":", &st_tmp))) {
242 OSRF_BUFFER_ADD_CHAR(method_name, '.');
243 OSRF_BUFFER_ADD(method_name, part);
245 OSRF_BUFFER_ADD_CHAR(method_name, '.');
246 OSRF_BUFFER_ADD(method_name, method_type);
250 char* method = buffer_release(method_name);
252 osrfHashSet( method_meta, method, "methodname" );
253 osrfHashSet( method_meta, strdup(method_type), "methodtype" );
256 if (*method_type == 'i' || *method_type == 's') {
257 flags = flags | OSRF_METHOD_STREAMING;
260 osrfAppRegisterExtendedMethod(
263 "dispatchCRUDMethod",
277 static char* getSourceDefinition( osrfHash* class ) {
279 char* tabledef = osrfHashGet(class, "tablename");
282 tabledef = strdup(tabledef);
284 tabledef = osrfHashGet(class, "source_definition");
286 growing_buffer* tablebuf = buffer_init(128);
287 buffer_fadd( tablebuf, "(%s)", tabledef );
288 tabledef = buffer_release(tablebuf);
290 const char* classname = osrfHashGet( class, "classname" );
295 "%s ERROR No tablename or source_definition for class \"%s\"",
306 * Connects to the database
308 int osrfAppChildInit() {
310 osrfLogDebug(OSRF_LOG_MARK, "Attempting to initialize libdbi...");
311 dbi_initialize(NULL);
312 osrfLogDebug(OSRF_LOG_MARK, "... libdbi initialized.");
314 char* driver = osrf_settings_host_value("/apps/%s/app_settings/driver", MODULENAME);
315 char* user = osrf_settings_host_value("/apps/%s/app_settings/database/user", MODULENAME);
316 char* host = osrf_settings_host_value("/apps/%s/app_settings/database/host", MODULENAME);
317 char* port = osrf_settings_host_value("/apps/%s/app_settings/database/port", MODULENAME);
318 char* db = osrf_settings_host_value("/apps/%s/app_settings/database/db", MODULENAME);
319 char* pw = osrf_settings_host_value("/apps/%s/app_settings/database/pw", MODULENAME);
320 char* md = osrf_settings_host_value("/apps/%s/app_settings/max_query_recursion", MODULENAME);
322 osrfLogDebug(OSRF_LOG_MARK, "Attempting to load the database driver [%s]...", driver);
323 writehandle = dbi_conn_new(driver);
326 osrfLogError(OSRF_LOG_MARK, "Error loading database driver [%s]", driver);
329 osrfLogDebug(OSRF_LOG_MARK, "Database driver [%s] seems OK", driver);
331 osrfLogInfo(OSRF_LOG_MARK, "%s connecting to database. host=%s, "
332 "port=%s, user=%s, pw=%s, db=%s", MODULENAME, host, port, user, pw, db );
334 if(host) dbi_conn_set_option(writehandle, "host", host );
335 if(port) dbi_conn_set_option_numeric( writehandle, "port", atoi(port) );
336 if(user) dbi_conn_set_option(writehandle, "username", user);
337 if(pw) dbi_conn_set_option(writehandle, "password", pw );
338 if(db) dbi_conn_set_option(writehandle, "dbname", db );
340 if(md) max_flesh_depth = atoi(md);
341 if(max_flesh_depth < 0) max_flesh_depth = 1;
342 if(max_flesh_depth > 1000) max_flesh_depth = 1000;
351 if (dbi_conn_connect(writehandle) < 0) {
353 if (dbi_conn_connect(writehandle) < 0) {
354 dbi_conn_error(writehandle, &err);
355 osrfLogError( OSRF_LOG_MARK, "Error connecting to database: %s", err);
360 osrfLogInfo(OSRF_LOG_MARK, "%s successfully connected to the database", MODULENAME);
366 osrfStringArray* classes = osrfHashKeys( oilsIDL() );
368 while ( (classname = osrfStringArrayGetString(classes, i++)) ) {
369 osrfHash* class = osrfHashGet( oilsIDL(), classname );
370 osrfHash* fields = osrfHashGet( class, "fields" );
372 if( str_is_true( osrfHashGet(class, "virtual") ) ) {
373 osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
377 char* tabledef = getSourceDefinition(class);
379 tabledef = strdup( "(null)" );
381 growing_buffer* sql_buf = buffer_init(32);
382 buffer_fadd( sql_buf, "SELECT * FROM %s AS x WHERE 1=0;", tabledef );
386 char* sql = buffer_release(sql_buf);
387 osrfLogDebug(OSRF_LOG_MARK, "%s Investigatory SQL = %s", MODULENAME, sql);
389 dbi_result result = dbi_conn_query(writehandle, sql);
395 const char* columnName;
397 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
399 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
401 /* fetch the fieldmapper index */
402 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
404 osrfLogDebug(OSRF_LOG_MARK, "Found [%s] in IDL hash...", (char*)columnName);
406 /* determine the field type and storage attributes */
407 type = dbi_result_get_field_type(result, columnName);
408 attr = dbi_result_get_field_attribs(result, columnName);
412 case DBI_TYPE_INTEGER :
414 if ( !osrfHashGet(_f, "primitive") )
415 osrfHashSet(_f,"number", "primitive");
417 if( attr & DBI_INTEGER_SIZE8 )
418 osrfHashSet(_f,"INT8", "datatype");
420 osrfHashSet(_f,"INT", "datatype");
423 case DBI_TYPE_DECIMAL :
424 if ( !osrfHashGet(_f, "primitive") )
425 osrfHashSet(_f,"number", "primitive");
427 osrfHashSet(_f,"NUMERIC", "datatype");
430 case DBI_TYPE_STRING :
431 if ( !osrfHashGet(_f, "primitive") )
432 osrfHashSet(_f,"string", "primitive");
433 osrfHashSet(_f,"TEXT", "datatype");
436 case DBI_TYPE_DATETIME :
437 if ( !osrfHashGet(_f, "primitive") )
438 osrfHashSet(_f,"string", "primitive");
440 osrfHashSet(_f,"TIMESTAMP", "datatype");
443 case DBI_TYPE_BINARY :
444 if ( !osrfHashGet(_f, "primitive") )
445 osrfHashSet(_f,"string", "primitive");
447 osrfHashSet(_f,"BYTEA", "datatype");
452 "Setting [%s] to primitive [%s] and datatype [%s]...",
454 osrfHashGet(_f, "primitive"),
455 osrfHashGet(_f, "datatype")
459 dbi_result_free(result);
461 osrfLogDebug(OSRF_LOG_MARK, "No data found for class [%s]...", (char*)classname);
465 osrfStringArrayFree(classes);
471 This function is a sleazy hack intended *only* for testing and
472 debugging. Any real server process should initialize the
473 database connection by calling osrfAppChildInit().
475 void set_cstore_dbi_conn( dbi_conn conn ) {
476 dbhandle = writehandle = conn;
479 void userDataFree( void* blob ) {
480 osrfHashFree( (osrfHash*)blob );
484 static void sessionDataFree( char* key, void* item ) {
485 if (!(strcmp(key,"xact_id"))) {
487 dbi_conn_query(writehandle, "ROLLBACK;");
494 int beginTransaction ( osrfMethodContext* ctx ) {
495 if(osrfMethodVerifyContext( ctx )) {
496 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
501 jsonObject* user = verifyUserPCRUD( ctx );
502 if (!user) return -1;
503 jsonObjectFree(user);
506 dbi_result result = dbi_conn_query(writehandle, "START TRANSACTION;");
508 osrfLogError(OSRF_LOG_MARK, "%s: Error starting transaction", MODULENAME );
509 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error starting transaction" );
512 jsonObject* ret = jsonNewObject(ctx->session->session_id);
513 osrfAppRespondComplete( ctx, ret );
516 if (!ctx->session->userData) {
517 ctx->session->userData = osrfNewHash();
518 osrfHashSetCallback((osrfHash*)ctx->session->userData, &sessionDataFree);
521 osrfHashSet( (osrfHash*)ctx->session->userData, strdup( ctx->session->session_id ), "xact_id" );
522 ctx->session->userDataFree = &userDataFree;
528 int setSavepoint ( osrfMethodContext* ctx ) {
529 if(osrfMethodVerifyContext( ctx )) {
530 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
537 jsonObject* user = verifyUserPCRUD( ctx );
538 if (!user) return -1;
539 jsonObjectFree(user);
542 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
543 osrfAppSessionStatus(
545 OSRF_STATUS_INTERNALSERVERERROR,
546 "osrfMethodException",
548 "No active transaction -- required for savepoints"
553 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
555 dbi_result result = dbi_conn_queryf(writehandle, "SAVEPOINT \"%s\";", spName);
559 "%s: Error creating savepoint %s in transaction %s",
562 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
564 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error creating savepoint" );
568 jsonObject* ret = jsonNewObject(spName);
569 osrfAppRespondComplete( ctx, ret );
576 int releaseSavepoint ( osrfMethodContext* ctx ) {
577 if(osrfMethodVerifyContext( ctx )) {
578 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
585 jsonObject* user = verifyUserPCRUD( ctx );
586 if (!user) return -1;
587 jsonObjectFree(user);
590 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
591 osrfAppSessionStatus(
593 OSRF_STATUS_INTERNALSERVERERROR,
594 "osrfMethodException",
596 "No active transaction -- required for savepoints"
601 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
603 dbi_result result = dbi_conn_queryf(writehandle, "RELEASE SAVEPOINT \"%s\";", spName);
607 "%s: Error releasing savepoint %s in transaction %s",
610 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
612 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error releasing savepoint" );
616 jsonObject* ret = jsonNewObject(spName);
617 osrfAppRespondComplete( ctx, ret );
624 int rollbackSavepoint ( osrfMethodContext* ctx ) {
625 if(osrfMethodVerifyContext( ctx )) {
626 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
633 jsonObject* user = verifyUserPCRUD( ctx );
634 if (!user) return -1;
635 jsonObjectFree(user);
638 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
639 osrfAppSessionStatus(
641 OSRF_STATUS_INTERNALSERVERERROR,
642 "osrfMethodException",
644 "No active transaction -- required for savepoints"
649 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
651 dbi_result result = dbi_conn_queryf(writehandle, "ROLLBACK TO SAVEPOINT \"%s\";", spName);
655 "%s: Error rolling back savepoint %s in transaction %s",
658 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
660 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back savepoint" );
664 jsonObject* ret = jsonNewObject(spName);
665 osrfAppRespondComplete( ctx, ret );
672 int commitTransaction ( osrfMethodContext* ctx ) {
673 if(osrfMethodVerifyContext( ctx )) {
674 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
679 jsonObject* user = verifyUserPCRUD( ctx );
680 if (!user) return -1;
681 jsonObjectFree(user);
684 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
685 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to commit" );
689 dbi_result result = dbi_conn_query(writehandle, "COMMIT;");
691 osrfLogError(OSRF_LOG_MARK, "%s: Error committing transaction", MODULENAME );
692 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error committing transaction" );
695 osrfHashRemove(ctx->session->userData, "xact_id");
696 jsonObject* ret = jsonNewObject(ctx->session->session_id);
697 osrfAppRespondComplete( ctx, ret );
703 int rollbackTransaction ( osrfMethodContext* ctx ) {
704 if(osrfMethodVerifyContext( ctx )) {
705 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
710 jsonObject* user = verifyUserPCRUD( ctx );
711 if (!user) return -1;
712 jsonObjectFree(user);
715 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
716 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to roll back" );
720 dbi_result result = dbi_conn_query(writehandle, "ROLLBACK;");
722 osrfLogError(OSRF_LOG_MARK, "%s: Error rolling back transaction", MODULENAME );
723 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back transaction" );
726 osrfHashRemove(ctx->session->userData, "xact_id");
727 jsonObject* ret = jsonNewObject(ctx->session->session_id);
728 osrfAppRespondComplete( ctx, ret );
734 int dispatchCRUDMethod ( osrfMethodContext* ctx ) {
735 if(osrfMethodVerifyContext( ctx )) {
736 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
740 osrfHash* meta = (osrfHash*) ctx->method->userData;
741 osrfHash* class_obj = osrfHashGet( meta, "class" );
745 const char* methodtype = osrfHashGet(meta, "methodtype");
746 jsonObject * obj = NULL;
748 if (!strcmp(methodtype, "create")) {
749 obj = doCreate(ctx, &err);
750 osrfAppRespondComplete( ctx, obj );
752 else if (!strcmp(methodtype, "retrieve")) {
753 obj = doRetrieve(ctx, &err);
754 osrfAppRespondComplete( ctx, obj );
756 else if (!strcmp(methodtype, "update")) {
757 obj = doUpdate(ctx, &err);
758 osrfAppRespondComplete( ctx, obj );
760 else if (!strcmp(methodtype, "delete")) {
761 obj = doDelete(ctx, &err);
762 osrfAppRespondComplete( ctx, obj );
764 else if (!strcmp(methodtype, "search")) {
766 jsonObject* _p = jsonObjectClone( ctx->params );
769 _p = jsonParseString("[]");
770 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 1)));
771 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 2)));
774 obj = doFieldmapperSearch(ctx, class_obj, _p, &err);
780 jsonIterator* itr = jsonNewIterator( obj );
781 while ((cur = jsonIteratorNext( itr ))) {
783 if(!verifyObjectPCRUD(ctx, cur)) continue;
785 osrfAppRespond( ctx, cur );
787 jsonIteratorFree(itr);
788 osrfAppRespondComplete( ctx, NULL );
790 } else if (!strcmp(methodtype, "id_list")) {
792 jsonObject* _p = jsonObjectClone( ctx->params );
795 _p = jsonParseString("[]");
796 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 1)));
797 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 2)));
800 if (jsonObjectGetIndex( _p, 1 )) {
801 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "select" );
802 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "no_i18n" );
803 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh" );
804 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh_columns" );
806 jsonObjectSetIndex( _p, 1, jsonNewObjectType(JSON_HASH) );
809 jsonObjectSetKey( jsonObjectGetIndex( _p, 1 ), "no_i18n", jsonNewBoolObject( 1 ) );
812 jsonObjectGetIndex( _p, 1 ),
815 "{ \"%s\":[\"%s\"] }",
816 osrfHashGet( class_obj, "classname" ),
817 osrfHashGet( class_obj, "primarykey" )
821 obj = doFieldmapperSearch(ctx, class_obj, _p, &err);
827 jsonIterator* itr = jsonNewIterator( obj );
828 while ((cur = jsonIteratorNext( itr ))) {
830 if(!verifyObjectPCRUD(ctx, cur)) continue;
834 oilsFMGetObject( cur, osrfHashGet( class_obj, "primarykey" ) )
837 jsonIteratorFree(itr);
838 osrfAppRespondComplete( ctx, NULL );
841 osrfAppRespondComplete( ctx, obj );
849 static int verifyObjectClass ( osrfMethodContext* ctx, const jsonObject* param ) {
852 osrfHash* meta = (osrfHash*) ctx->method->userData;
853 osrfHash* class = osrfHashGet( meta, "class" );
855 if (!param->classname || (strcmp( osrfHashGet(class, "classname"), param->classname ))) {
857 growing_buffer* msg = buffer_init(128);
860 "%s: %s method for type %s was passed a %s",
862 osrfHashGet(meta, "methodtype"),
863 osrfHashGet(class, "classname"),
867 char* m = buffer_release(msg);
868 osrfAppSessionStatus( ctx->session, OSRF_STATUS_BADREQUEST, "osrfMethodException", ctx->request, m );
876 ret = verifyObjectPCRUD( ctx, param );
884 static jsonObject* verifyUserPCRUD( osrfMethodContext* ctx ) {
885 char* auth = jsonObjectToSimpleString( jsonObjectGetIndex( ctx->params, 0 ) );
886 jsonObject* auth_object = jsonNewObject(auth);
887 jsonObject* user = oilsUtilsQuickReq("open-ils.auth","open-ils.auth.session.retrieve", auth_object);
888 jsonObjectFree(auth_object);
890 if (!user->classname || strcmp(user->classname, "au")) {
892 growing_buffer* msg = buffer_init(128);
895 "%s: permacrud received a bad auth token: %s",
900 char* m = buffer_release(msg);
901 osrfAppSessionStatus( ctx->session, OSRF_STATUS_UNAUTHORIZED, "osrfMethodException", ctx->request, m );
904 jsonObjectFree(user);
913 static int verifyObjectPCRUD ( osrfMethodContext* ctx, const jsonObject* obj ) {
915 dbhandle = writehandle;
917 osrfHash* meta = (osrfHash*) ctx->method->userData;
918 osrfHash* class = osrfHashGet( meta, "class" );
919 char* method_type = strdup( osrfHashGet(meta, "methodtype") );
922 if ( ( *method_type == 's' || *method_type == 'i' ) ) {
924 method_type = strdup("retrieve"); // search and id_list are equivelant to retrieve for this
925 } else if ( *method_type == 'u' || *method_type == 'd' ) {
926 fetch = 1; // MUST go to the db for the object for update and delete
929 osrfHash* pcrud = osrfHashGet( osrfHashGet(class, "permacrud"), method_type );
933 // No permacrud for this method type on this class
935 growing_buffer* msg = buffer_init(128);
938 "%s: %s on class %s has no permacrud IDL entry",
940 osrfHashGet(meta, "methodtype"),
941 osrfHashGet(class, "classname")
944 char* m = buffer_release(msg);
945 osrfAppSessionStatus( ctx->session, OSRF_STATUS_FORBIDDEN, "osrfMethodException", ctx->request, m );
952 jsonObject* user = verifyUserPCRUD( ctx );
955 int userid = atoi( oilsFMGetString( user, "id" ) );
956 jsonObjectFree(user);
958 osrfStringArray* permission = osrfHashGet(pcrud, "permission");
959 osrfStringArray* local_context = osrfHashGet(pcrud, "local_context");
960 osrfHash* foreign_context = osrfHashGet(pcrud, "foreign_context");
962 osrfStringArray* context_org_array = osrfNewStringArray(1);
965 char* pkey_value = NULL;
966 if ( str_is_true( osrfHashGet(pcrud, "global_required") ) ) {
967 osrfLogDebug( OSRF_LOG_MARK, "global-level permissions required, fetching top of the org tree" );
969 // check for perm at top of org tree
970 jsonObject* _tmp_params = jsonParseString("[{\"parent_ou\":null}]");
971 jsonObject* _list = doFieldmapperSearch(ctx, osrfHashGet( oilsIDL(), "aou" ), _tmp_params, &err);
973 jsonObject* _tree_top = jsonObjectGetIndex(_list, 0);
976 jsonObjectFree(_tmp_params);
977 jsonObjectFree(_list);
979 growing_buffer* msg = buffer_init(128);
980 OSRF_BUFFER_ADD( msg, MODULENAME );
981 OSRF_BUFFER_ADD( msg,
982 ": Internal error, could not find the top of the org tree (parent_ou = NULL)" );
984 char* m = buffer_release(msg);
985 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, m );
991 osrfStringArrayAdd( context_org_array, oilsFMGetString( _tree_top, "id" ) );
992 osrfLogDebug( OSRF_LOG_MARK, "top of the org tree is %s", osrfStringArrayGetString(context_org_array, 0) );
994 jsonObjectFree(_tmp_params);
995 jsonObjectFree(_list);
998 osrfLogDebug( OSRF_LOG_MARK, "global-level permissions not required, fetching context org ids" );
999 char* pkey = osrfHashGet(class, "primarykey");
1000 jsonObject *param = NULL;
1002 if (obj->classname) {
1003 pkey_value = oilsFMGetString( obj, pkey );
1004 if (!fetch) param = jsonObjectClone(obj);
1005 osrfLogDebug( OSRF_LOG_MARK, "Object supplied, using primary key value of %s", pkey_value );
1007 pkey_value = jsonObjectToSimpleString( obj );
1009 osrfLogDebug( OSRF_LOG_MARK, "Object not supplied, using primary key value of %s and retrieving from the database", pkey_value );
1013 jsonObject* _tmp_params = jsonParseStringFmt("[{\"%s\":\"%s\"}]", pkey, pkey_value);
1014 jsonObject* _list = doFieldmapperSearch(
1021 param = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1023 jsonObjectFree(_tmp_params);
1024 jsonObjectFree(_list);
1028 osrfLogDebug( OSRF_LOG_MARK, "Object not found in the database with primary key %s of %s", pkey, pkey_value );
1030 growing_buffer* msg = buffer_init(128);
1033 "%s: no object found with primary key %s of %s",
1039 char* m = buffer_release(msg);
1040 osrfAppSessionStatus(
1042 OSRF_STATUS_INTERNALSERVERERROR,
1043 "osrfMethodException",
1049 if (pkey_value) free(pkey_value);
1054 if (local_context->size > 0) {
1055 osrfLogDebug( OSRF_LOG_MARK, "%d class-local context field(s) specified", local_context->size);
1057 char* lcontext = NULL;
1058 while ( (lcontext = osrfStringArrayGetString(local_context, i++)) ) {
1059 osrfStringArrayAdd( context_org_array, oilsFMGetString( param, lcontext ) );
1062 "adding class-local field %s (value: %s) to the context org list",
1064 osrfStringArrayGetString(context_org_array, context_org_array->size - 1)
1069 osrfStringArray* class_list;
1071 if (foreign_context) {
1072 class_list = osrfHashKeys( foreign_context );
1073 osrfLogDebug( OSRF_LOG_MARK, "%d foreign context classes(s) specified", class_list->size);
1075 if (class_list->size > 0) {
1078 char* class_name = NULL;
1079 while ( (class_name = osrfStringArrayGetString(class_list, i++)) ) {
1080 osrfHash* fcontext = osrfHashGet(foreign_context, class_name);
1084 "%d foreign context fields(s) specified for class %s",
1085 ((osrfStringArray*)osrfHashGet(fcontext,"context"))->size,
1089 char* foreign_pkey = osrfHashGet(fcontext, "field");
1090 char* foreign_pkey_value = oilsFMGetString(param, osrfHashGet(fcontext, "fkey"));
1092 jsonObject* _tmp_params = jsonParseStringFmt(
1093 "[{\"%s\":\"%s\"}]",
1098 jsonObject* _list = doFieldmapperSearch(
1100 osrfHashGet( oilsIDL(), class_name ),
1105 jsonObject* _fparam = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1106 jsonObjectFree(_tmp_params);
1107 jsonObjectFree(_list);
1109 osrfStringArray* jump_list = osrfHashGet(fcontext, "jump");
1111 if (_fparam && jump_list) {
1114 while ( (flink = osrfStringArrayGetString(jump_list, k++)) && _fparam ) {
1115 free(foreign_pkey_value);
1117 osrfHash* foreign_link_hash = oilsIDLFindPath( "/%s/links/%s", _fparam->classname, flink );
1119 foreign_pkey_value = oilsFMGetString(_fparam, flink);
1120 foreign_pkey = osrfHashGet( foreign_link_hash, "key" );
1122 _tmp_params = jsonParseStringFmt(
1123 "[{\"%s\":\"%s\"}]",
1128 _list = doFieldmapperSearch(
1130 osrfHashGet( oilsIDL(), osrfHashGet( foreign_link_hash, "class" ) ),
1135 _fparam = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1136 jsonObjectFree(_tmp_params);
1137 jsonObjectFree(_list);
1144 growing_buffer* msg = buffer_init(128);
1147 "%s: no object found with primary key %s of %s",
1153 char* m = buffer_release(msg);
1154 osrfAppSessionStatus(
1156 OSRF_STATUS_INTERNALSERVERERROR,
1157 "osrfMethodException",
1163 osrfStringArrayFree(class_list);
1164 free(foreign_pkey_value);
1165 jsonObjectFree(param);
1170 free(foreign_pkey_value);
1173 char* foreign_field = NULL;
1174 while ( (foreign_field = osrfStringArrayGetString(osrfHashGet(fcontext,"context"), j++)) ) {
1175 osrfStringArrayAdd( context_org_array, oilsFMGetString( _fparam, foreign_field ) );
1178 "adding foreign class %s field %s (value: %s) to the context org list",
1181 osrfStringArrayGetString(context_org_array, context_org_array->size - 1)
1185 jsonObjectFree(_fparam);
1188 osrfStringArrayFree(class_list);
1192 jsonObjectFree(param);
1195 char* context_org = NULL;
1199 if (permission->size == 0) {
1200 osrfLogDebug( OSRF_LOG_MARK, "No permission specified for this action, passing through" );
1205 while ( (perm = osrfStringArrayGetString(permission, i++)) ) {
1207 while ( (context_org = osrfStringArrayGetString(context_org_array, j++)) ) {
1213 "Checking object permission [%s] for user %d on object %s (class %s) at org %d",
1217 osrfHashGet(class, "classname"),
1221 result = dbi_conn_queryf(
1223 "SELECT permission.usr_has_object_perm(%d, '%s', '%s', '%s', %d) AS has_perm;",
1226 osrfHashGet(class, "classname"),
1234 "Recieved a result for object permission [%s] for user %d on object %s (class %s) at org %d",
1238 osrfHashGet(class, "classname"),
1242 if (dbi_result_first_row(result)) {
1243 jsonObject* return_val = oilsMakeJSONFromResult( result );
1244 char* has_perm = jsonObjectToSimpleString( jsonObjectGetKeyConst(return_val, "has_perm") );
1248 "Status of object permission [%s] for user %d on object %s (class %s) at org %d is %s",
1252 osrfHashGet(class, "classname"),
1257 if ( *has_perm == 't' ) OK = 1;
1259 jsonObjectFree(return_val);
1262 dbi_result_free(result);
1267 osrfLogDebug( OSRF_LOG_MARK, "Checking non-object permission [%s] for user %d at org %d", perm, userid, atoi(context_org) );
1268 result = dbi_conn_queryf(
1270 "SELECT permission.usr_has_perm(%d, '%s', %d) AS has_perm;",
1277 osrfLogDebug( OSRF_LOG_MARK, "Received a result for permission [%s] for user %d at org %d", perm, userid, atoi(context_org) );
1278 if (dbi_result_first_row(result)) {
1279 jsonObject* return_val = oilsMakeJSONFromResult( result );
1280 char* has_perm = jsonObjectToSimpleString( jsonObjectGetKeyConst(return_val, "has_perm") );
1281 osrfLogDebug( OSRF_LOG_MARK, "Status of permission [%s] for user %d at org %d is [%s]", perm, userid, atoi(context_org), has_perm );
1282 if ( *has_perm == 't' ) OK = 1;
1284 jsonObjectFree(return_val);
1287 dbi_result_free(result);
1295 if (pkey_value) free(pkey_value);
1296 osrfStringArrayFree(context_org_array);
1303 static jsonObject* doCreate(osrfMethodContext* ctx, int* err ) {
1305 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1307 jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
1308 jsonObject* options = jsonObjectGetIndex( ctx->params, 2 );
1310 jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
1311 jsonObject* options = jsonObjectGetIndex( ctx->params, 1 );
1314 if (!verifyObjectClass(ctx, target)) {
1319 osrfLogDebug( OSRF_LOG_MARK, "Object seems to be of the correct type" );
1321 if (!ctx->session || !ctx->session->userData || !osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
1322 osrfLogError( OSRF_LOG_MARK, "No active transaction -- required for CREATE" );
1324 osrfAppSessionStatus(
1326 OSRF_STATUS_BADREQUEST,
1327 "osrfMethodException",
1329 "No active transaction -- required for CREATE"
1335 // The following test is harmless but redundant. If a class is
1336 // readonly, we don't register a create method for it.
1337 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
1338 osrfAppSessionStatus(
1340 OSRF_STATUS_BADREQUEST,
1341 "osrfMethodException",
1343 "Cannot INSERT readonly class"
1350 char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
1352 // Set the last_xact_id
1353 int index = oilsIDL_ntop( target->classname, "last_xact_id" );
1355 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
1356 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
1359 osrfLogDebug( OSRF_LOG_MARK, "There is a transaction running..." );
1361 dbhandle = writehandle;
1363 osrfHash* fields = osrfHashGet(meta, "fields");
1364 char* pkey = osrfHashGet(meta, "primarykey");
1365 char* seq = osrfHashGet(meta, "sequence");
1367 growing_buffer* table_buf = buffer_init(128);
1368 growing_buffer* col_buf = buffer_init(128);
1369 growing_buffer* val_buf = buffer_init(128);
1371 OSRF_BUFFER_ADD(table_buf, "INSERT INTO ");
1372 OSRF_BUFFER_ADD(table_buf, osrfHashGet(meta, "tablename"));
1373 OSRF_BUFFER_ADD_CHAR( col_buf, '(' );
1374 buffer_add(val_buf,"VALUES (");
1380 osrfStringArray* field_list = osrfHashKeys( fields );
1381 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
1383 osrfHash* field = osrfHashGet( fields, field_name );
1385 if( str_is_true( osrfHashGet( field, "virtual" ) ) )
1388 const jsonObject* field_object = oilsFMGetObject( target, field_name );
1391 if (field_object && field_object->classname) {
1392 value = oilsFMGetString(
1394 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
1397 value = jsonObjectToSimpleString( field_object );
1404 OSRF_BUFFER_ADD_CHAR( col_buf, ',' );
1405 OSRF_BUFFER_ADD_CHAR( val_buf, ',' );
1408 buffer_add(col_buf, field_name);
1410 if (!field_object || field_object->type == JSON_NULL) {
1411 buffer_add( val_buf, "DEFAULT" );
1413 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1414 if ( !strcmp(osrfHashGet(field, "datatype"), "INT8") ) {
1415 buffer_fadd( val_buf, "%lld", atoll(value) );
1417 } else if ( !strcmp(osrfHashGet(field, "datatype"), "INT") ) {
1418 buffer_fadd( val_buf, "%d", atoi(value) );
1420 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
1421 buffer_fadd( val_buf, "%f", atof(value) );
1424 if ( dbi_conn_quote_string(writehandle, &value) ) {
1425 OSRF_BUFFER_ADD( val_buf, value );
1428 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
1429 osrfAppSessionStatus(
1431 OSRF_STATUS_INTERNALSERVERERROR,
1432 "osrfMethodException",
1434 "Error quoting string -- please see the error log for more details"
1437 buffer_free(table_buf);
1438 buffer_free(col_buf);
1439 buffer_free(val_buf);
1450 OSRF_BUFFER_ADD_CHAR( col_buf, ')' );
1451 OSRF_BUFFER_ADD_CHAR( val_buf, ')' );
1453 char* table_str = buffer_release(table_buf);
1454 char* col_str = buffer_release(col_buf);
1455 char* val_str = buffer_release(val_buf);
1456 growing_buffer* sql = buffer_init(128);
1457 buffer_fadd( sql, "%s %s %s;", table_str, col_str, val_str );
1462 char* query = buffer_release(sql);
1464 osrfLogDebug(OSRF_LOG_MARK, "%s: Insert SQL [%s]", MODULENAME, query);
1467 dbi_result result = dbi_conn_query(writehandle, query);
1469 jsonObject* obj = NULL;
1472 obj = jsonNewObject(NULL);
1475 "%s ERROR inserting %s object using query [%s]",
1477 osrfHashGet(meta, "fieldmapper"),
1480 osrfAppSessionStatus(
1482 OSRF_STATUS_INTERNALSERVERERROR,
1483 "osrfMethodException",
1485 "INSERT error -- please see the error log for more details"
1490 char* id = oilsFMGetString(target, pkey);
1492 unsigned long long new_id = dbi_conn_sequence_last(writehandle, seq);
1493 growing_buffer* _id = buffer_init(10);
1494 buffer_fadd(_id, "%lld", new_id);
1495 id = buffer_release(_id);
1498 // Find quietness specification, if present
1499 char* quiet_str = NULL;
1501 const jsonObject* quiet_obj = jsonObjectGetKeyConst( options, "quiet" );
1503 quiet_str = jsonObjectToSimpleString( quiet_obj );
1506 if( str_is_true( quiet_str ) ) { // if quietness is specified
1507 obj = jsonNewObject(id);
1511 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
1512 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH));
1515 jsonObjectGetIndex(fake_params, 0),
1520 jsonObject* list = doFieldmapperSearch( ctx,meta, fake_params, err);
1523 jsonObjectFree( fake_params );
1526 obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
1529 jsonObjectFree( list );
1530 jsonObjectFree( fake_params );
1533 if(quiet_str) free(quiet_str);
1544 static jsonObject* doRetrieve(osrfMethodContext* ctx, int* err ) {
1554 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1556 char* id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, id_pos));
1557 jsonObject* order_hash = jsonObjectGetIndex(ctx->params, order_pos);
1561 "%s retrieving %s object with primary key value of %s",
1563 osrfHashGet(meta, "fieldmapper"),
1568 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
1569 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH));
1572 jsonObjectGetIndex(fake_params, 0),
1573 osrfHashGet(meta, "primarykey"),
1574 jsonObjectClone(jsonObjectGetIndex(ctx->params, id_pos))
1578 if (order_hash) jsonObjectPush(fake_params, jsonObjectClone(order_hash) );
1580 jsonObject* list = doFieldmapperSearch( ctx,meta, fake_params, err);
1583 jsonObjectFree( fake_params );
1587 jsonObject* obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
1589 jsonObjectFree( list );
1590 jsonObjectFree( fake_params );
1593 if(!verifyObjectPCRUD(ctx, obj)) {
1594 jsonObjectFree(obj);
1597 growing_buffer* msg = buffer_init(128);
1598 OSRF_BUFFER_ADD( msg, MODULENAME );
1599 OSRF_BUFFER_ADD( msg, ": Insufficient permissions to retrieve object" );
1601 char* m = buffer_release(msg);
1602 osrfAppSessionStatus( ctx->session, OSRF_STATUS_NOTALLOWED, "osrfMethodException", ctx->request, m );
1613 static char* jsonNumberToDBString ( osrfHash* field, const jsonObject* value ) {
1614 growing_buffer* val_buf = buffer_init(32);
1616 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
1617 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%ld", (long)jsonObjectGetNumber(value) );
1619 char* val_str = jsonObjectToSimpleString(value);
1620 buffer_fadd( val_buf, "%ld", atol(val_str) );
1624 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
1625 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%f", jsonObjectGetNumber(value) );
1627 char* val_str = jsonObjectToSimpleString(value);
1628 buffer_fadd( val_buf, "%f", atof(val_str) );
1633 return buffer_release(val_buf);
1636 static char* searchINPredicate (const char* class, osrfHash* field,
1637 jsonObject* node, const char* op, osrfMethodContext* ctx ) {
1638 growing_buffer* sql_buf = buffer_init(32);
1644 osrfHashGet(field, "name")
1648 buffer_add(sql_buf, "IN (");
1649 } else if (!(strcasecmp(op,"not in"))) {
1650 buffer_add(sql_buf, "NOT IN (");
1652 buffer_add(sql_buf, "IN (");
1655 if (node->type == JSON_HASH) {
1656 // subquery predicate
1657 char* subpred = SELECT(
1659 jsonObjectGetKey( node, "select" ),
1660 jsonObjectGetKey( node, "from" ),
1661 jsonObjectGetKey( node, "where" ),
1662 jsonObjectGetKey( node, "having" ),
1663 jsonObjectGetKey( node, "order_by" ),
1664 jsonObjectGetKey( node, "limit" ),
1665 jsonObjectGetKey( node, "offset" ),
1669 buffer_add(sql_buf, subpred);
1672 } else if (node->type == JSON_ARRAY) {
1673 // litteral value list
1674 int in_item_index = 0;
1675 int in_item_first = 1;
1676 jsonObject* in_item;
1677 while ( (in_item = jsonObjectGetIndex(node, in_item_index++)) ) {
1682 buffer_add(sql_buf, ", ");
1684 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1685 char* val = jsonNumberToDBString( field, in_item );
1686 OSRF_BUFFER_ADD( sql_buf, val );
1690 char* key_string = jsonObjectToSimpleString(in_item);
1691 if ( dbi_conn_quote_string(dbhandle, &key_string) ) {
1692 OSRF_BUFFER_ADD( sql_buf, key_string );
1695 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, key_string);
1697 buffer_free(sql_buf);
1704 OSRF_BUFFER_ADD_CHAR( sql_buf, ')' );
1706 return buffer_release(sql_buf);
1709 // Receive a JSON_ARRAY representing a function call. The first
1710 // entry in the array is the function name. The rest are parameters.
1711 static char* searchValueTransform( const jsonObject* array ) {
1712 growing_buffer* sql_buf = buffer_init(32);
1715 jsonObject* func_item;
1717 // Get the function name
1718 if( array->size > 0 ) {
1719 func_item = jsonObjectGetIndex( array, 0 );
1720 val = jsonObjectToSimpleString( func_item );
1721 OSRF_BUFFER_ADD( sql_buf, val );
1722 OSRF_BUFFER_ADD( sql_buf, "( " );
1726 // Get the parameters
1727 int func_item_index = 1; // We already grabbed the zeroth entry
1728 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1730 // Add a separator comma, if we need one
1731 if( func_item_index > 2 )
1732 buffer_add( sql_buf, ", " );
1734 // Add the current parameter
1735 if (func_item->type == JSON_NULL) {
1736 buffer_add( sql_buf, "NULL" );
1738 val = jsonObjectToSimpleString(func_item);
1739 if ( dbi_conn_quote_string(dbhandle, &val) ) {
1740 OSRF_BUFFER_ADD( sql_buf, val );
1743 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1744 buffer_free(sql_buf);
1751 buffer_add( sql_buf, " )" );
1753 return buffer_release(sql_buf);
1756 static char* searchFunctionPredicate (const char* class, osrfHash* field,
1757 const jsonObject* node, const char* node_key) {
1758 growing_buffer* sql_buf = buffer_init(32);
1760 char* val = searchValueTransform(node);
1766 osrfHashGet(field, "name"),
1773 return buffer_release(sql_buf);
1776 // class is a class name
1777 // field is a field definition as stored in the IDL
1778 // node comes from the method parameter, and represents an entry in the SELECT list
1779 static char* searchFieldTransform (const char* class, osrfHash* field, const jsonObject* node) {
1780 growing_buffer* sql_buf = buffer_init(32);
1782 char* field_transform = jsonObjectToSimpleString( jsonObjectGetKeyConst( node, "transform" ) );
1783 char* transform_subcolumn = jsonObjectToSimpleString( jsonObjectGetKeyConst( node, "result_field" ) );
1785 if(transform_subcolumn)
1786 OSRF_BUFFER_ADD_CHAR( sql_buf, '(' ); // enclose transform in parentheses
1788 if (field_transform) {
1789 buffer_fadd( sql_buf, "%s(\"%s\".%s", field_transform, class, osrfHashGet(field, "name"));
1790 const jsonObject* array = jsonObjectGetKeyConst( node, "params" );
1793 int func_item_index = 0;
1794 jsonObject* func_item;
1795 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1797 char* val = jsonObjectToSimpleString(func_item);
1800 buffer_add( sql_buf, ",NULL" );
1801 } else if ( dbi_conn_quote_string(dbhandle, &val) ) {
1802 OSRF_BUFFER_ADD_CHAR( sql_buf, ',' );
1803 OSRF_BUFFER_ADD( sql_buf, val );
1805 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1806 free(transform_subcolumn);
1807 free(field_transform);
1809 buffer_free(sql_buf);
1816 buffer_add( sql_buf, " )" );
1819 buffer_fadd( sql_buf, "\"%s\".%s", class, osrfHashGet(field, "name"));
1822 if (transform_subcolumn)
1823 buffer_fadd( sql_buf, ").\"%s\"", transform_subcolumn );
1825 if (field_transform) free(field_transform);
1826 if (transform_subcolumn) free(transform_subcolumn);
1828 return buffer_release(sql_buf);
1831 static char* searchFieldTransformPredicate (const char* class, osrfHash* field, jsonObject* node, const char* node_key) {
1832 char* field_transform = searchFieldTransform( class, field, node );
1835 if (!jsonObjectGetKeyConst( node, "value" )) {
1836 value = searchWHERE( node, osrfHashGet( oilsIDL(), class ), AND_OP_JOIN, NULL );
1837 } else if (jsonObjectGetKeyConst( node, "value" )->type == JSON_ARRAY) {
1838 value = searchValueTransform(jsonObjectGetKeyConst( node, "value" ));
1839 } else if (jsonObjectGetKeyConst( node, "value" )->type == JSON_HASH) {
1840 value = searchWHERE( jsonObjectGetKeyConst( node, "value" ), osrfHashGet( oilsIDL(), class ), AND_OP_JOIN, NULL );
1841 } else if (jsonObjectGetKeyConst( node, "value" )->type != JSON_NULL) {
1842 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1843 value = jsonNumberToDBString( field, jsonObjectGetKeyConst( node, "value" ) );
1845 value = jsonObjectToSimpleString(jsonObjectGetKeyConst( node, "value" ));
1846 if ( !dbi_conn_quote_string(dbhandle, &value) ) {
1847 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, value);
1849 free(field_transform);
1855 growing_buffer* sql_buf = buffer_init(32);
1866 free(field_transform);
1868 return buffer_release(sql_buf);
1871 static char* searchSimplePredicate (const char* orig_op, const char* class,
1872 osrfHash* field, const jsonObject* node) {
1876 if (node->type != JSON_NULL) {
1877 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1878 val = jsonNumberToDBString( field, node );
1880 val = jsonObjectToSimpleString(node);
1884 char* pred = searchWriteSimplePredicate( class, field, osrfHashGet(field, "name"), orig_op, val );
1891 static char* searchWriteSimplePredicate ( const char* class, osrfHash* field,
1892 const char* left, const char* orig_op, const char* right ) {
1896 if (right == NULL) {
1897 val = strdup("NULL");
1899 if (strcmp( orig_op, "=" ))
1900 op = strdup("IS NOT");
1904 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1905 val = strdup(right);
1906 op = strdup(orig_op);
1909 val = strdup(right);
1910 if ( !dbi_conn_quote_string(dbhandle, &val) ) {
1911 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1915 op = strdup(orig_op);
1918 growing_buffer* sql_buf = buffer_init(16);
1919 buffer_fadd( sql_buf, "\"%s\".%s %s %s", class, left, op, val );
1923 return buffer_release(sql_buf);
1926 static char* searchBETWEENPredicate (const char* class, osrfHash* field, jsonObject* node) {
1931 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1932 x_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,0));
1933 y_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,1));
1936 x_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,0));
1937 y_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,1));
1938 if ( !(dbi_conn_quote_string(dbhandle, &x_string) && dbi_conn_quote_string(dbhandle, &y_string)) ) {
1939 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key strings [%s] and [%s]", MODULENAME, x_string, y_string);
1946 growing_buffer* sql_buf = buffer_init(32);
1947 buffer_fadd( sql_buf, "%s BETWEEN %s AND %s", osrfHashGet(field, "name"), x_string, y_string );
1951 return buffer_release(sql_buf);
1954 static char* searchPredicate ( const char* class, osrfHash* field,
1955 jsonObject* node, osrfMethodContext* ctx ) {
1958 if (node->type == JSON_ARRAY) { // equality IN search
1959 pred = searchINPredicate( class, field, node, NULL, ctx );
1960 } else if (node->type == JSON_HASH) { // non-equality search
1961 jsonObject* pred_node;
1962 jsonIterator* pred_itr = jsonNewIterator( node );
1963 while ( (pred_node = jsonIteratorNext( pred_itr )) ) {
1964 if ( !(strcasecmp( pred_itr->key,"between" )) )
1965 pred = searchBETWEENPredicate( class, field, pred_node );
1966 else if ( !(strcasecmp( pred_itr->key,"in" )) || !(strcasecmp( pred_itr->key,"not in" )) )
1967 pred = searchINPredicate( class, field, pred_node, pred_itr->key, ctx );
1968 else if ( pred_node->type == JSON_ARRAY )
1969 pred = searchFunctionPredicate( class, field, pred_node, pred_itr->key );
1970 else if ( pred_node->type == JSON_HASH )
1971 pred = searchFieldTransformPredicate( class, field, pred_node, pred_itr->key );
1973 pred = searchSimplePredicate( pred_itr->key, class, field, pred_node );
1977 jsonIteratorFree(pred_itr);
1978 } else if (node->type == JSON_NULL) { // IS NULL search
1979 growing_buffer* _p = buffer_init(64);
1982 "\"%s\".%s IS NULL",
1984 osrfHashGet(field, "name")
1986 pred = buffer_release(_p);
1987 } else { // equality search
1988 pred = searchSimplePredicate( "=", class, field, node );
2007 field : call_number,
2023 static char* searchJOIN ( const jsonObject* join_hash, osrfHash* leftmeta ) {
2025 const jsonObject* working_hash;
2026 jsonObject* freeable_hash = NULL;
2028 if (join_hash->type == JSON_STRING) {
2029 // create a wrapper around a copy of the original
2030 char* _tmp = jsonObjectToSimpleString( join_hash );
2031 freeable_hash = jsonNewObjectType(JSON_HASH);
2032 jsonObjectSetKey(freeable_hash, _tmp, NULL);
2034 working_hash = freeable_hash;
2037 if( join_hash->type != JSON_HASH ) {
2040 "%s: JOIN failed; expected JSON object type not found",
2045 working_hash = join_hash;
2048 growing_buffer* join_buf = buffer_init(128);
2049 const char* leftclass = osrfHashGet(leftmeta, "classname");
2051 jsonObject* snode = NULL;
2052 jsonIterator* search_itr = jsonNewIterator( working_hash );
2054 while ( (snode = jsonIteratorNext( search_itr )) ) {
2055 const char* class = search_itr->key;
2056 osrfHash* idlClass = osrfHashGet( oilsIDL(), class );
2060 "%s: JOIN failed. No class \"%s\" defined in IDL",
2064 jsonIteratorFree( search_itr );
2065 buffer_free( join_buf );
2067 jsonObjectFree( freeable_hash );
2071 char* fkey = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "fkey" ) );
2072 char* field = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "field" ) );
2074 if (field && !fkey) {
2075 fkey = (char*)oilsIDLFindPath("/%s/links/%s/key", class, field);
2079 "%s: JOIN failed. No link defined from %s.%s to %s",
2085 buffer_free(join_buf);
2087 jsonObjectFree(freeable_hash);
2089 jsonIteratorFree(search_itr);
2092 fkey = strdup( fkey );
2094 } else if (!field && fkey) {
2095 field = (char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, fkey );
2099 "%s: JOIN failed. No link defined from %s.%s to %s",
2105 buffer_free(join_buf);
2107 jsonObjectFree(freeable_hash);
2109 jsonIteratorFree(search_itr);
2112 field = strdup( field );
2114 } else if (!field && !fkey) {
2115 osrfHash* _links = oilsIDL_links( leftclass );
2117 // For each link defined for the left class:
2118 // see if the link references the joined class
2119 osrfHashIterator* itr = osrfNewHashIterator( _links );
2120 osrfHash* curr_link = NULL;
2121 while( (curr_link = osrfHashIteratorNext( itr ) ) ) {
2122 const char* other_class = osrfHashGet( curr_link, "class" );
2123 if( other_class && !strcmp( other_class, class ) ) {
2125 // Found a link between the classes
2126 fkey = strdup( osrfHashIteratorKey( itr ) );
2127 const char* other_key = osrfHashGet( curr_link, "key" );
2128 field = other_key ? strdup( other_key ) : NULL;
2132 osrfHashIteratorFree( itr );
2134 if (!field || !fkey) {
2135 // Do another such search, with the classes reversed
2136 _links = oilsIDL_links( class );
2138 // For each link defined for the joined class:
2139 // see if the link references the left class
2140 osrfHashIterator* itr = osrfNewHashIterator( _links );
2141 osrfHash* curr_link = NULL;
2142 while( (curr_link = osrfHashIteratorNext( itr ) ) ) {
2143 const char* other_class = osrfHashGet( curr_link, "class" );
2144 if( other_class && !strcmp( other_class, leftclass ) ) {
2146 // Found a link between the classes
2147 fkey = strdup( osrfHashIteratorKey( itr ) );
2148 const char* other_key = osrfHashGet( curr_link, "key" );
2149 field = other_key ? strdup( other_key ) : NULL;
2153 osrfHashIteratorFree( itr );
2156 if (!field || !fkey) {
2159 "%s: JOIN failed. No link defined between %s and %s",
2166 buffer_free(join_buf);
2168 jsonObjectFree(freeable_hash);
2169 jsonIteratorFree(search_itr);
2175 char* type = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "type" ) );
2177 if ( !strcasecmp(type,"left") ) {
2178 buffer_add(join_buf, " LEFT JOIN");
2179 } else if ( !strcasecmp(type,"right") ) {
2180 buffer_add(join_buf, " RIGHT JOIN");
2181 } else if ( !strcasecmp(type,"full") ) {
2182 buffer_add(join_buf, " FULL JOIN");
2184 buffer_add(join_buf, " INNER JOIN");
2187 buffer_add(join_buf, " INNER JOIN");
2191 char* table = getSourceDefinition(idlClass);
2195 jsonIteratorFree( search_itr );
2196 buffer_free( join_buf );
2198 jsonObjectFree( freeable_hash );
2202 buffer_fadd(join_buf, " %s AS \"%s\" ON ( \"%s\".%s = \"%s\".%s",
2203 table, class, class, field, leftclass, fkey);
2206 const jsonObject* filter = jsonObjectGetKeyConst( snode, "filter" );
2208 char* filter_op = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "filter_op" ) );
2210 if (!strcasecmp("or",filter_op)) {
2211 buffer_add( join_buf, " OR " );
2213 buffer_add( join_buf, " AND " );
2216 buffer_add( join_buf, " AND " );
2219 char* jpred = searchWHERE( filter, idlClass, AND_OP_JOIN, NULL );
2220 OSRF_BUFFER_ADD_CHAR( join_buf, ' ' );
2221 OSRF_BUFFER_ADD( join_buf, jpred );
2226 buffer_add(join_buf, " ) ");
2228 const jsonObject* join_filter = jsonObjectGetKeyConst( snode, "join" );
2230 char* jpred = searchJOIN( join_filter, idlClass );
2231 OSRF_BUFFER_ADD_CHAR( join_buf, ' ' );
2232 OSRF_BUFFER_ADD( join_buf, jpred );
2241 jsonObjectFree(freeable_hash);
2242 jsonIteratorFree(search_itr);
2244 return buffer_release(join_buf);
2249 { +class : { -or|-and : { field : { op : value }, ... } ... }, ... }
2250 { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }
2251 [ { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }, ... ]
2255 static char* searchWHERE ( const jsonObject* search_hash, osrfHash* meta, int opjoin_type, osrfMethodContext* ctx ) {
2259 "%s: Entering searchWHERE; search_hash addr = %p, meta addr = %p, opjoin_type = %d, ctx addr = %p",
2267 growing_buffer* sql_buf = buffer_init(128);
2269 jsonObject* node = NULL;
2272 if ( search_hash->type == JSON_ARRAY ) {
2273 osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_ARRAY", MODULENAME);
2274 jsonIterator* search_itr = jsonNewIterator( search_hash );
2275 while ( (node = jsonIteratorNext( search_itr )) ) {
2279 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2280 else buffer_add(sql_buf, " AND ");
2283 char* subpred = searchWHERE( node, meta, opjoin_type, ctx );
2284 buffer_fadd(sql_buf, "( %s )", subpred);
2287 jsonIteratorFree(search_itr);
2289 } else if ( search_hash->type == JSON_HASH ) {
2290 osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_HASH", MODULENAME);
2291 jsonIterator* search_itr = jsonNewIterator( search_hash );
2292 while ( (node = jsonIteratorNext( search_itr )) ) {
2297 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2298 else buffer_add(sql_buf, " AND ");
2301 if ( !strncmp("+",search_itr->key,1) ) {
2302 if ( node->type == JSON_STRING ) {
2303 char* subpred = jsonObjectToSimpleString( node );
2304 buffer_fadd(sql_buf, " \"%s\".%s ", search_itr->key + 1, subpred);
2307 char* subpred = searchWHERE( node, osrfHashGet( oilsIDL(), search_itr->key + 1 ), AND_OP_JOIN, ctx );
2308 buffer_fadd(sql_buf, "( %s )", subpred);
2311 } else if ( !strcasecmp("-or",search_itr->key) ) {
2312 char* subpred = searchWHERE( node, meta, OR_OP_JOIN, ctx );
2313 buffer_fadd(sql_buf, "( %s )", subpred);
2315 } else if ( !strcasecmp("-and",search_itr->key) ) {
2316 char* subpred = searchWHERE( node, meta, AND_OP_JOIN, ctx );
2317 buffer_fadd(sql_buf, "( %s )", subpred);
2319 } else if ( !strcasecmp("-exists",search_itr->key) ) {
2320 char* subpred = SELECT(
2322 jsonObjectGetKey( node, "select" ),
2323 jsonObjectGetKey( node, "from" ),
2324 jsonObjectGetKey( node, "where" ),
2325 jsonObjectGetKey( node, "having" ),
2326 jsonObjectGetKey( node, "order_by" ),
2327 jsonObjectGetKey( node, "limit" ),
2328 jsonObjectGetKey( node, "offset" ),
2332 buffer_fadd(sql_buf, "EXISTS ( %s )", subpred);
2334 } else if ( !strcasecmp("-not-exists",search_itr->key) ) {
2335 char* subpred = SELECT(
2337 jsonObjectGetKey( node, "select" ),
2338 jsonObjectGetKey( node, "from" ),
2339 jsonObjectGetKey( node, "where" ),
2340 jsonObjectGetKey( node, "having" ),
2341 jsonObjectGetKey( node, "order_by" ),
2342 jsonObjectGetKey( node, "limit" ),
2343 jsonObjectGetKey( node, "offset" ),
2347 buffer_fadd(sql_buf, "NOT EXISTS ( %s )", subpred);
2351 char* class = osrfHashGet(meta, "classname");
2352 osrfHash* fields = osrfHashGet(meta, "fields");
2353 osrfHash* field = osrfHashGet( fields, search_itr->key );
2357 char* table = getSourceDefinition(meta);
2359 table = strdup( "(?)" );
2362 "%s: Attempt to reference non-existent column %s on %s (%s)",
2368 buffer_free(sql_buf);
2370 jsonIteratorFree(search_itr);
2374 char* subpred = searchPredicate( class, field, node, ctx );
2375 buffer_add( sql_buf, subpred );
2379 jsonIteratorFree(search_itr);
2382 // ERROR ... only hash and array allowed at this level
2383 char* predicate_string = jsonObjectToJSON( search_hash );
2386 "%s: Invalid predicate structure: %s",
2390 buffer_free(sql_buf);
2391 free(predicate_string);
2396 return buffer_release(sql_buf);
2400 /* method context */ osrfMethodContext* ctx,
2402 /* SELECT */ jsonObject* selhash,
2403 /* FROM */ jsonObject* join_hash,
2404 /* WHERE */ jsonObject* search_hash,
2405 /* HAVING */ jsonObject* having_hash,
2406 /* ORDER BY */ jsonObject* order_hash,
2407 /* LIMIT */ jsonObject* limit,
2408 /* OFFSET */ jsonObject* offset,
2409 /* flags */ int flags
2411 const char* locale = osrf_message_get_last_locale();
2413 // in case we don't get a select list
2414 jsonObject* defaultselhash = NULL;
2416 // general tmp objects
2417 const jsonObject* tmp_const;
2418 jsonObject* selclass = NULL;
2419 jsonObject* selfield = NULL;
2420 jsonObject* snode = NULL;
2421 jsonObject* onode = NULL;
2423 char* string = NULL;
2424 int from_function = 0;
2429 // the core search class
2430 char* core_class = NULL;
2432 // metadata about the core search class
2433 osrfHash* core_meta = NULL;
2435 // punt if there's no core class
2436 if (!join_hash || ( join_hash->type == JSON_HASH && !join_hash->size )) {
2439 "%s: FROM clause is missing or empty",
2443 osrfAppSessionStatus(
2445 OSRF_STATUS_INTERNALSERVERERROR,
2446 "osrfMethodException",
2448 "FROM clause is missing or empty in JSON query"
2453 // get the core class -- the only key of the top level FROM clause, or a string
2454 if (join_hash->type == JSON_HASH) {
2455 jsonIterator* tmp_itr = jsonNewIterator( join_hash );
2456 snode = jsonIteratorNext( tmp_itr );
2458 core_class = strdup( tmp_itr->key );
2461 jsonObject* extra = jsonIteratorNext( tmp_itr );
2463 jsonIteratorFree( tmp_itr );
2466 // There shouldn't be more than one entry in join_hash
2470 "%s: Malformed FROM clause: extra entry in JSON_HASH",
2474 osrfAppSessionStatus(
2476 OSRF_STATUS_INTERNALSERVERERROR,
2477 "osrfMethodException",
2479 "Malformed FROM clause in JSON query"
2482 return NULL; // Malformed join_hash; extra entry
2484 } else if (join_hash->type == JSON_ARRAY) {
2486 core_class = jsonObjectToSimpleString( jsonObjectGetIndex(join_hash, 0) );
2489 } else if (join_hash->type == JSON_STRING) {
2490 core_class = jsonObjectToSimpleString( join_hash );
2496 "%s: FROM clause is unexpected JSON type: %s",
2498 json_type( join_hash->type )
2501 osrfAppSessionStatus(
2503 OSRF_STATUS_INTERNALSERVERERROR,
2504 "osrfMethodException",
2506 "Ill-formed FROM clause in JSON query"
2512 if (!from_function) {
2513 // Get the IDL class definition for the core class
2514 core_meta = osrfHashGet( oilsIDL(), core_class );
2515 if( !core_meta ) { // Didn't find it?
2518 "%s: SELECT clause references undefined class: \"%s\"",
2523 osrfAppSessionStatus(
2525 OSRF_STATUS_INTERNALSERVERERROR,
2526 "osrfMethodException",
2528 "SELECT clause references undefined class in JSON query"
2534 // Make sure the class isn't virtual
2535 if( str_is_true( osrfHashGet( core_meta, "virtual" ) ) ) {
2538 "%s: Core class is virtual: \"%s\"",
2543 osrfAppSessionStatus(
2545 OSRF_STATUS_INTERNALSERVERERROR,
2546 "osrfMethodException",
2548 "FROM clause references virtual class in JSON query"
2555 // if the select list is empty, or the core class field list is '*',
2556 // build the default select list ...
2558 selhash = defaultselhash = jsonNewObjectType(JSON_HASH);
2559 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2560 } else if( selhash->type != JSON_HASH ) {
2563 "%s: Expected JSON_HASH for SELECT clause; found %s",
2565 json_type( selhash->type )
2569 osrfAppSessionStatus(
2571 OSRF_STATUS_INTERNALSERVERERROR,
2572 "osrfMethodException",
2574 "Malformed SELECT clause in JSON query"
2578 } else if ( (tmp_const = jsonObjectGetKeyConst( selhash, core_class )) && tmp_const->type == JSON_STRING ) {
2579 char* _x = jsonObjectToSimpleString( tmp_const );
2580 if (!strncmp( "*", _x, 1 )) {
2581 jsonObjectRemoveKey( selhash, core_class );
2582 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2588 growing_buffer* sql_buf = buffer_init(128);
2590 // temp buffer for the SELECT list
2591 growing_buffer* select_buf = buffer_init(128);
2592 growing_buffer* order_buf = buffer_init(128);
2593 growing_buffer* group_buf = buffer_init(128);
2594 growing_buffer* having_buf = buffer_init(128);
2596 int aggregate_found = 0; // boolean
2598 // Build a select list
2599 if(from_function) // From a function we select everything
2600 OSRF_BUFFER_ADD_CHAR( select_buf, '*' );
2603 // If we need to build a default list, prepare to do so
2604 jsonObject* _tmp = jsonObjectGetKey( selhash, core_class );
2605 if ( _tmp && !_tmp->size ) {
2607 osrfHash* core_fields = osrfHashGet( core_meta, "fields" );
2609 osrfHashIterator* field_itr = osrfNewHashIterator( core_fields );
2610 osrfHash* field_def;
2611 while( ( field_def = osrfHashIteratorNext( field_itr ) ) ) {
2612 if( ! str_is_true( osrfHashGet( field_def, "virtual" ) ) ) {
2613 // This field is not virtual, so add it to the list
2614 jsonObjectPush( _tmp, jsonNewObject( osrfHashIteratorKey( field_itr ) ) );
2617 osrfHashIteratorFree( field_itr );
2620 // Now build the actual select list
2622 //jsonObject* is_agg = jsonObjectFindPath(selhash, "//aggregate");
2625 jsonIterator* selclass_itr = jsonNewIterator( selhash );
2626 while ( (selclass = jsonIteratorNext( selclass_itr )) ) { // For each class
2628 // Make sure the class is defined in the IDL
2629 const char* cname = selclass_itr->key;
2630 osrfHash* idlClass = osrfHashGet( oilsIDL(), cname );
2634 "%s: Selected class \"%s\" not defined in IDL",
2640 osrfAppSessionStatus(
2642 OSRF_STATUS_INTERNALSERVERERROR,
2643 "osrfMethodException",
2645 "Selected class is not defined"
2647 jsonIteratorFree( selclass_itr );
2648 //jsonObjectFree( is_agg );
2649 buffer_free( sql_buf );
2650 buffer_free( select_buf );
2651 buffer_free( order_buf );
2652 buffer_free( group_buf );
2653 buffer_free( having_buf );
2654 if( defaultselhash ) jsonObjectFree( defaultselhash );
2659 // Make sure the target relation is in the join tree.
2661 // At this point join_hash is a step down from the join_hash we
2662 // received as a parameter. If the original was a JSON_STRING,
2663 // then json_hash is now NULL. If the original was a JSON_HASH,
2664 // then json_hash is now the first (and only) entry in it,
2665 // denoting the core class. We've already excluded the
2666 // possibility that the original was a JSON_ARRAY, because in
2667 // that case from_function would be non-NULL, and we wouldn't
2670 int class_in_from_clause; // boolean
2672 if ( ! strcmp( core_class, cname ))
2673 // This is the core class -- no problem
2674 class_in_from_clause = 1;
2677 // There's only one class in the FROM clause, and this isn't it
2678 class_in_from_clause = 0;
2679 else if (join_hash->type == JSON_STRING) {
2680 // There's only one class in the FROM clause
2681 string = jsonObjectToSimpleString(join_hash);
2682 if ( strcmp( string, cname ) )
2683 class_in_from_clause = 0; // This isn't it
2685 class_in_from_clause = 1; // This is it
2688 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", cname);
2689 if ( 0 == found->size )
2690 class_in_from_clause = 0; // Nowhere in the join tree
2692 class_in_from_clause = 1; // Found it
2693 jsonObjectFree( found );
2697 // If the class isn't in the FROM clause, bail out
2698 if( ! class_in_from_clause ) {
2701 "%s: SELECT clause references class not in FROM clause: \"%s\"",
2706 osrfAppSessionStatus(
2708 OSRF_STATUS_INTERNALSERVERERROR,
2709 "osrfMethodException",
2711 "Selected class not in FROM clause in JSON query"
2713 jsonIteratorFree( selclass_itr );
2714 //jsonObjectFree( is_agg );
2715 buffer_free( sql_buf );
2716 buffer_free( select_buf );
2717 buffer_free( order_buf );
2718 buffer_free( group_buf );
2719 buffer_free( having_buf );
2720 if( defaultselhash ) jsonObjectFree( defaultselhash );
2725 // Look up some attributes of the current class, so that we
2726 // don't have to look them up again for each field
2727 osrfHash* class_field_set = osrfHashGet( idlClass, "fields" );
2728 const char* class_pkey = osrfHashGet( idlClass, "primarykey" );
2729 const char* class_tname = osrfHashGet( idlClass, "tablename" );
2731 // stitch together the column list ...
2732 jsonIterator* select_itr = jsonNewIterator( selclass );
2733 while ( (selfield = jsonIteratorNext( select_itr )) ) { // for each SELECT column
2735 // If we need a separator comma, add one
2739 OSRF_BUFFER_ADD_CHAR( select_buf, ',' );
2742 // ... if it's a string, just toss it on the pile
2743 if (selfield->type == JSON_STRING) {
2745 // Look up the field in the IDL
2746 const char* col_name = selfield->value.s;
2747 osrfHash* field_def = osrfHashGet( class_field_set, col_name );
2749 // No such field in current class
2752 "%s: Selected column \"%s\" not defined in IDL for class \"%s\"",
2758 osrfAppSessionStatus(
2760 OSRF_STATUS_INTERNALSERVERERROR,
2761 "osrfMethodException",
2763 "Selected column not defined in JSON query"
2765 jsonIteratorFree( select_itr );
2766 jsonIteratorFree( selclass_itr );
2767 //jsonObjectFree( is_agg );
2768 buffer_free( sql_buf );
2769 buffer_free( select_buf );
2770 buffer_free( order_buf );
2771 buffer_free( group_buf );
2772 buffer_free( having_buf );
2773 if( defaultselhash ) jsonObjectFree( defaultselhash );
2776 } else if ( str_is_true( osrfHashGet( field_def, "virtual" ) ) ) {
2777 // Virtual field not allowed
2780 "%s: Selected column \"%s\" for class \"%s\" is virtual",
2786 osrfAppSessionStatus(
2788 OSRF_STATUS_INTERNALSERVERERROR,
2789 "osrfMethodException",
2791 "Selected column may not be virtual in JSON query"
2793 jsonIteratorFree( select_itr );
2794 jsonIteratorFree( selclass_itr );
2795 //jsonObjectFree( is_agg );
2796 buffer_free( sql_buf );
2797 buffer_free( select_buf );
2798 buffer_free( order_buf );
2799 buffer_free( group_buf );
2800 buffer_free( having_buf );
2801 if( defaultselhash ) jsonObjectFree( defaultselhash );
2808 if (flags & DISABLE_I18N)
2811 i18n = osrfHashGet(field_def, "i18n");
2813 if( str_is_true( i18n ) ) {
2814 buffer_fadd( select_buf,
2815 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2816 class_tname, cname, col_name, class_pkey, cname, class_pkey, locale, col_name );
2818 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2821 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2824 // ... but it could be an object, in which case we check for a Field Transform
2825 } else if (selfield->type == JSON_HASH) {
2827 char* col_name = jsonObjectToSimpleString( jsonObjectGetKeyConst( selfield, "column" ) );
2829 // Get the field definition from the IDL
2830 osrfHash* field_def = osrfHashGet( class_field_set, col_name );
2832 // No such field in current class
2835 "%s: Selected column \"%s\" is not defined in IDL for class \"%s\"",
2841 osrfAppSessionStatus(
2843 OSRF_STATUS_INTERNALSERVERERROR,
2844 "osrfMethodException",
2846 "Selected column is not defined in JSON query"
2848 jsonIteratorFree( select_itr );
2849 jsonIteratorFree( selclass_itr );
2850 //jsonObjectFree( is_agg );
2851 buffer_free( sql_buf );
2852 buffer_free( select_buf );
2853 buffer_free( order_buf );
2854 buffer_free( group_buf );
2855 buffer_free( having_buf );
2856 if( defaultselhash ) jsonObjectFree( defaultselhash );
2859 } else if ( str_is_true( osrfHashGet( field_def, "virtual" ) ) ) {
2860 // No such field in current class
2863 "%s: Selected column \"%s\" is virtual for class \"%s\"",
2869 osrfAppSessionStatus(
2871 OSRF_STATUS_INTERNALSERVERERROR,
2872 "osrfMethodException",
2874 "Selected column is virtual in JSON query"
2876 jsonIteratorFree( select_itr );
2877 jsonIteratorFree( selclass_itr );
2878 //jsonObjectFree( is_agg );
2879 buffer_free( sql_buf );
2880 buffer_free( select_buf );
2881 buffer_free( order_buf );
2882 buffer_free( group_buf );
2883 buffer_free( having_buf );
2884 if( defaultselhash ) jsonObjectFree( defaultselhash );
2889 // Decide what to use as a column alias
2891 if ((tmp_const = jsonObjectGetKeyConst( selfield, "alias" ))) {
2892 _alias = jsonObjectToSimpleString( tmp_const );
2893 } else { // Use field name as the alias
2897 if (jsonObjectGetKeyConst( selfield, "transform" )) {
2898 char* transform_str = searchFieldTransform(cname, field_def, selfield);
2899 buffer_fadd(select_buf, " %s AS \"%s\"", transform_str, _alias);
2900 free(transform_str);
2905 if (flags & DISABLE_I18N)
2908 i18n = osrfHashGet(field_def, "i18n");
2910 if( str_is_true( i18n ) ) {
2911 buffer_fadd( select_buf,
2912 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2913 class_tname, cname, col_name, class_pkey, cname, class_pkey, locale, _alias);
2915 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, _alias);
2918 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, _alias);
2922 if( _alias != col_name )
2929 "%s: Selected item is unexpected JSON type: %s",
2931 json_type( selfield->type )
2934 osrfAppSessionStatus(
2936 OSRF_STATUS_INTERNALSERVERERROR,
2937 "osrfMethodException",
2939 "Ill-formed SELECT item in JSON query"
2941 jsonIteratorFree( select_itr );
2942 jsonIteratorFree( selclass_itr );
2943 //jsonObjectFree( is_agg );
2944 buffer_free( sql_buf );
2945 buffer_free( select_buf );
2946 buffer_free( order_buf );
2947 buffer_free( group_buf );
2948 buffer_free( having_buf );
2949 if( defaultselhash ) jsonObjectFree( defaultselhash );
2954 const jsonObject* agg_obj = jsonObjectGetKey( selfield, "aggregate" );
2956 aggregate_found = 1;
2958 if( ( ! agg_obj ) || ( ! obj_is_true( agg_obj ) ) ) {
2959 // Append a comma (except for the first one)
2960 // and add the column to a GROUP BY clause
2964 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
2966 buffer_fadd(group_buf, " %d", sel_pos);
2970 if (is_agg->size || (flags & SELECT_DISTINCT)) {
2972 const jsonObject* aggregate_obj = jsonObjectGetKey( selfield, "aggregate" );
2973 if ( ! obj_is_true( aggregate_obj ) ) {
2977 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
2980 buffer_fadd(group_buf, " %d", sel_pos);
2983 } else if (is_agg = jsonObjectGetKey( selfield, "having" )) {
2987 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
2990 _column = searchFieldTransform(cname, field, selfield);
2991 OSRF_BUFFER_ADD_CHAR(group_buf, ' ');
2992 OSRF_BUFFER_ADD(group_buf, _column);
2993 _column = searchFieldTransform(cname, field, selfield);
3000 } // end while -- iterating across SELECT columns
3002 jsonIteratorFree(select_itr);
3003 } // end while -- iterating across classes
3005 jsonIteratorFree(selclass_itr);
3007 //if (is_agg) jsonObjectFree(is_agg);
3011 char* col_list = buffer_release(select_buf);
3013 if (from_function) table = searchValueTransform(join_hash);
3014 else table = getSourceDefinition(core_meta);
3018 osrfAppSessionStatus(
3020 OSRF_STATUS_INTERNALSERVERERROR,
3021 "osrfMethodException",
3023 "Unable to identify table for core class"
3026 buffer_free( sql_buf );
3027 buffer_free( order_buf );
3028 buffer_free( group_buf );
3029 buffer_free( having_buf );
3030 if( defaultselhash ) jsonObjectFree( defaultselhash );
3035 // Put it all together
3036 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\" ", col_list, table, core_class );
3040 if (!from_function) {
3041 // Now, walk the join tree and add that clause
3043 char* join_clause = searchJOIN( join_hash, core_meta );
3045 buffer_add(sql_buf, join_clause);
3049 osrfAppSessionStatus(
3051 OSRF_STATUS_INTERNALSERVERERROR,
3052 "osrfMethodException",
3054 "Unable to construct JOIN clause(s)"
3056 buffer_free( sql_buf );
3057 buffer_free( order_buf );
3058 buffer_free( group_buf );
3059 buffer_free( having_buf );
3060 if( defaultselhash ) jsonObjectFree( defaultselhash );
3066 // Build a WHERE clause, if there is one
3067 if ( search_hash ) {
3068 buffer_add(sql_buf, " WHERE ");
3070 // and it's on the WHERE clause
3071 char* pred = searchWHERE( search_hash, core_meta, AND_OP_JOIN, ctx );
3074 buffer_add(sql_buf, pred);
3078 osrfAppSessionStatus(
3080 OSRF_STATUS_INTERNALSERVERERROR,
3081 "osrfMethodException",
3083 "Severe query error in WHERE predicate -- see error log for more details"
3087 buffer_free(having_buf);
3088 buffer_free(group_buf);
3089 buffer_free(order_buf);
3090 buffer_free(sql_buf);
3091 if (defaultselhash) jsonObjectFree(defaultselhash);
3096 // Build a HAVING clause, if there is one
3097 if ( having_hash ) {
3098 buffer_add(sql_buf, " HAVING ");
3100 // and it's on the the WHERE clause
3101 char* pred = searchWHERE( having_hash, core_meta, AND_OP_JOIN, ctx );
3104 buffer_add(sql_buf, pred);
3108 osrfAppSessionStatus(
3110 OSRF_STATUS_INTERNALSERVERERROR,
3111 "osrfMethodException",
3113 "Severe query error in HAVING predicate -- see error log for more details"
3117 buffer_free(having_buf);
3118 buffer_free(group_buf);
3119 buffer_free(order_buf);
3120 buffer_free(sql_buf);
3121 if (defaultselhash) jsonObjectFree(defaultselhash);
3126 // Build an ORDER BY clause, if there is one
3128 jsonIterator* class_itr = jsonNewIterator( order_hash );
3129 while ( (snode = jsonIteratorNext( class_itr )) ) {
3131 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
3134 if ( snode->type == JSON_HASH ) {
3136 jsonIterator* order_itr = jsonNewIterator( snode );
3137 while ( (onode = jsonIteratorNext( order_itr )) ) {
3139 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
3142 char* direction = NULL;
3143 if ( onode->type == JSON_HASH ) {
3144 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
3145 string = searchFieldTransform(
3147 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
3151 growing_buffer* field_buf = buffer_init(16);
3152 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
3153 string = buffer_release(field_buf);
3156 if ( (tmp_const = jsonObjectGetKeyConst( onode, "direction" )) ) {
3157 direction = jsonObjectToSimpleString(tmp_const);
3158 if (!strncasecmp(direction, "d", 1)) {
3160 direction = " DESC";
3168 string = strdup(order_itr->key);
3169 direction = jsonObjectToSimpleString(onode);
3170 if (!strncasecmp(direction, "d", 1)) {
3172 direction = " DESC";
3182 buffer_add(order_buf, ", ");
3185 buffer_add(order_buf, string);
3189 buffer_add(order_buf, direction);
3193 // jsonIteratorFree(order_itr);
3195 } else if ( snode->type == JSON_ARRAY ) {
3197 jsonIterator* order_itr = jsonNewIterator( snode );
3198 while ( (onode = jsonIteratorNext( order_itr )) ) {
3200 char* _f = jsonObjectToSimpleString( onode );
3202 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, _f))
3208 buffer_add(order_buf, ", ");
3211 buffer_add(order_buf, _f);
3215 // jsonIteratorFree(order_itr);
3218 // IT'S THE OOOOOOOOOOOLD STYLE!
3220 osrfLogError(OSRF_LOG_MARK, "%s: Possible SQL injection attempt; direct order by is not allowed", MODULENAME);
3222 osrfAppSessionStatus(
3224 OSRF_STATUS_INTERNALSERVERERROR,
3225 "osrfMethodException",
3227 "Severe query error -- see error log for more details"
3232 buffer_free(having_buf);
3233 buffer_free(group_buf);
3234 buffer_free(order_buf);
3235 buffer_free(sql_buf);
3236 if (defaultselhash) jsonObjectFree(defaultselhash);
3237 jsonIteratorFree(class_itr);
3242 // jsonIteratorFree(class_itr);
3246 string = buffer_release(group_buf);
3248 if ( *string && ( aggregate_found || (flags & SELECT_DISTINCT) ) ) {
3249 OSRF_BUFFER_ADD( sql_buf, " GROUP BY " );
3250 OSRF_BUFFER_ADD( sql_buf, string );
3255 string = buffer_release(having_buf);
3258 OSRF_BUFFER_ADD( sql_buf, " HAVING " );
3259 OSRF_BUFFER_ADD( sql_buf, string );
3264 string = buffer_release(order_buf);
3267 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
3268 OSRF_BUFFER_ADD( sql_buf, string );
3274 string = jsonObjectToSimpleString(limit);
3275 buffer_fadd( sql_buf, " LIMIT %d", atoi(string) );
3280 string = jsonObjectToSimpleString(offset);
3281 buffer_fadd( sql_buf, " OFFSET %d", atoi(string) );
3285 if (!(flags & SUBSELECT)) OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
3288 if (defaultselhash) jsonObjectFree(defaultselhash);
3290 return buffer_release(sql_buf);
3294 static char* buildSELECT ( jsonObject* search_hash, jsonObject* order_hash, osrfHash* meta, osrfMethodContext* ctx ) {
3296 const char* locale = osrf_message_get_last_locale();
3298 osrfHash* fields = osrfHashGet(meta, "fields");
3299 char* core_class = osrfHashGet(meta, "classname");
3301 const jsonObject* join_hash = jsonObjectGetKeyConst( order_hash, "join" );
3303 jsonObject* node = NULL;
3304 jsonObject* snode = NULL;
3305 jsonObject* onode = NULL;
3306 const jsonObject* _tmp = NULL;
3307 jsonObject* selhash = NULL;
3308 jsonObject* defaultselhash = NULL;
3310 growing_buffer* sql_buf = buffer_init(128);
3311 growing_buffer* select_buf = buffer_init(128);
3313 if ( !(selhash = jsonObjectGetKey( order_hash, "select" )) ) {
3314 defaultselhash = jsonNewObjectType(JSON_HASH);
3315 selhash = defaultselhash;
3318 if ( !jsonObjectGetKeyConst(selhash,core_class) ) {
3319 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
3320 jsonObject* flist = jsonObjectGetKey( selhash, core_class );
3325 osrfStringArray* keys = osrfHashKeys( fields );
3326 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
3327 if( ! str_is_true( osrfHashGet( osrfHashGet( fields, field ), "virtual" ) ) )
3328 jsonObjectPush( flist, jsonNewObject( field ) );
3330 osrfStringArrayFree(keys);
3334 jsonIterator* class_itr = jsonNewIterator( selhash );
3335 while ( (snode = jsonIteratorNext( class_itr )) ) {
3337 char* cname = class_itr->key;
3338 osrfHash* idlClass = osrfHashGet( oilsIDL(), cname );
3339 if (!idlClass) continue;
3341 if (strcmp(core_class,class_itr->key)) {
3342 if (!join_hash) continue;
3344 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", class_itr->key);
3346 jsonObjectFree(found);
3350 jsonObjectFree(found);
3353 jsonIterator* select_itr = jsonNewIterator( snode );
3354 while ( (node = jsonIteratorNext( select_itr )) ) {
3355 char* item_str = jsonObjectToSimpleString(node);
3356 osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), item_str );
3358 char* fname = osrfHashGet(field, "name");
3360 if (!field) continue;
3365 OSRF_BUFFER_ADD_CHAR(select_buf, ',');
3370 const jsonObject* no_i18n_obj = jsonObjectGetKey( order_hash, "no_i18n" );
3371 if ( obj_is_true( no_i18n_obj ) ) // Suppress internationalization?
3374 i18n = osrfHashGet(field, "i18n");
3376 if( str_is_true( i18n ) ) {
3377 char* pkey = osrfHashGet(idlClass, "primarykey");
3378 char* tname = osrfHashGet(idlClass, "tablename");
3380 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);
3382 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
3385 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
3389 jsonIteratorFree(select_itr);
3392 jsonIteratorFree(class_itr);
3394 char* col_list = buffer_release(select_buf);
3395 char* table = getSourceDefinition(meta);
3397 table = strdup( "(null)" );
3399 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\"", col_list, table, core_class );
3404 char* join_clause = searchJOIN( join_hash, meta );
3405 OSRF_BUFFER_ADD_CHAR(sql_buf, ' ');
3406 OSRF_BUFFER_ADD(sql_buf, join_clause);
3410 osrfLogDebug(OSRF_LOG_MARK, "%s pre-predicate SQL = %s",
3411 MODULENAME, OSRF_BUFFER_C_STR(sql_buf));
3413 buffer_add(sql_buf, " WHERE ");
3415 char* pred = searchWHERE( search_hash, meta, AND_OP_JOIN, ctx );
3417 osrfAppSessionStatus(
3419 OSRF_STATUS_INTERNALSERVERERROR,
3420 "osrfMethodException",
3422 "Severe query error -- see error log for more details"
3424 buffer_free(sql_buf);
3425 if(defaultselhash) jsonObjectFree(defaultselhash);
3428 buffer_add(sql_buf, pred);
3433 char* string = NULL;
3434 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "order_by" )) ){
3436 growing_buffer* order_buf = buffer_init(128);
3439 jsonIterator* class_itr = jsonNewIterator( _tmp );
3440 while ( (snode = jsonIteratorNext( class_itr )) ) {
3442 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
3445 if ( snode->type == JSON_HASH ) {
3447 jsonIterator* order_itr = jsonNewIterator( snode );
3448 while ( (onode = jsonIteratorNext( order_itr )) ) {
3450 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
3453 char* direction = NULL;
3454 if ( onode->type == JSON_HASH ) {
3455 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
3456 string = searchFieldTransform(
3458 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
3462 growing_buffer* field_buf = buffer_init(16);
3463 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
3464 string = buffer_release(field_buf);
3467 if ( (_tmp = jsonObjectGetKeyConst( onode, "direction" )) ) {
3468 direction = jsonObjectToSimpleString(_tmp);
3469 if (!strncasecmp(direction, "d", 1)) {
3471 direction = " DESC";
3479 string = strdup(order_itr->key);
3480 direction = jsonObjectToSimpleString(onode);
3481 if (!strncasecmp(direction, "d", 1)) {
3483 direction = " DESC";
3493 buffer_add(order_buf, ", ");
3496 buffer_add(order_buf, string);
3500 buffer_add(order_buf, direction);
3505 jsonIteratorFree(order_itr);
3508 string = jsonObjectToSimpleString(snode);
3509 buffer_add(order_buf, string);
3516 jsonIteratorFree(class_itr);
3518 string = buffer_release(order_buf);
3521 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
3522 OSRF_BUFFER_ADD( sql_buf, string );
3528 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "limit" )) ){
3529 string = jsonObjectToSimpleString(_tmp);
3538 _tmp = jsonObjectGetKeyConst( order_hash, "offset" );
3540 string = jsonObjectToSimpleString(_tmp);
3550 if (defaultselhash) jsonObjectFree(defaultselhash);
3552 OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
3553 return buffer_release(sql_buf);
3556 int doJSONSearch ( osrfMethodContext* ctx ) {
3557 if(osrfMethodVerifyContext( ctx )) {
3558 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
3562 osrfLogDebug(OSRF_LOG_MARK, "Recieved query request");
3567 dbhandle = writehandle;
3569 jsonObject* hash = jsonObjectGetIndex(ctx->params, 0);
3573 if ( obj_is_true( jsonObjectGetKey( hash, "distinct" ) ) )
3574 flags |= SELECT_DISTINCT;
3576 if ( obj_is_true( jsonObjectGetKey( hash, "no_i18n" ) ) )
3577 flags |= DISABLE_I18N;
3579 osrfLogDebug(OSRF_LOG_MARK, "Building SQL ...");
3582 jsonObjectGetKey( hash, "select" ),
3583 jsonObjectGetKey( hash, "from" ),
3584 jsonObjectGetKey( hash, "where" ),
3585 jsonObjectGetKey( hash, "having" ),
3586 jsonObjectGetKey( hash, "order_by" ),
3587 jsonObjectGetKey( hash, "limit" ),
3588 jsonObjectGetKey( hash, "offset" ),
3597 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3598 dbi_result result = dbi_conn_query(dbhandle, sql);
3601 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3603 if (dbi_result_first_row(result)) {
3604 /* JSONify the result */
3605 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3608 jsonObject* return_val = oilsMakeJSONFromResult( result );
3609 osrfAppRespond( ctx, return_val );
3610 jsonObjectFree( return_val );
3611 } while (dbi_result_next_row(result));
3614 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
3617 osrfAppRespondComplete( ctx, NULL );
3619 /* clean up the query */
3620 dbi_result_free(result);
3624 osrfLogError(OSRF_LOG_MARK, "%s: Error with query [%s]", MODULENAME, sql);
3625 osrfAppSessionStatus(
3627 OSRF_STATUS_INTERNALSERVERERROR,
3628 "osrfMethodException",
3630 "Severe query error -- see error log for more details"
3638 static jsonObject* doFieldmapperSearch ( osrfMethodContext* ctx, osrfHash* meta,
3639 const jsonObject* params, int* err ) {
3642 dbhandle = writehandle;
3644 osrfHash* links = osrfHashGet(meta, "links");
3645 osrfHash* fields = osrfHashGet(meta, "fields");
3646 char* core_class = osrfHashGet(meta, "classname");
3647 char* pkey = osrfHashGet(meta, "primarykey");
3649 const jsonObject* _tmp;
3651 jsonObject* search_hash = jsonObjectGetIndex(params, 0);
3652 jsonObject* order_hash = jsonObjectGetIndex(params, 1);
3654 char* sql = buildSELECT( search_hash, order_hash, meta, ctx );
3656 osrfLogDebug(OSRF_LOG_MARK, "Problem building query, returning NULL");
3661 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3663 dbi_result result = dbi_conn_query(dbhandle, sql);
3664 if( NULL == result ) {
3665 osrfLogError(OSRF_LOG_MARK, "%s: Error retrieving %s with query [%s]",
3666 MODULENAME, osrfHashGet(meta, "fieldmapper"), sql);
3667 osrfAppSessionStatus(
3669 OSRF_STATUS_INTERNALSERVERERROR,
3670 "osrfMethodException",
3672 "Severe query error -- see error log for more details"
3679 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3682 jsonObject* res_list = jsonNewObjectType(JSON_ARRAY);
3683 osrfHash* dedup = osrfNewHash();
3685 if (dbi_result_first_row(result)) {
3686 /* JSONify the result */
3687 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3689 obj = oilsMakeFieldmapperFromResult( result, meta );
3690 char* pkey_val = oilsFMGetString( obj, pkey );
3691 if ( osrfHashGet( dedup, pkey_val ) ) {
3692 jsonObjectFree(obj);
3695 osrfHashSet( dedup, pkey_val, pkey_val );
3696 jsonObjectPush(res_list, obj);
3698 } while (dbi_result_next_row(result));
3700 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s",
3704 osrfHashFree(dedup);
3705 /* clean up the query */
3706 dbi_result_free(result);
3709 if (res_list->size && order_hash) {
3710 _tmp = jsonObjectGetKeyConst( order_hash, "flesh" );
3712 int x = (int)jsonObjectGetNumber(_tmp);
3713 if (x == -1 || x > max_flesh_depth) x = max_flesh_depth;
3715 const jsonObject* temp_blob;
3716 if ((temp_blob = jsonObjectGetKeyConst( order_hash, "flesh_fields" )) && x > 0) {
3718 jsonObject* flesh_blob = jsonObjectClone( temp_blob );
3719 const jsonObject* flesh_fields = jsonObjectGetKeyConst( flesh_blob, core_class );
3721 osrfStringArray* link_fields = NULL;
3724 if (flesh_fields->size == 1) {
3725 char* _t = jsonObjectToSimpleString( jsonObjectGetIndex( flesh_fields, 0 ) );
3726 if (!strcmp(_t,"*")) link_fields = osrfHashKeys( links );
3732 link_fields = osrfNewStringArray(1);
3733 jsonIterator* _i = jsonNewIterator( flesh_fields );
3734 while ((_f = jsonIteratorNext( _i ))) {
3735 osrfStringArrayAdd( link_fields, jsonObjectToSimpleString( _f ) );
3737 jsonIteratorFree(_i);
3742 jsonIterator* itr = jsonNewIterator( res_list );
3743 while ((cur = jsonIteratorNext( itr ))) {
3748 while ( (link_field = osrfStringArrayGetString(link_fields, i++)) ) {
3750 osrfLogDebug(OSRF_LOG_MARK, "Starting to flesh %s", link_field);
3752 osrfHash* kid_link = osrfHashGet(links, link_field);
3753 if (!kid_link) continue;
3755 osrfHash* field = osrfHashGet(fields, link_field);
3756 if (!field) continue;
3758 osrfHash* value_field = field;
3760 osrfHash* kid_idl = osrfHashGet(oilsIDL(), osrfHashGet(kid_link, "class"));
3761 if (!kid_idl) continue;
3763 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3764 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3767 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) { // might_have
3768 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3771 osrfStringArray* link_map = osrfHashGet( kid_link, "map" );
3773 if (link_map->size > 0) {
3774 jsonObject* _kid_key = jsonNewObjectType(JSON_ARRAY);
3777 jsonNewObject( osrfStringArrayGetString( link_map, 0 ) )
3782 osrfHashGet(kid_link, "class"),
3789 "Link field: %s, remote class: %s, fkey: %s, reltype: %s",
3790 osrfHashGet(kid_link, "field"),
3791 osrfHashGet(kid_link, "class"),
3792 osrfHashGet(kid_link, "key"),
3793 osrfHashGet(kid_link, "reltype")
3796 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
3797 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // search hash
3798 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // order/flesh hash
3800 osrfLogDebug(OSRF_LOG_MARK, "Creating dummy params object...");
3803 jsonObjectToSimpleString(
3806 atoi( osrfHashGet(value_field, "array_position") )
3811 osrfLogDebug(OSRF_LOG_MARK, "Nothing to search for!");
3816 jsonObjectGetIndex(fake_params, 0),
3817 osrfHashGet(kid_link, "key"),
3818 jsonNewObject( search_key )
3825 jsonObjectGetIndex(fake_params, 1),
3827 jsonNewNumberObject( (double)(x - 1 + link_map->size) )
3831 jsonObjectSetKey( jsonObjectGetIndex(fake_params, 1), "flesh_fields", jsonObjectClone(flesh_blob) );
3833 if (jsonObjectGetKeyConst(order_hash, "order_by")) {
3835 jsonObjectGetIndex(fake_params, 1),
3837 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "order_by"))
3841 if (jsonObjectGetKeyConst(order_hash, "select")) {
3843 jsonObjectGetIndex(fake_params, 1),
3845 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "select"))
3849 jsonObject* kids = doFieldmapperSearch(ctx, kid_idl, fake_params, err);
3852 jsonObjectFree( fake_params );
3853 osrfStringArrayFree(link_fields);
3854 jsonIteratorFree(itr);
3855 jsonObjectFree(res_list);
3856 jsonObjectFree(flesh_blob);
3860 osrfLogDebug(OSRF_LOG_MARK, "Search for %s return %d linked objects", osrfHashGet(kid_link, "class"), kids->size);
3862 jsonObject* X = NULL;
3863 if ( link_map->size > 0 && kids->size > 0 ) {
3865 kids = jsonNewObjectType(JSON_ARRAY);
3867 jsonObject* _k_node;
3868 jsonIterator* _k = jsonNewIterator( X );
3869 while ((_k_node = jsonIteratorNext( _k ))) {
3875 (unsigned long)atoi(
3881 osrfHashGet(kid_link, "class")
3885 osrfStringArrayGetString( link_map, 0 )
3894 jsonIteratorFree(_k);
3897 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_a" )) || !(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) {
3898 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3901 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3902 jsonObjectClone( jsonObjectGetIndex(kids, 0) )
3906 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3907 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3910 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3911 jsonObjectClone( kids )
3916 jsonObjectFree(kids);
3920 jsonObjectFree( kids );
3921 jsonObjectFree( fake_params );
3923 osrfLogDebug(OSRF_LOG_MARK, "Fleshing of %s complete", osrfHashGet(kid_link, "field"));
3924 osrfLogDebug(OSRF_LOG_MARK, "%s", jsonObjectToJSON(cur));
3928 jsonObjectFree( flesh_blob );
3929 osrfStringArrayFree(link_fields);
3930 jsonIteratorFree(itr);
3939 static jsonObject* doUpdate(osrfMethodContext* ctx, int* err ) {
3941 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3943 jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
3945 jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
3948 if (!verifyObjectClass(ctx, target)) {
3953 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3954 osrfAppSessionStatus(
3956 OSRF_STATUS_BADREQUEST,
3957 "osrfMethodException",
3959 "No active transaction -- required for UPDATE"
3965 // The following test is harmless but redundant. If a class is
3966 // readonly, we don't register an update method for it.
3967 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
3968 osrfAppSessionStatus(
3970 OSRF_STATUS_BADREQUEST,
3971 "osrfMethodException",
3973 "Cannot UPDATE readonly class"
3979 dbhandle = writehandle;
3981 char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
3983 // Set the last_xact_id
3984 int index = oilsIDL_ntop( target->classname, "last_xact_id" );
3986 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
3987 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
3990 char* pkey = osrfHashGet(meta, "primarykey");
3991 osrfHash* fields = osrfHashGet(meta, "fields");
3993 char* id = oilsFMGetString( target, pkey );
3997 "%s updating %s object with %s = %s",
3999 osrfHashGet(meta, "fieldmapper"),
4004 growing_buffer* sql = buffer_init(128);
4005 buffer_fadd(sql,"UPDATE %s SET", osrfHashGet(meta, "tablename"));
4010 osrfStringArray* field_list = osrfHashKeys( fields );
4011 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
4013 osrfHash* field = osrfHashGet( fields, field_name );
4015 if(!( strcmp( field_name, pkey ) )) continue;
4016 if( str_is_true( osrfHashGet(osrfHashGet(fields,field_name), "virtual") ) )
4019 const jsonObject* field_object = oilsFMGetObject( target, field_name );
4022 if (field_object && field_object->classname) {
4023 value = oilsFMGetString(
4025 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
4028 value = jsonObjectToSimpleString( field_object );
4031 osrfLogDebug( OSRF_LOG_MARK, "Updating %s object with %s = %s", osrfHashGet(meta, "fieldmapper"), field_name, value);
4033 if (!field_object || field_object->type == JSON_NULL) {
4034 if ( !(!( strcmp( osrfHashGet(meta, "classname"), "au" ) ) && !( strcmp( field_name, "passwd" ) )) ) { // arg at the special case!
4035 if (first) first = 0;
4036 else OSRF_BUFFER_ADD_CHAR(sql, ',');
4037 buffer_fadd( sql, " %s = NULL", field_name );
4040 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
4041 if (first) first = 0;
4042 else OSRF_BUFFER_ADD_CHAR(sql, ',');
4044 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
4045 buffer_fadd( sql, " %s = %ld", field_name, atol(value) );
4046 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
4047 buffer_fadd( sql, " %s = %f", field_name, atof(value) );
4050 osrfLogDebug( OSRF_LOG_MARK, "%s is of type %s", field_name, osrfHashGet(field, "datatype"));
4053 if ( dbi_conn_quote_string(dbhandle, &value) ) {
4054 if (first) first = 0;
4055 else OSRF_BUFFER_ADD_CHAR(sql, ',');
4056 buffer_fadd( sql, " %s = %s", field_name, value );
4059 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
4060 osrfAppSessionStatus(
4062 OSRF_STATUS_INTERNALSERVERERROR,
4063 "osrfMethodException",
4065 "Error quoting string -- please see the error log for more details"
4079 jsonObject* obj = jsonNewObject(id);
4081 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
4082 dbi_conn_quote_string(dbhandle, &id);
4084 buffer_fadd( sql, " WHERE %s = %s;", pkey, id );
4086 char* query = buffer_release(sql);
4087 osrfLogDebug(OSRF_LOG_MARK, "%s: Update SQL [%s]", MODULENAME, query);
4089 dbi_result result = dbi_conn_query(dbhandle, query);
4093 jsonObjectFree(obj);
4094 obj = jsonNewObject(NULL);
4097 "%s ERROR updating %s object with %s = %s",
4099 osrfHashGet(meta, "fieldmapper"),
4110 static jsonObject* doDelete(osrfMethodContext* ctx, int* err ) {
4112 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
4114 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
4115 osrfAppSessionStatus(
4117 OSRF_STATUS_BADREQUEST,
4118 "osrfMethodException",
4120 "No active transaction -- required for DELETE"
4126 // The following test is harmless but redundant. If a class is
4127 // readonly, we don't register a delete method for it.
4128 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
4129 osrfAppSessionStatus(
4131 OSRF_STATUS_BADREQUEST,
4132 "osrfMethodException",
4134 "Cannot DELETE readonly class"
4140 dbhandle = writehandle;
4144 char* pkey = osrfHashGet(meta, "primarykey");
4152 if (jsonObjectGetIndex(ctx->params, _obj_pos)->classname) {
4153 if (!verifyObjectClass(ctx, jsonObjectGetIndex( ctx->params, _obj_pos ))) {
4158 id = oilsFMGetString( jsonObjectGetIndex(ctx->params, _obj_pos), pkey );
4161 if (!verifyObjectPCRUD( ctx, NULL )) {
4166 id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, _obj_pos));
4171 "%s deleting %s object with %s = %s",
4173 osrfHashGet(meta, "fieldmapper"),
4178 obj = jsonNewObject(id);
4180 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
4181 dbi_conn_quote_string(writehandle, &id);
4183 dbi_result result = dbi_conn_queryf(writehandle, "DELETE FROM %s WHERE %s = %s;", osrfHashGet(meta, "tablename"), pkey, id);
4186 jsonObjectFree(obj);
4187 obj = jsonNewObject(NULL);
4190 "%s ERROR deleting %s object with %s = %s",
4192 osrfHashGet(meta, "fieldmapper"),
4205 static jsonObject* oilsMakeFieldmapperFromResult( dbi_result result, osrfHash* meta) {
4206 if(!(result && meta)) return jsonNULL;
4208 jsonObject* object = jsonNewObject(NULL);
4209 jsonObjectSetClass(object, osrfHashGet(meta, "classname"));
4211 osrfHash* fields = osrfHashGet(meta, "fields");
4213 osrfLogInternal(OSRF_LOG_MARK, "Setting object class to %s ", object->classname);
4217 char dt_string[256];
4221 int columnIndex = 1;
4223 unsigned short type;
4224 const char* columnName;
4226 /* cycle through the column list */
4227 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
4229 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
4231 fmIndex = -1; // reset the position
4233 /* determine the field type and storage attributes */
4234 type = dbi_result_get_field_type(result, columnName);
4235 attr = dbi_result_get_field_attribs(result, columnName);
4237 /* fetch the fieldmapper index */
4238 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
4240 if ( str_is_true( osrfHashGet(_f, "virtual") ) )
4243 const char* pos = (char*)osrfHashGet(_f, "array_position");
4244 if ( !pos ) continue;
4246 fmIndex = atoi( pos );
4247 osrfLogInternal(OSRF_LOG_MARK, "... Found column at position [%s]...", pos);
4252 if (dbi_result_field_is_null(result, columnName)) {
4253 jsonObjectSetIndex( object, fmIndex, jsonNewObject(NULL) );
4258 case DBI_TYPE_INTEGER :
4260 if( attr & DBI_INTEGER_SIZE8 )
4261 jsonObjectSetIndex( object, fmIndex,
4262 jsonNewNumberObject(dbi_result_get_longlong(result, columnName)));
4264 jsonObjectSetIndex( object, fmIndex,
4265 jsonNewNumberObject(dbi_result_get_int(result, columnName)));
4269 case DBI_TYPE_DECIMAL :
4270 jsonObjectSetIndex( object, fmIndex,
4271 jsonNewNumberObject(dbi_result_get_double(result, columnName)));
4274 case DBI_TYPE_STRING :
4280 jsonNewObject( dbi_result_get_string(result, columnName) )
4285 case DBI_TYPE_DATETIME :
4287 memset(dt_string, '\0', sizeof(dt_string));
4288 memset(&gmdt, '\0', sizeof(gmdt));
4290 _tmp_dt = dbi_result_get_datetime(result, columnName);
4293 if (!(attr & DBI_DATETIME_DATE)) {
4294 gmtime_r( &_tmp_dt, &gmdt );
4295 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
4296 } else if (!(attr & DBI_DATETIME_TIME)) {
4297 localtime_r( &_tmp_dt, &gmdt );
4298 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
4300 localtime_r( &_tmp_dt, &gmdt );
4301 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
4304 jsonObjectSetIndex( object, fmIndex, jsonNewObject(dt_string) );
4308 case DBI_TYPE_BINARY :
4309 osrfLogError( OSRF_LOG_MARK,
4310 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
4318 static jsonObject* oilsMakeJSONFromResult( dbi_result result ) {
4319 if(!result) return jsonNULL;
4321 jsonObject* object = jsonNewObject(NULL);
4324 char dt_string[256];
4328 int columnIndex = 1;
4330 unsigned short type;
4331 const char* columnName;
4333 /* cycle through the column list */
4334 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
4336 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
4338 fmIndex = -1; // reset the position
4340 /* determine the field type and storage attributes */
4341 type = dbi_result_get_field_type(result, columnName);
4342 attr = dbi_result_get_field_attribs(result, columnName);
4344 if (dbi_result_field_is_null(result, columnName)) {
4345 jsonObjectSetKey( object, columnName, jsonNewObject(NULL) );
4350 case DBI_TYPE_INTEGER :
4352 if( attr & DBI_INTEGER_SIZE8 )
4353 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_longlong(result, columnName)) );
4355 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_int(result, columnName)) );
4358 case DBI_TYPE_DECIMAL :
4359 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_double(result, columnName)) );
4362 case DBI_TYPE_STRING :
4363 jsonObjectSetKey( object, columnName, jsonNewObject(dbi_result_get_string(result, columnName)) );
4366 case DBI_TYPE_DATETIME :
4368 memset(dt_string, '\0', sizeof(dt_string));
4369 memset(&gmdt, '\0', sizeof(gmdt));
4371 _tmp_dt = dbi_result_get_datetime(result, columnName);
4374 if (!(attr & DBI_DATETIME_DATE)) {
4375 gmtime_r( &_tmp_dt, &gmdt );
4376 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
4377 } else if (!(attr & DBI_DATETIME_TIME)) {
4378 localtime_r( &_tmp_dt, &gmdt );
4379 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
4381 localtime_r( &_tmp_dt, &gmdt );
4382 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
4385 jsonObjectSetKey( object, columnName, jsonNewObject(dt_string) );
4388 case DBI_TYPE_BINARY :
4389 osrfLogError( OSRF_LOG_MARK,
4390 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
4398 // Interpret a string as true or false
4399 static int str_is_true( const char* str ) {
4400 if( NULL == str || strcasecmp( str, "true" ) )
4406 // Interpret a jsonObject as true or false
4407 static int obj_is_true( const jsonObject* obj ) {
4410 else switch( obj->type )
4418 if( strcasecmp( obj->value.s, "true" ) )
4422 case JSON_NUMBER : // Support 1/0 for perl's sake
4423 if( jsonObjectGetNumber( obj ) == 1.0 )
4432 // Translate a numeric code into a text string identifying a type of
4433 // jsonObject. To be used for building error messages.
4434 static const char* json_type( int code ) {
4440 return "JSON_ARRAY";
4442 return "JSON_STRING";
4444 return "JSON_NUMBER";
4450 return "(unrecognized)";