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 if( array->type != JSON_ARRAY ) {
1794 osrfLogError( OSRF_LOG_MARK,
1795 "%s: Expected JSON_ARRAY for function params; found %s",
1796 MODULENAME, json_type( array->type ) );
1797 free( transform_subcolumn );
1798 free( field_transform );
1799 buffer_free( sql_buf );
1802 int func_item_index = 0;
1803 jsonObject* func_item;
1804 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1806 char* val = jsonObjectToSimpleString(func_item);
1809 buffer_add( sql_buf, ",NULL" );
1810 } else if ( dbi_conn_quote_string(dbhandle, &val) ) {
1811 OSRF_BUFFER_ADD_CHAR( sql_buf, ',' );
1812 OSRF_BUFFER_ADD( sql_buf, val );
1814 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1815 free(transform_subcolumn);
1816 free(field_transform);
1818 buffer_free(sql_buf);
1825 buffer_add( sql_buf, " )" );
1828 buffer_fadd( sql_buf, "\"%s\".%s", class, osrfHashGet(field, "name"));
1831 if (transform_subcolumn)
1832 buffer_fadd( sql_buf, ").\"%s\"", transform_subcolumn );
1834 if (field_transform) free(field_transform);
1835 if (transform_subcolumn) free(transform_subcolumn);
1837 return buffer_release(sql_buf);
1840 static char* searchFieldTransformPredicate (const char* class, osrfHash* field, jsonObject* node, const char* node_key) {
1841 char* field_transform = searchFieldTransform( class, field, node );
1844 if (!jsonObjectGetKeyConst( node, "value" )) {
1845 value = searchWHERE( node, osrfHashGet( oilsIDL(), class ), AND_OP_JOIN, NULL );
1846 } else if (jsonObjectGetKeyConst( node, "value" )->type == JSON_ARRAY) {
1847 value = searchValueTransform(jsonObjectGetKeyConst( node, "value" ));
1848 } else if (jsonObjectGetKeyConst( node, "value" )->type == JSON_HASH) {
1849 value = searchWHERE( jsonObjectGetKeyConst( node, "value" ), osrfHashGet( oilsIDL(), class ), AND_OP_JOIN, NULL );
1850 } else if (jsonObjectGetKeyConst( node, "value" )->type != JSON_NULL) {
1851 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1852 value = jsonNumberToDBString( field, jsonObjectGetKeyConst( node, "value" ) );
1854 value = jsonObjectToSimpleString(jsonObjectGetKeyConst( node, "value" ));
1855 if ( !dbi_conn_quote_string(dbhandle, &value) ) {
1856 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, value);
1858 free(field_transform);
1864 growing_buffer* sql_buf = buffer_init(32);
1875 free(field_transform);
1877 return buffer_release(sql_buf);
1880 static char* searchSimplePredicate (const char* orig_op, const char* class,
1881 osrfHash* field, const jsonObject* node) {
1885 if (node->type != JSON_NULL) {
1886 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1887 val = jsonNumberToDBString( field, node );
1889 val = jsonObjectToSimpleString(node);
1893 char* pred = searchWriteSimplePredicate( class, field, osrfHashGet(field, "name"), orig_op, val );
1900 static char* searchWriteSimplePredicate ( const char* class, osrfHash* field,
1901 const char* left, const char* orig_op, const char* right ) {
1905 if (right == NULL) {
1906 val = strdup("NULL");
1908 if (strcmp( orig_op, "=" ))
1909 op = strdup("IS NOT");
1913 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1914 val = strdup(right);
1915 op = strdup(orig_op);
1918 val = strdup(right);
1919 if ( !dbi_conn_quote_string(dbhandle, &val) ) {
1920 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1924 op = strdup(orig_op);
1927 growing_buffer* sql_buf = buffer_init(16);
1928 buffer_fadd( sql_buf, "\"%s\".%s %s %s", class, left, op, val );
1932 return buffer_release(sql_buf);
1935 static char* searchBETWEENPredicate (const char* class, osrfHash* field, jsonObject* node) {
1940 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1941 x_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,0));
1942 y_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,1));
1945 x_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,0));
1946 y_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,1));
1947 if ( !(dbi_conn_quote_string(dbhandle, &x_string) && dbi_conn_quote_string(dbhandle, &y_string)) ) {
1948 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key strings [%s] and [%s]", MODULENAME, x_string, y_string);
1955 growing_buffer* sql_buf = buffer_init(32);
1956 buffer_fadd( sql_buf, "%s BETWEEN %s AND %s", osrfHashGet(field, "name"), x_string, y_string );
1960 return buffer_release(sql_buf);
1963 static char* searchPredicate ( const char* class, osrfHash* field,
1964 jsonObject* node, osrfMethodContext* ctx ) {
1967 if (node->type == JSON_ARRAY) { // equality IN search
1968 pred = searchINPredicate( class, field, node, NULL, ctx );
1969 } else if (node->type == JSON_HASH) { // non-equality search
1970 jsonObject* pred_node;
1971 jsonIterator* pred_itr = jsonNewIterator( node );
1972 while ( (pred_node = jsonIteratorNext( pred_itr )) ) {
1973 if ( !(strcasecmp( pred_itr->key,"between" )) )
1974 pred = searchBETWEENPredicate( class, field, pred_node );
1975 else if ( !(strcasecmp( pred_itr->key,"in" )) || !(strcasecmp( pred_itr->key,"not in" )) )
1976 pred = searchINPredicate( class, field, pred_node, pred_itr->key, ctx );
1977 else if ( pred_node->type == JSON_ARRAY )
1978 pred = searchFunctionPredicate( class, field, pred_node, pred_itr->key );
1979 else if ( pred_node->type == JSON_HASH )
1980 pred = searchFieldTransformPredicate( class, field, pred_node, pred_itr->key );
1982 pred = searchSimplePredicate( pred_itr->key, class, field, pred_node );
1986 jsonIteratorFree(pred_itr);
1987 } else if (node->type == JSON_NULL) { // IS NULL search
1988 growing_buffer* _p = buffer_init(64);
1991 "\"%s\".%s IS NULL",
1993 osrfHashGet(field, "name")
1995 pred = buffer_release(_p);
1996 } else { // equality search
1997 pred = searchSimplePredicate( "=", class, field, node );
2016 field : call_number,
2032 static char* searchJOIN ( const jsonObject* join_hash, osrfHash* leftmeta ) {
2034 const jsonObject* working_hash;
2035 jsonObject* freeable_hash = NULL;
2037 if (join_hash->type == JSON_STRING) {
2038 // create a wrapper around a copy of the original
2039 char* _tmp = jsonObjectToSimpleString( join_hash );
2040 freeable_hash = jsonNewObjectType(JSON_HASH);
2041 jsonObjectSetKey(freeable_hash, _tmp, NULL);
2043 working_hash = freeable_hash;
2046 if( join_hash->type != JSON_HASH ) {
2049 "%s: JOIN failed; expected JSON object type not found",
2054 working_hash = join_hash;
2057 growing_buffer* join_buf = buffer_init(128);
2058 const char* leftclass = osrfHashGet(leftmeta, "classname");
2060 jsonObject* snode = NULL;
2061 jsonIterator* search_itr = jsonNewIterator( working_hash );
2063 while ( (snode = jsonIteratorNext( search_itr )) ) {
2064 const char* class = search_itr->key;
2065 osrfHash* idlClass = osrfHashGet( oilsIDL(), class );
2069 "%s: JOIN failed. No class \"%s\" defined in IDL",
2073 jsonIteratorFree( search_itr );
2074 buffer_free( join_buf );
2076 jsonObjectFree( freeable_hash );
2080 char* fkey = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "fkey" ) );
2081 char* field = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "field" ) );
2083 if (field && !fkey) {
2084 fkey = (char*)oilsIDLFindPath("/%s/links/%s/key", class, field);
2088 "%s: JOIN failed. No link defined from %s.%s to %s",
2094 buffer_free(join_buf);
2096 jsonObjectFree(freeable_hash);
2098 jsonIteratorFree(search_itr);
2101 fkey = strdup( fkey );
2103 } else if (!field && fkey) {
2104 field = (char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, fkey );
2108 "%s: JOIN failed. No link defined from %s.%s to %s",
2114 buffer_free(join_buf);
2116 jsonObjectFree(freeable_hash);
2118 jsonIteratorFree(search_itr);
2121 field = strdup( field );
2123 } else if (!field && !fkey) {
2124 osrfHash* _links = oilsIDL_links( leftclass );
2126 // For each link defined for the left class:
2127 // see if the link references the joined class
2128 osrfHashIterator* itr = osrfNewHashIterator( _links );
2129 osrfHash* curr_link = NULL;
2130 while( (curr_link = osrfHashIteratorNext( itr ) ) ) {
2131 const char* other_class = osrfHashGet( curr_link, "class" );
2132 if( other_class && !strcmp( other_class, class ) ) {
2134 // Found a link between the classes
2135 fkey = strdup( osrfHashIteratorKey( itr ) );
2136 const char* other_key = osrfHashGet( curr_link, "key" );
2137 field = other_key ? strdup( other_key ) : NULL;
2141 osrfHashIteratorFree( itr );
2143 if (!field || !fkey) {
2144 // Do another such search, with the classes reversed
2145 _links = oilsIDL_links( class );
2147 // For each link defined for the joined class:
2148 // see if the link references the left class
2149 osrfHashIterator* itr = osrfNewHashIterator( _links );
2150 osrfHash* curr_link = NULL;
2151 while( (curr_link = osrfHashIteratorNext( itr ) ) ) {
2152 const char* other_class = osrfHashGet( curr_link, "class" );
2153 if( other_class && !strcmp( other_class, leftclass ) ) {
2155 // Found a link between the classes
2156 fkey = strdup( osrfHashIteratorKey( itr ) );
2157 const char* other_key = osrfHashGet( curr_link, "key" );
2158 field = other_key ? strdup( other_key ) : NULL;
2162 osrfHashIteratorFree( itr );
2165 if (!field || !fkey) {
2168 "%s: JOIN failed. No link defined between %s and %s",
2175 buffer_free(join_buf);
2177 jsonObjectFree(freeable_hash);
2178 jsonIteratorFree(search_itr);
2184 char* type = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "type" ) );
2186 if ( !strcasecmp(type,"left") ) {
2187 buffer_add(join_buf, " LEFT JOIN");
2188 } else if ( !strcasecmp(type,"right") ) {
2189 buffer_add(join_buf, " RIGHT JOIN");
2190 } else if ( !strcasecmp(type,"full") ) {
2191 buffer_add(join_buf, " FULL JOIN");
2193 buffer_add(join_buf, " INNER JOIN");
2196 buffer_add(join_buf, " INNER JOIN");
2200 char* table = getSourceDefinition(idlClass);
2204 jsonIteratorFree( search_itr );
2205 buffer_free( join_buf );
2207 jsonObjectFree( freeable_hash );
2211 buffer_fadd(join_buf, " %s AS \"%s\" ON ( \"%s\".%s = \"%s\".%s",
2212 table, class, class, field, leftclass, fkey);
2215 const jsonObject* filter = jsonObjectGetKeyConst( snode, "filter" );
2217 char* filter_op = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "filter_op" ) );
2219 if (!strcasecmp("or",filter_op)) {
2220 buffer_add( join_buf, " OR " );
2222 buffer_add( join_buf, " AND " );
2225 buffer_add( join_buf, " AND " );
2228 char* jpred = searchWHERE( filter, idlClass, AND_OP_JOIN, NULL );
2229 OSRF_BUFFER_ADD_CHAR( join_buf, ' ' );
2230 OSRF_BUFFER_ADD( join_buf, jpred );
2235 buffer_add(join_buf, " ) ");
2237 const jsonObject* join_filter = jsonObjectGetKeyConst( snode, "join" );
2239 char* jpred = searchJOIN( join_filter, idlClass );
2240 OSRF_BUFFER_ADD_CHAR( join_buf, ' ' );
2241 OSRF_BUFFER_ADD( join_buf, jpred );
2250 jsonObjectFree(freeable_hash);
2251 jsonIteratorFree(search_itr);
2253 return buffer_release(join_buf);
2258 { +class : { -or|-and : { field : { op : value }, ... } ... }, ... }
2259 { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }
2260 [ { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }, ... ]
2264 static char* searchWHERE ( const jsonObject* search_hash, osrfHash* meta, int opjoin_type, osrfMethodContext* ctx ) {
2268 "%s: Entering searchWHERE; search_hash addr = %p, meta addr = %p, opjoin_type = %d, ctx addr = %p",
2276 growing_buffer* sql_buf = buffer_init(128);
2278 jsonObject* node = NULL;
2281 if ( search_hash->type == JSON_ARRAY ) {
2282 osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_ARRAY", MODULENAME);
2283 jsonIterator* search_itr = jsonNewIterator( search_hash );
2284 while ( (node = jsonIteratorNext( search_itr )) ) {
2288 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2289 else buffer_add(sql_buf, " AND ");
2292 char* subpred = searchWHERE( node, meta, opjoin_type, ctx );
2293 buffer_fadd(sql_buf, "( %s )", subpred);
2296 jsonIteratorFree(search_itr);
2298 } else if ( search_hash->type == JSON_HASH ) {
2299 osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_HASH", MODULENAME);
2300 jsonIterator* search_itr = jsonNewIterator( search_hash );
2301 while ( (node = jsonIteratorNext( search_itr )) ) {
2306 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2307 else buffer_add(sql_buf, " AND ");
2310 if ( !strncmp("+",search_itr->key,1) ) {
2311 if ( node->type == JSON_STRING ) {
2312 char* subpred = jsonObjectToSimpleString( node );
2313 buffer_fadd(sql_buf, " \"%s\".%s ", search_itr->key + 1, subpred);
2316 char* subpred = searchWHERE( node, osrfHashGet( oilsIDL(), search_itr->key + 1 ), AND_OP_JOIN, ctx );
2317 buffer_fadd(sql_buf, "( %s )", subpred);
2320 } else if ( !strcasecmp("-or",search_itr->key) ) {
2321 char* subpred = searchWHERE( node, meta, OR_OP_JOIN, ctx );
2322 buffer_fadd(sql_buf, "( %s )", subpred);
2324 } else if ( !strcasecmp("-and",search_itr->key) ) {
2325 char* subpred = searchWHERE( node, meta, AND_OP_JOIN, ctx );
2326 buffer_fadd(sql_buf, "( %s )", subpred);
2328 } else if ( !strcasecmp("-exists",search_itr->key) ) {
2329 char* subpred = SELECT(
2331 jsonObjectGetKey( node, "select" ),
2332 jsonObjectGetKey( node, "from" ),
2333 jsonObjectGetKey( node, "where" ),
2334 jsonObjectGetKey( node, "having" ),
2335 jsonObjectGetKey( node, "order_by" ),
2336 jsonObjectGetKey( node, "limit" ),
2337 jsonObjectGetKey( node, "offset" ),
2341 buffer_fadd(sql_buf, "EXISTS ( %s )", subpred);
2343 } else if ( !strcasecmp("-not-exists",search_itr->key) ) {
2344 char* subpred = SELECT(
2346 jsonObjectGetKey( node, "select" ),
2347 jsonObjectGetKey( node, "from" ),
2348 jsonObjectGetKey( node, "where" ),
2349 jsonObjectGetKey( node, "having" ),
2350 jsonObjectGetKey( node, "order_by" ),
2351 jsonObjectGetKey( node, "limit" ),
2352 jsonObjectGetKey( node, "offset" ),
2356 buffer_fadd(sql_buf, "NOT EXISTS ( %s )", subpred);
2360 char* class = osrfHashGet(meta, "classname");
2361 osrfHash* fields = osrfHashGet(meta, "fields");
2362 osrfHash* field = osrfHashGet( fields, search_itr->key );
2366 char* table = getSourceDefinition(meta);
2368 table = strdup( "(?)" );
2371 "%s: Attempt to reference non-existent column %s on %s (%s)",
2377 buffer_free(sql_buf);
2379 jsonIteratorFree(search_itr);
2383 char* subpred = searchPredicate( class, field, node, ctx );
2384 buffer_add( sql_buf, subpred );
2388 jsonIteratorFree(search_itr);
2391 // ERROR ... only hash and array allowed at this level
2392 char* predicate_string = jsonObjectToJSON( search_hash );
2395 "%s: Invalid predicate structure: %s",
2399 buffer_free(sql_buf);
2400 free(predicate_string);
2405 return buffer_release(sql_buf);
2409 /* method context */ osrfMethodContext* ctx,
2411 /* SELECT */ jsonObject* selhash,
2412 /* FROM */ jsonObject* join_hash,
2413 /* WHERE */ jsonObject* search_hash,
2414 /* HAVING */ jsonObject* having_hash,
2415 /* ORDER BY */ jsonObject* order_hash,
2416 /* LIMIT */ jsonObject* limit,
2417 /* OFFSET */ jsonObject* offset,
2418 /* flags */ int flags
2420 const char* locale = osrf_message_get_last_locale();
2422 // in case we don't get a select list
2423 jsonObject* defaultselhash = NULL;
2425 // general tmp objects
2426 const jsonObject* tmp_const;
2427 jsonObject* selclass = NULL;
2428 jsonObject* selfield = NULL;
2429 jsonObject* snode = NULL;
2430 jsonObject* onode = NULL;
2432 char* string = NULL;
2433 int from_function = 0;
2438 // the core search class
2439 char* core_class = NULL;
2441 // metadata about the core search class
2442 osrfHash* core_meta = NULL;
2444 // punt if there's no core class
2445 if (!join_hash || ( join_hash->type == JSON_HASH && !join_hash->size )) {
2448 "%s: FROM clause is missing or empty",
2452 osrfAppSessionStatus(
2454 OSRF_STATUS_INTERNALSERVERERROR,
2455 "osrfMethodException",
2457 "FROM clause is missing or empty in JSON query"
2462 // get the core class -- the only key of the top level FROM clause, or a string
2463 if (join_hash->type == JSON_HASH) {
2464 jsonIterator* tmp_itr = jsonNewIterator( join_hash );
2465 snode = jsonIteratorNext( tmp_itr );
2467 core_class = strdup( tmp_itr->key );
2470 jsonObject* extra = jsonIteratorNext( tmp_itr );
2472 jsonIteratorFree( tmp_itr );
2475 // There shouldn't be more than one entry in join_hash
2479 "%s: Malformed FROM clause: extra entry in JSON_HASH",
2483 osrfAppSessionStatus(
2485 OSRF_STATUS_INTERNALSERVERERROR,
2486 "osrfMethodException",
2488 "Malformed FROM clause in JSON query"
2491 return NULL; // Malformed join_hash; extra entry
2493 } else if (join_hash->type == JSON_ARRAY) {
2495 core_class = jsonObjectToSimpleString( jsonObjectGetIndex(join_hash, 0) );
2498 } else if (join_hash->type == JSON_STRING) {
2499 core_class = jsonObjectToSimpleString( join_hash );
2505 "%s: FROM clause is unexpected JSON type: %s",
2507 json_type( join_hash->type )
2510 osrfAppSessionStatus(
2512 OSRF_STATUS_INTERNALSERVERERROR,
2513 "osrfMethodException",
2515 "Ill-formed FROM clause in JSON query"
2521 if (!from_function) {
2522 // Get the IDL class definition for the core class
2523 core_meta = osrfHashGet( oilsIDL(), core_class );
2524 if( !core_meta ) { // Didn't find it?
2527 "%s: SELECT clause references undefined class: \"%s\"",
2532 osrfAppSessionStatus(
2534 OSRF_STATUS_INTERNALSERVERERROR,
2535 "osrfMethodException",
2537 "SELECT clause references undefined class in JSON query"
2543 // Make sure the class isn't virtual
2544 if( str_is_true( osrfHashGet( core_meta, "virtual" ) ) ) {
2547 "%s: Core class is virtual: \"%s\"",
2552 osrfAppSessionStatus(
2554 OSRF_STATUS_INTERNALSERVERERROR,
2555 "osrfMethodException",
2557 "FROM clause references virtual class in JSON query"
2564 // if the select list is empty, or the core class field list is '*',
2565 // build the default select list ...
2567 selhash = defaultselhash = jsonNewObjectType(JSON_HASH);
2568 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2569 } else if( selhash->type != JSON_HASH ) {
2572 "%s: Expected JSON_HASH for SELECT clause; found %s",
2574 json_type( selhash->type )
2578 osrfAppSessionStatus(
2580 OSRF_STATUS_INTERNALSERVERERROR,
2581 "osrfMethodException",
2583 "Malformed SELECT clause in JSON query"
2587 } else if ( (tmp_const = jsonObjectGetKeyConst( selhash, core_class )) && tmp_const->type == JSON_STRING ) {
2588 char* _x = jsonObjectToSimpleString( tmp_const );
2589 if (!strncmp( "*", _x, 1 )) {
2590 jsonObjectRemoveKey( selhash, core_class );
2591 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2597 growing_buffer* sql_buf = buffer_init(128);
2599 // temp buffer for the SELECT list
2600 growing_buffer* select_buf = buffer_init(128);
2601 growing_buffer* order_buf = buffer_init(128);
2602 growing_buffer* group_buf = buffer_init(128);
2603 growing_buffer* having_buf = buffer_init(128);
2605 int aggregate_found = 0; // boolean
2607 // Build a select list
2608 if(from_function) // From a function we select everything
2609 OSRF_BUFFER_ADD_CHAR( select_buf, '*' );
2612 // If we need to build a default list, prepare to do so
2613 jsonObject* _tmp = jsonObjectGetKey( selhash, core_class );
2614 if ( _tmp && !_tmp->size ) {
2616 osrfHash* core_fields = osrfHashGet( core_meta, "fields" );
2618 osrfHashIterator* field_itr = osrfNewHashIterator( core_fields );
2619 osrfHash* field_def;
2620 while( ( field_def = osrfHashIteratorNext( field_itr ) ) ) {
2621 if( ! str_is_true( osrfHashGet( field_def, "virtual" ) ) ) {
2622 // This field is not virtual, so add it to the list
2623 jsonObjectPush( _tmp, jsonNewObject( osrfHashIteratorKey( field_itr ) ) );
2626 osrfHashIteratorFree( field_itr );
2629 // Now build the actual select list
2631 //jsonObject* is_agg = jsonObjectFindPath(selhash, "//aggregate");
2634 jsonIterator* selclass_itr = jsonNewIterator( selhash );
2635 while ( (selclass = jsonIteratorNext( selclass_itr )) ) { // For each class
2637 // Make sure the class is defined in the IDL
2638 const char* cname = selclass_itr->key;
2639 osrfHash* idlClass = osrfHashGet( oilsIDL(), cname );
2643 "%s: Selected class \"%s\" not defined in IDL",
2649 osrfAppSessionStatus(
2651 OSRF_STATUS_INTERNALSERVERERROR,
2652 "osrfMethodException",
2654 "Selected class is not defined"
2656 jsonIteratorFree( selclass_itr );
2657 //jsonObjectFree( is_agg );
2658 buffer_free( sql_buf );
2659 buffer_free( select_buf );
2660 buffer_free( order_buf );
2661 buffer_free( group_buf );
2662 buffer_free( having_buf );
2663 if( defaultselhash ) jsonObjectFree( defaultselhash );
2668 // Make sure the target relation is in the join tree.
2670 // At this point join_hash is a step down from the join_hash we
2671 // received as a parameter. If the original was a JSON_STRING,
2672 // then json_hash is now NULL. If the original was a JSON_HASH,
2673 // then json_hash is now the first (and only) entry in it,
2674 // denoting the core class. We've already excluded the
2675 // possibility that the original was a JSON_ARRAY, because in
2676 // that case from_function would be non-NULL, and we wouldn't
2679 int class_in_from_clause; // boolean
2681 if ( ! strcmp( core_class, cname ))
2682 // This is the core class -- no problem
2683 class_in_from_clause = 1;
2686 // There's only one class in the FROM clause, and this isn't it
2687 class_in_from_clause = 0;
2688 else if (join_hash->type == JSON_STRING) {
2689 // There's only one class in the FROM clause
2690 string = jsonObjectToSimpleString(join_hash);
2691 if ( strcmp( string, cname ) )
2692 class_in_from_clause = 0; // This isn't it
2694 class_in_from_clause = 1; // This is it
2697 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", cname);
2698 if ( 0 == found->size )
2699 class_in_from_clause = 0; // Nowhere in the join tree
2701 class_in_from_clause = 1; // Found it
2702 jsonObjectFree( found );
2706 // If the class isn't in the FROM clause, bail out
2707 if( ! class_in_from_clause ) {
2710 "%s: SELECT clause references class not in FROM clause: \"%s\"",
2715 osrfAppSessionStatus(
2717 OSRF_STATUS_INTERNALSERVERERROR,
2718 "osrfMethodException",
2720 "Selected class not in FROM clause in JSON query"
2722 jsonIteratorFree( selclass_itr );
2723 //jsonObjectFree( is_agg );
2724 buffer_free( sql_buf );
2725 buffer_free( select_buf );
2726 buffer_free( order_buf );
2727 buffer_free( group_buf );
2728 buffer_free( having_buf );
2729 if( defaultselhash ) jsonObjectFree( defaultselhash );
2734 // Look up some attributes of the current class, so that we
2735 // don't have to look them up again for each field
2736 osrfHash* class_field_set = osrfHashGet( idlClass, "fields" );
2737 const char* class_pkey = osrfHashGet( idlClass, "primarykey" );
2738 const char* class_tname = osrfHashGet( idlClass, "tablename" );
2740 // stitch together the column list ...
2741 jsonIterator* select_itr = jsonNewIterator( selclass );
2742 while ( (selfield = jsonIteratorNext( select_itr )) ) { // for each SELECT column
2744 // If we need a separator comma, add one
2748 OSRF_BUFFER_ADD_CHAR( select_buf, ',' );
2751 // ... if it's a string, just toss it on the pile
2752 if (selfield->type == JSON_STRING) {
2754 // Look up the field in the IDL
2755 const char* col_name = selfield->value.s;
2756 osrfHash* field_def = osrfHashGet( class_field_set, col_name );
2758 // No such field in current class
2761 "%s: Selected column \"%s\" not defined in IDL for class \"%s\"",
2767 osrfAppSessionStatus(
2769 OSRF_STATUS_INTERNALSERVERERROR,
2770 "osrfMethodException",
2772 "Selected column not defined in JSON query"
2774 jsonIteratorFree( select_itr );
2775 jsonIteratorFree( selclass_itr );
2776 //jsonObjectFree( is_agg );
2777 buffer_free( sql_buf );
2778 buffer_free( select_buf );
2779 buffer_free( order_buf );
2780 buffer_free( group_buf );
2781 buffer_free( having_buf );
2782 if( defaultselhash ) jsonObjectFree( defaultselhash );
2785 } else if ( str_is_true( osrfHashGet( field_def, "virtual" ) ) ) {
2786 // Virtual field not allowed
2789 "%s: Selected column \"%s\" for class \"%s\" is virtual",
2795 osrfAppSessionStatus(
2797 OSRF_STATUS_INTERNALSERVERERROR,
2798 "osrfMethodException",
2800 "Selected column may not be virtual in JSON query"
2802 jsonIteratorFree( select_itr );
2803 jsonIteratorFree( selclass_itr );
2804 //jsonObjectFree( is_agg );
2805 buffer_free( sql_buf );
2806 buffer_free( select_buf );
2807 buffer_free( order_buf );
2808 buffer_free( group_buf );
2809 buffer_free( having_buf );
2810 if( defaultselhash ) jsonObjectFree( defaultselhash );
2817 if (flags & DISABLE_I18N)
2820 i18n = osrfHashGet(field_def, "i18n");
2822 if( str_is_true( i18n ) ) {
2823 buffer_fadd( select_buf,
2824 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2825 class_tname, cname, col_name, class_pkey, cname, class_pkey, locale, col_name );
2827 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2830 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2833 // ... but it could be an object, in which case we check for a Field Transform
2834 } else if (selfield->type == JSON_HASH) {
2836 char* col_name = jsonObjectToSimpleString( jsonObjectGetKeyConst( selfield, "column" ) );
2838 // Get the field definition from the IDL
2839 osrfHash* field_def = osrfHashGet( class_field_set, col_name );
2841 // No such field in current class
2844 "%s: Selected column \"%s\" is not defined in IDL for class \"%s\"",
2850 osrfAppSessionStatus(
2852 OSRF_STATUS_INTERNALSERVERERROR,
2853 "osrfMethodException",
2855 "Selected column is not defined in JSON query"
2857 jsonIteratorFree( select_itr );
2858 jsonIteratorFree( selclass_itr );
2859 //jsonObjectFree( is_agg );
2860 buffer_free( sql_buf );
2861 buffer_free( select_buf );
2862 buffer_free( order_buf );
2863 buffer_free( group_buf );
2864 buffer_free( having_buf );
2865 if( defaultselhash ) jsonObjectFree( defaultselhash );
2868 } else if ( str_is_true( osrfHashGet( field_def, "virtual" ) ) ) {
2869 // No such field in current class
2872 "%s: Selected column \"%s\" is virtual for class \"%s\"",
2878 osrfAppSessionStatus(
2880 OSRF_STATUS_INTERNALSERVERERROR,
2881 "osrfMethodException",
2883 "Selected column is virtual in JSON query"
2885 jsonIteratorFree( select_itr );
2886 jsonIteratorFree( selclass_itr );
2887 //jsonObjectFree( is_agg );
2888 buffer_free( sql_buf );
2889 buffer_free( select_buf );
2890 buffer_free( order_buf );
2891 buffer_free( group_buf );
2892 buffer_free( having_buf );
2893 if( defaultselhash ) jsonObjectFree( defaultselhash );
2898 // Decide what to use as a column alias
2900 if ((tmp_const = jsonObjectGetKeyConst( selfield, "alias" ))) {
2901 _alias = jsonObjectToSimpleString( tmp_const );
2902 } else { // Use field name as the alias
2906 if (jsonObjectGetKeyConst( selfield, "transform" )) {
2907 char* transform_str = searchFieldTransform(cname, field_def, selfield);
2908 if( transform_str ) {
2909 buffer_fadd(select_buf, " %s AS \"%s\"", transform_str, _alias);
2910 free(transform_str);
2913 osrfAppSessionStatus(
2915 OSRF_STATUS_INTERNALSERVERERROR,
2916 "osrfMethodException",
2918 "Unable to generate transform function in JSON query"
2920 jsonIteratorFree( select_itr );
2921 jsonIteratorFree( selclass_itr );
2922 //jsonObjectFree( is_agg );
2923 buffer_free( sql_buf );
2924 buffer_free( select_buf );
2925 buffer_free( order_buf );
2926 buffer_free( group_buf );
2927 buffer_free( having_buf );
2928 if( defaultselhash ) jsonObjectFree( defaultselhash );
2936 if (flags & DISABLE_I18N)
2939 i18n = osrfHashGet(field_def, "i18n");
2941 if( str_is_true( i18n ) ) {
2942 buffer_fadd( select_buf,
2943 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2944 class_tname, cname, col_name, class_pkey, cname, class_pkey, locale, _alias);
2946 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, _alias);
2949 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, _alias);
2953 if( _alias != col_name )
2960 "%s: Selected item is unexpected JSON type: %s",
2962 json_type( selfield->type )
2965 osrfAppSessionStatus(
2967 OSRF_STATUS_INTERNALSERVERERROR,
2968 "osrfMethodException",
2970 "Ill-formed SELECT item in JSON query"
2972 jsonIteratorFree( select_itr );
2973 jsonIteratorFree( selclass_itr );
2974 //jsonObjectFree( is_agg );
2975 buffer_free( sql_buf );
2976 buffer_free( select_buf );
2977 buffer_free( order_buf );
2978 buffer_free( group_buf );
2979 buffer_free( having_buf );
2980 if( defaultselhash ) jsonObjectFree( defaultselhash );
2985 const jsonObject* agg_obj = jsonObjectGetKey( selfield, "aggregate" );
2987 aggregate_found = 1;
2989 if( ( ! agg_obj ) || ( ! obj_is_true( agg_obj ) ) ) {
2990 // Append a comma (except for the first one)
2991 // and add the column to a GROUP BY clause
2995 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
2997 buffer_fadd(group_buf, " %d", sel_pos);
3001 if (is_agg->size || (flags & SELECT_DISTINCT)) {
3003 const jsonObject* aggregate_obj = jsonObjectGetKey( selfield, "aggregate" );
3004 if ( ! obj_is_true( aggregate_obj ) ) {
3008 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
3011 buffer_fadd(group_buf, " %d", sel_pos);
3014 } else if (is_agg = jsonObjectGetKey( selfield, "having" )) {
3018 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
3021 _column = searchFieldTransform(cname, field, selfield);
3022 OSRF_BUFFER_ADD_CHAR(group_buf, ' ');
3023 OSRF_BUFFER_ADD(group_buf, _column);
3024 _column = searchFieldTransform(cname, field, selfield);
3031 } // end while -- iterating across SELECT columns
3033 jsonIteratorFree(select_itr);
3034 } // end while -- iterating across classes
3036 jsonIteratorFree(selclass_itr);
3038 //if (is_agg) jsonObjectFree(is_agg);
3042 char* col_list = buffer_release(select_buf);
3044 if (from_function) table = searchValueTransform(join_hash);
3045 else table = getSourceDefinition(core_meta);
3049 osrfAppSessionStatus(
3051 OSRF_STATUS_INTERNALSERVERERROR,
3052 "osrfMethodException",
3054 "Unable to identify table for core class"
3057 buffer_free( sql_buf );
3058 buffer_free( order_buf );
3059 buffer_free( group_buf );
3060 buffer_free( having_buf );
3061 if( defaultselhash ) jsonObjectFree( defaultselhash );
3066 // Put it all together
3067 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\" ", col_list, table, core_class );
3071 if (!from_function) {
3072 // Now, walk the join tree and add that clause
3074 char* join_clause = searchJOIN( join_hash, core_meta );
3076 buffer_add(sql_buf, join_clause);
3080 osrfAppSessionStatus(
3082 OSRF_STATUS_INTERNALSERVERERROR,
3083 "osrfMethodException",
3085 "Unable to construct JOIN clause(s)"
3087 buffer_free( sql_buf );
3088 buffer_free( order_buf );
3089 buffer_free( group_buf );
3090 buffer_free( having_buf );
3091 if( defaultselhash ) jsonObjectFree( defaultselhash );
3097 // Build a WHERE clause, if there is one
3098 if ( search_hash ) {
3099 buffer_add(sql_buf, " WHERE ");
3101 // and it's on the WHERE clause
3102 char* pred = searchWHERE( search_hash, core_meta, AND_OP_JOIN, ctx );
3105 buffer_add(sql_buf, pred);
3109 osrfAppSessionStatus(
3111 OSRF_STATUS_INTERNALSERVERERROR,
3112 "osrfMethodException",
3114 "Severe query error in WHERE predicate -- see error log for more details"
3118 buffer_free(having_buf);
3119 buffer_free(group_buf);
3120 buffer_free(order_buf);
3121 buffer_free(sql_buf);
3122 if (defaultselhash) jsonObjectFree(defaultselhash);
3127 // Build a HAVING clause, if there is one
3128 if ( having_hash ) {
3129 buffer_add(sql_buf, " HAVING ");
3131 // and it's on the the WHERE clause
3132 char* pred = searchWHERE( having_hash, core_meta, AND_OP_JOIN, ctx );
3135 buffer_add(sql_buf, pred);
3139 osrfAppSessionStatus(
3141 OSRF_STATUS_INTERNALSERVERERROR,
3142 "osrfMethodException",
3144 "Severe query error in HAVING predicate -- see error log for more details"
3148 buffer_free(having_buf);
3149 buffer_free(group_buf);
3150 buffer_free(order_buf);
3151 buffer_free(sql_buf);
3152 if (defaultselhash) jsonObjectFree(defaultselhash);
3157 // Build an ORDER BY clause, if there is one
3159 jsonIterator* class_itr = jsonNewIterator( order_hash );
3160 while ( (snode = jsonIteratorNext( class_itr )) ) {
3162 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
3165 if ( snode->type == JSON_HASH ) {
3167 jsonIterator* order_itr = jsonNewIterator( snode );
3168 while ( (onode = jsonIteratorNext( order_itr )) ) {
3170 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
3173 char* direction = NULL;
3174 if ( onode->type == JSON_HASH ) {
3175 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
3176 string = searchFieldTransform(
3178 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
3182 growing_buffer* field_buf = buffer_init(16);
3183 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
3184 string = buffer_release(field_buf);
3187 if ( (tmp_const = jsonObjectGetKeyConst( onode, "direction" )) ) {
3188 direction = jsonObjectToSimpleString(tmp_const);
3189 if (!strncasecmp(direction, "d", 1)) {
3191 direction = " DESC";
3199 string = strdup(order_itr->key);
3200 direction = jsonObjectToSimpleString(onode);
3201 if (!strncasecmp(direction, "d", 1)) {
3203 direction = " DESC";
3213 buffer_add(order_buf, ", ");
3216 buffer_add(order_buf, string);
3220 buffer_add(order_buf, direction);
3224 // jsonIteratorFree(order_itr);
3226 } else if ( snode->type == JSON_ARRAY ) {
3228 jsonIterator* order_itr = jsonNewIterator( snode );
3229 while ( (onode = jsonIteratorNext( order_itr )) ) {
3231 char* _f = jsonObjectToSimpleString( onode );
3233 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, _f))
3239 buffer_add(order_buf, ", ");
3242 buffer_add(order_buf, _f);
3246 // jsonIteratorFree(order_itr);
3249 // IT'S THE OOOOOOOOOOOLD STYLE!
3251 osrfLogError(OSRF_LOG_MARK, "%s: Possible SQL injection attempt; direct order by is not allowed", MODULENAME);
3253 osrfAppSessionStatus(
3255 OSRF_STATUS_INTERNALSERVERERROR,
3256 "osrfMethodException",
3258 "Severe query error -- see error log for more details"
3263 buffer_free(having_buf);
3264 buffer_free(group_buf);
3265 buffer_free(order_buf);
3266 buffer_free(sql_buf);
3267 if (defaultselhash) jsonObjectFree(defaultselhash);
3268 jsonIteratorFree(class_itr);
3273 // jsonIteratorFree(class_itr);
3277 string = buffer_release(group_buf);
3279 if ( *string && ( aggregate_found || (flags & SELECT_DISTINCT) ) ) {
3280 OSRF_BUFFER_ADD( sql_buf, " GROUP BY " );
3281 OSRF_BUFFER_ADD( sql_buf, string );
3286 string = buffer_release(having_buf);
3289 OSRF_BUFFER_ADD( sql_buf, " HAVING " );
3290 OSRF_BUFFER_ADD( sql_buf, string );
3295 string = buffer_release(order_buf);
3298 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
3299 OSRF_BUFFER_ADD( sql_buf, string );
3305 string = jsonObjectToSimpleString(limit);
3306 buffer_fadd( sql_buf, " LIMIT %d", atoi(string) );
3311 string = jsonObjectToSimpleString(offset);
3312 buffer_fadd( sql_buf, " OFFSET %d", atoi(string) );
3316 if (!(flags & SUBSELECT)) OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
3319 if (defaultselhash) jsonObjectFree(defaultselhash);
3321 return buffer_release(sql_buf);
3325 static char* buildSELECT ( jsonObject* search_hash, jsonObject* order_hash, osrfHash* meta, osrfMethodContext* ctx ) {
3327 const char* locale = osrf_message_get_last_locale();
3329 osrfHash* fields = osrfHashGet(meta, "fields");
3330 char* core_class = osrfHashGet(meta, "classname");
3332 const jsonObject* join_hash = jsonObjectGetKeyConst( order_hash, "join" );
3334 jsonObject* node = NULL;
3335 jsonObject* snode = NULL;
3336 jsonObject* onode = NULL;
3337 const jsonObject* _tmp = NULL;
3338 jsonObject* selhash = NULL;
3339 jsonObject* defaultselhash = NULL;
3341 growing_buffer* sql_buf = buffer_init(128);
3342 growing_buffer* select_buf = buffer_init(128);
3344 if ( !(selhash = jsonObjectGetKey( order_hash, "select" )) ) {
3345 defaultselhash = jsonNewObjectType(JSON_HASH);
3346 selhash = defaultselhash;
3349 if ( !jsonObjectGetKeyConst(selhash,core_class) ) {
3350 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
3351 jsonObject* flist = jsonObjectGetKey( selhash, core_class );
3356 osrfStringArray* keys = osrfHashKeys( fields );
3357 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
3358 if( ! str_is_true( osrfHashGet( osrfHashGet( fields, field ), "virtual" ) ) )
3359 jsonObjectPush( flist, jsonNewObject( field ) );
3361 osrfStringArrayFree(keys);
3365 jsonIterator* class_itr = jsonNewIterator( selhash );
3366 while ( (snode = jsonIteratorNext( class_itr )) ) {
3368 char* cname = class_itr->key;
3369 osrfHash* idlClass = osrfHashGet( oilsIDL(), cname );
3370 if (!idlClass) continue;
3372 if (strcmp(core_class,class_itr->key)) {
3373 if (!join_hash) continue;
3375 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", class_itr->key);
3377 jsonObjectFree(found);
3381 jsonObjectFree(found);
3384 jsonIterator* select_itr = jsonNewIterator( snode );
3385 while ( (node = jsonIteratorNext( select_itr )) ) {
3386 char* item_str = jsonObjectToSimpleString(node);
3387 osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), item_str );
3389 char* fname = osrfHashGet(field, "name");
3391 if (!field) continue;
3396 OSRF_BUFFER_ADD_CHAR(select_buf, ',');
3401 const jsonObject* no_i18n_obj = jsonObjectGetKey( order_hash, "no_i18n" );
3402 if ( obj_is_true( no_i18n_obj ) ) // Suppress internationalization?
3405 i18n = osrfHashGet(field, "i18n");
3407 if( str_is_true( i18n ) ) {
3408 char* pkey = osrfHashGet(idlClass, "primarykey");
3409 char* tname = osrfHashGet(idlClass, "tablename");
3411 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);
3413 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
3416 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
3420 jsonIteratorFree(select_itr);
3423 jsonIteratorFree(class_itr);
3425 char* col_list = buffer_release(select_buf);
3426 char* table = getSourceDefinition(meta);
3428 table = strdup( "(null)" );
3430 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\"", col_list, table, core_class );
3435 char* join_clause = searchJOIN( join_hash, meta );
3436 OSRF_BUFFER_ADD_CHAR(sql_buf, ' ');
3437 OSRF_BUFFER_ADD(sql_buf, join_clause);
3441 osrfLogDebug(OSRF_LOG_MARK, "%s pre-predicate SQL = %s",
3442 MODULENAME, OSRF_BUFFER_C_STR(sql_buf));
3444 buffer_add(sql_buf, " WHERE ");
3446 char* pred = searchWHERE( search_hash, meta, AND_OP_JOIN, ctx );
3448 osrfAppSessionStatus(
3450 OSRF_STATUS_INTERNALSERVERERROR,
3451 "osrfMethodException",
3453 "Severe query error -- see error log for more details"
3455 buffer_free(sql_buf);
3456 if(defaultselhash) jsonObjectFree(defaultselhash);
3459 buffer_add(sql_buf, pred);
3464 char* string = NULL;
3465 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "order_by" )) ){
3467 growing_buffer* order_buf = buffer_init(128);
3470 jsonIterator* class_itr = jsonNewIterator( _tmp );
3471 while ( (snode = jsonIteratorNext( class_itr )) ) {
3473 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
3476 if ( snode->type == JSON_HASH ) {
3478 jsonIterator* order_itr = jsonNewIterator( snode );
3479 while ( (onode = jsonIteratorNext( order_itr )) ) {
3481 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
3484 char* direction = NULL;
3485 if ( onode->type == JSON_HASH ) {
3486 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
3487 string = searchFieldTransform(
3489 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
3493 growing_buffer* field_buf = buffer_init(16);
3494 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
3495 string = buffer_release(field_buf);
3498 if ( (_tmp = jsonObjectGetKeyConst( onode, "direction" )) ) {
3499 direction = jsonObjectToSimpleString(_tmp);
3500 if (!strncasecmp(direction, "d", 1)) {
3502 direction = " DESC";
3510 string = strdup(order_itr->key);
3511 direction = jsonObjectToSimpleString(onode);
3512 if (!strncasecmp(direction, "d", 1)) {
3514 direction = " DESC";
3524 buffer_add(order_buf, ", ");
3527 buffer_add(order_buf, string);
3531 buffer_add(order_buf, direction);
3536 jsonIteratorFree(order_itr);
3539 string = jsonObjectToSimpleString(snode);
3540 buffer_add(order_buf, string);
3547 jsonIteratorFree(class_itr);
3549 string = buffer_release(order_buf);
3552 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
3553 OSRF_BUFFER_ADD( sql_buf, string );
3559 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "limit" )) ){
3560 string = jsonObjectToSimpleString(_tmp);
3569 _tmp = jsonObjectGetKeyConst( order_hash, "offset" );
3571 string = jsonObjectToSimpleString(_tmp);
3581 if (defaultselhash) jsonObjectFree(defaultselhash);
3583 OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
3584 return buffer_release(sql_buf);
3587 int doJSONSearch ( osrfMethodContext* ctx ) {
3588 if(osrfMethodVerifyContext( ctx )) {
3589 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
3593 osrfLogDebug(OSRF_LOG_MARK, "Recieved query request");
3598 dbhandle = writehandle;
3600 jsonObject* hash = jsonObjectGetIndex(ctx->params, 0);
3604 if ( obj_is_true( jsonObjectGetKey( hash, "distinct" ) ) )
3605 flags |= SELECT_DISTINCT;
3607 if ( obj_is_true( jsonObjectGetKey( hash, "no_i18n" ) ) )
3608 flags |= DISABLE_I18N;
3610 osrfLogDebug(OSRF_LOG_MARK, "Building SQL ...");
3613 jsonObjectGetKey( hash, "select" ),
3614 jsonObjectGetKey( hash, "from" ),
3615 jsonObjectGetKey( hash, "where" ),
3616 jsonObjectGetKey( hash, "having" ),
3617 jsonObjectGetKey( hash, "order_by" ),
3618 jsonObjectGetKey( hash, "limit" ),
3619 jsonObjectGetKey( hash, "offset" ),
3628 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3629 dbi_result result = dbi_conn_query(dbhandle, sql);
3632 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3634 if (dbi_result_first_row(result)) {
3635 /* JSONify the result */
3636 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3639 jsonObject* return_val = oilsMakeJSONFromResult( result );
3640 osrfAppRespond( ctx, return_val );
3641 jsonObjectFree( return_val );
3642 } while (dbi_result_next_row(result));
3645 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
3648 osrfAppRespondComplete( ctx, NULL );
3650 /* clean up the query */
3651 dbi_result_free(result);
3655 osrfLogError(OSRF_LOG_MARK, "%s: Error with query [%s]", MODULENAME, sql);
3656 osrfAppSessionStatus(
3658 OSRF_STATUS_INTERNALSERVERERROR,
3659 "osrfMethodException",
3661 "Severe query error -- see error log for more details"
3669 static jsonObject* doFieldmapperSearch ( osrfMethodContext* ctx, osrfHash* meta,
3670 const jsonObject* params, int* err ) {
3673 dbhandle = writehandle;
3675 osrfHash* links = osrfHashGet(meta, "links");
3676 osrfHash* fields = osrfHashGet(meta, "fields");
3677 char* core_class = osrfHashGet(meta, "classname");
3678 char* pkey = osrfHashGet(meta, "primarykey");
3680 const jsonObject* _tmp;
3682 jsonObject* search_hash = jsonObjectGetIndex(params, 0);
3683 jsonObject* order_hash = jsonObjectGetIndex(params, 1);
3685 char* sql = buildSELECT( search_hash, order_hash, meta, ctx );
3687 osrfLogDebug(OSRF_LOG_MARK, "Problem building query, returning NULL");
3692 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3694 dbi_result result = dbi_conn_query(dbhandle, sql);
3695 if( NULL == result ) {
3696 osrfLogError(OSRF_LOG_MARK, "%s: Error retrieving %s with query [%s]",
3697 MODULENAME, osrfHashGet(meta, "fieldmapper"), sql);
3698 osrfAppSessionStatus(
3700 OSRF_STATUS_INTERNALSERVERERROR,
3701 "osrfMethodException",
3703 "Severe query error -- see error log for more details"
3710 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3713 jsonObject* res_list = jsonNewObjectType(JSON_ARRAY);
3714 osrfHash* dedup = osrfNewHash();
3716 if (dbi_result_first_row(result)) {
3717 /* JSONify the result */
3718 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3720 obj = oilsMakeFieldmapperFromResult( result, meta );
3721 char* pkey_val = oilsFMGetString( obj, pkey );
3722 if ( osrfHashGet( dedup, pkey_val ) ) {
3723 jsonObjectFree(obj);
3726 osrfHashSet( dedup, pkey_val, pkey_val );
3727 jsonObjectPush(res_list, obj);
3729 } while (dbi_result_next_row(result));
3731 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s",
3735 osrfHashFree(dedup);
3736 /* clean up the query */
3737 dbi_result_free(result);
3740 if (res_list->size && order_hash) {
3741 _tmp = jsonObjectGetKeyConst( order_hash, "flesh" );
3743 int x = (int)jsonObjectGetNumber(_tmp);
3744 if (x == -1 || x > max_flesh_depth) x = max_flesh_depth;
3746 const jsonObject* temp_blob;
3747 if ((temp_blob = jsonObjectGetKeyConst( order_hash, "flesh_fields" )) && x > 0) {
3749 jsonObject* flesh_blob = jsonObjectClone( temp_blob );
3750 const jsonObject* flesh_fields = jsonObjectGetKeyConst( flesh_blob, core_class );
3752 osrfStringArray* link_fields = NULL;
3755 if (flesh_fields->size == 1) {
3756 char* _t = jsonObjectToSimpleString( jsonObjectGetIndex( flesh_fields, 0 ) );
3757 if (!strcmp(_t,"*")) link_fields = osrfHashKeys( links );
3763 link_fields = osrfNewStringArray(1);
3764 jsonIterator* _i = jsonNewIterator( flesh_fields );
3765 while ((_f = jsonIteratorNext( _i ))) {
3766 osrfStringArrayAdd( link_fields, jsonObjectToSimpleString( _f ) );
3768 jsonIteratorFree(_i);
3773 jsonIterator* itr = jsonNewIterator( res_list );
3774 while ((cur = jsonIteratorNext( itr ))) {
3779 while ( (link_field = osrfStringArrayGetString(link_fields, i++)) ) {
3781 osrfLogDebug(OSRF_LOG_MARK, "Starting to flesh %s", link_field);
3783 osrfHash* kid_link = osrfHashGet(links, link_field);
3784 if (!kid_link) continue;
3786 osrfHash* field = osrfHashGet(fields, link_field);
3787 if (!field) continue;
3789 osrfHash* value_field = field;
3791 osrfHash* kid_idl = osrfHashGet(oilsIDL(), osrfHashGet(kid_link, "class"));
3792 if (!kid_idl) continue;
3794 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3795 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3798 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) { // might_have
3799 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3802 osrfStringArray* link_map = osrfHashGet( kid_link, "map" );
3804 if (link_map->size > 0) {
3805 jsonObject* _kid_key = jsonNewObjectType(JSON_ARRAY);
3808 jsonNewObject( osrfStringArrayGetString( link_map, 0 ) )
3813 osrfHashGet(kid_link, "class"),
3820 "Link field: %s, remote class: %s, fkey: %s, reltype: %s",
3821 osrfHashGet(kid_link, "field"),
3822 osrfHashGet(kid_link, "class"),
3823 osrfHashGet(kid_link, "key"),
3824 osrfHashGet(kid_link, "reltype")
3827 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
3828 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // search hash
3829 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // order/flesh hash
3831 osrfLogDebug(OSRF_LOG_MARK, "Creating dummy params object...");
3834 jsonObjectToSimpleString(
3837 atoi( osrfHashGet(value_field, "array_position") )
3842 osrfLogDebug(OSRF_LOG_MARK, "Nothing to search for!");
3847 jsonObjectGetIndex(fake_params, 0),
3848 osrfHashGet(kid_link, "key"),
3849 jsonNewObject( search_key )
3856 jsonObjectGetIndex(fake_params, 1),
3858 jsonNewNumberObject( (double)(x - 1 + link_map->size) )
3862 jsonObjectSetKey( jsonObjectGetIndex(fake_params, 1), "flesh_fields", jsonObjectClone(flesh_blob) );
3864 if (jsonObjectGetKeyConst(order_hash, "order_by")) {
3866 jsonObjectGetIndex(fake_params, 1),
3868 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "order_by"))
3872 if (jsonObjectGetKeyConst(order_hash, "select")) {
3874 jsonObjectGetIndex(fake_params, 1),
3876 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "select"))
3880 jsonObject* kids = doFieldmapperSearch(ctx, kid_idl, fake_params, err);
3883 jsonObjectFree( fake_params );
3884 osrfStringArrayFree(link_fields);
3885 jsonIteratorFree(itr);
3886 jsonObjectFree(res_list);
3887 jsonObjectFree(flesh_blob);
3891 osrfLogDebug(OSRF_LOG_MARK, "Search for %s return %d linked objects", osrfHashGet(kid_link, "class"), kids->size);
3893 jsonObject* X = NULL;
3894 if ( link_map->size > 0 && kids->size > 0 ) {
3896 kids = jsonNewObjectType(JSON_ARRAY);
3898 jsonObject* _k_node;
3899 jsonIterator* _k = jsonNewIterator( X );
3900 while ((_k_node = jsonIteratorNext( _k ))) {
3906 (unsigned long)atoi(
3912 osrfHashGet(kid_link, "class")
3916 osrfStringArrayGetString( link_map, 0 )
3925 jsonIteratorFree(_k);
3928 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_a" )) || !(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) {
3929 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3932 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3933 jsonObjectClone( jsonObjectGetIndex(kids, 0) )
3937 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3938 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3941 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3942 jsonObjectClone( kids )
3947 jsonObjectFree(kids);
3951 jsonObjectFree( kids );
3952 jsonObjectFree( fake_params );
3954 osrfLogDebug(OSRF_LOG_MARK, "Fleshing of %s complete", osrfHashGet(kid_link, "field"));
3955 osrfLogDebug(OSRF_LOG_MARK, "%s", jsonObjectToJSON(cur));
3959 jsonObjectFree( flesh_blob );
3960 osrfStringArrayFree(link_fields);
3961 jsonIteratorFree(itr);
3970 static jsonObject* doUpdate(osrfMethodContext* ctx, int* err ) {
3972 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3974 jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
3976 jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
3979 if (!verifyObjectClass(ctx, target)) {
3984 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3985 osrfAppSessionStatus(
3987 OSRF_STATUS_BADREQUEST,
3988 "osrfMethodException",
3990 "No active transaction -- required for UPDATE"
3996 // The following test is harmless but redundant. If a class is
3997 // readonly, we don't register an update method for it.
3998 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
3999 osrfAppSessionStatus(
4001 OSRF_STATUS_BADREQUEST,
4002 "osrfMethodException",
4004 "Cannot UPDATE readonly class"
4010 dbhandle = writehandle;
4012 char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
4014 // Set the last_xact_id
4015 int index = oilsIDL_ntop( target->classname, "last_xact_id" );
4017 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
4018 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
4021 char* pkey = osrfHashGet(meta, "primarykey");
4022 osrfHash* fields = osrfHashGet(meta, "fields");
4024 char* id = oilsFMGetString( target, pkey );
4028 "%s updating %s object with %s = %s",
4030 osrfHashGet(meta, "fieldmapper"),
4035 growing_buffer* sql = buffer_init(128);
4036 buffer_fadd(sql,"UPDATE %s SET", osrfHashGet(meta, "tablename"));
4041 osrfStringArray* field_list = osrfHashKeys( fields );
4042 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
4044 osrfHash* field = osrfHashGet( fields, field_name );
4046 if(!( strcmp( field_name, pkey ) )) continue;
4047 if( str_is_true( osrfHashGet(osrfHashGet(fields,field_name), "virtual") ) )
4050 const jsonObject* field_object = oilsFMGetObject( target, field_name );
4053 if (field_object && field_object->classname) {
4054 value = oilsFMGetString(
4056 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
4059 value = jsonObjectToSimpleString( field_object );
4062 osrfLogDebug( OSRF_LOG_MARK, "Updating %s object with %s = %s", osrfHashGet(meta, "fieldmapper"), field_name, value);
4064 if (!field_object || field_object->type == JSON_NULL) {
4065 if ( !(!( strcmp( osrfHashGet(meta, "classname"), "au" ) ) && !( strcmp( field_name, "passwd" ) )) ) { // arg at the special case!
4066 if (first) first = 0;
4067 else OSRF_BUFFER_ADD_CHAR(sql, ',');
4068 buffer_fadd( sql, " %s = NULL", field_name );
4071 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
4072 if (first) first = 0;
4073 else OSRF_BUFFER_ADD_CHAR(sql, ',');
4075 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
4076 buffer_fadd( sql, " %s = %ld", field_name, atol(value) );
4077 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
4078 buffer_fadd( sql, " %s = %f", field_name, atof(value) );
4081 osrfLogDebug( OSRF_LOG_MARK, "%s is of type %s", field_name, osrfHashGet(field, "datatype"));
4084 if ( dbi_conn_quote_string(dbhandle, &value) ) {
4085 if (first) first = 0;
4086 else OSRF_BUFFER_ADD_CHAR(sql, ',');
4087 buffer_fadd( sql, " %s = %s", field_name, value );
4090 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
4091 osrfAppSessionStatus(
4093 OSRF_STATUS_INTERNALSERVERERROR,
4094 "osrfMethodException",
4096 "Error quoting string -- please see the error log for more details"
4110 jsonObject* obj = jsonNewObject(id);
4112 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
4113 dbi_conn_quote_string(dbhandle, &id);
4115 buffer_fadd( sql, " WHERE %s = %s;", pkey, id );
4117 char* query = buffer_release(sql);
4118 osrfLogDebug(OSRF_LOG_MARK, "%s: Update SQL [%s]", MODULENAME, query);
4120 dbi_result result = dbi_conn_query(dbhandle, query);
4124 jsonObjectFree(obj);
4125 obj = jsonNewObject(NULL);
4128 "%s ERROR updating %s object with %s = %s",
4130 osrfHashGet(meta, "fieldmapper"),
4141 static jsonObject* doDelete(osrfMethodContext* ctx, int* err ) {
4143 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
4145 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
4146 osrfAppSessionStatus(
4148 OSRF_STATUS_BADREQUEST,
4149 "osrfMethodException",
4151 "No active transaction -- required for DELETE"
4157 // The following test is harmless but redundant. If a class is
4158 // readonly, we don't register a delete method for it.
4159 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
4160 osrfAppSessionStatus(
4162 OSRF_STATUS_BADREQUEST,
4163 "osrfMethodException",
4165 "Cannot DELETE readonly class"
4171 dbhandle = writehandle;
4175 char* pkey = osrfHashGet(meta, "primarykey");
4183 if (jsonObjectGetIndex(ctx->params, _obj_pos)->classname) {
4184 if (!verifyObjectClass(ctx, jsonObjectGetIndex( ctx->params, _obj_pos ))) {
4189 id = oilsFMGetString( jsonObjectGetIndex(ctx->params, _obj_pos), pkey );
4192 if (!verifyObjectPCRUD( ctx, NULL )) {
4197 id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, _obj_pos));
4202 "%s deleting %s object with %s = %s",
4204 osrfHashGet(meta, "fieldmapper"),
4209 obj = jsonNewObject(id);
4211 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
4212 dbi_conn_quote_string(writehandle, &id);
4214 dbi_result result = dbi_conn_queryf(writehandle, "DELETE FROM %s WHERE %s = %s;", osrfHashGet(meta, "tablename"), pkey, id);
4217 jsonObjectFree(obj);
4218 obj = jsonNewObject(NULL);
4221 "%s ERROR deleting %s object with %s = %s",
4223 osrfHashGet(meta, "fieldmapper"),
4236 static jsonObject* oilsMakeFieldmapperFromResult( dbi_result result, osrfHash* meta) {
4237 if(!(result && meta)) return jsonNULL;
4239 jsonObject* object = jsonNewObject(NULL);
4240 jsonObjectSetClass(object, osrfHashGet(meta, "classname"));
4242 osrfHash* fields = osrfHashGet(meta, "fields");
4244 osrfLogInternal(OSRF_LOG_MARK, "Setting object class to %s ", object->classname);
4248 char dt_string[256];
4252 int columnIndex = 1;
4254 unsigned short type;
4255 const char* columnName;
4257 /* cycle through the column list */
4258 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
4260 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
4262 fmIndex = -1; // reset the position
4264 /* determine the field type and storage attributes */
4265 type = dbi_result_get_field_type(result, columnName);
4266 attr = dbi_result_get_field_attribs(result, columnName);
4268 /* fetch the fieldmapper index */
4269 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
4271 if ( str_is_true( osrfHashGet(_f, "virtual") ) )
4274 const char* pos = (char*)osrfHashGet(_f, "array_position");
4275 if ( !pos ) continue;
4277 fmIndex = atoi( pos );
4278 osrfLogInternal(OSRF_LOG_MARK, "... Found column at position [%s]...", pos);
4283 if (dbi_result_field_is_null(result, columnName)) {
4284 jsonObjectSetIndex( object, fmIndex, jsonNewObject(NULL) );
4289 case DBI_TYPE_INTEGER :
4291 if( attr & DBI_INTEGER_SIZE8 )
4292 jsonObjectSetIndex( object, fmIndex,
4293 jsonNewNumberObject(dbi_result_get_longlong(result, columnName)));
4295 jsonObjectSetIndex( object, fmIndex,
4296 jsonNewNumberObject(dbi_result_get_int(result, columnName)));
4300 case DBI_TYPE_DECIMAL :
4301 jsonObjectSetIndex( object, fmIndex,
4302 jsonNewNumberObject(dbi_result_get_double(result, columnName)));
4305 case DBI_TYPE_STRING :
4311 jsonNewObject( dbi_result_get_string(result, columnName) )
4316 case DBI_TYPE_DATETIME :
4318 memset(dt_string, '\0', sizeof(dt_string));
4319 memset(&gmdt, '\0', sizeof(gmdt));
4321 _tmp_dt = dbi_result_get_datetime(result, columnName);
4324 if (!(attr & DBI_DATETIME_DATE)) {
4325 gmtime_r( &_tmp_dt, &gmdt );
4326 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
4327 } else if (!(attr & DBI_DATETIME_TIME)) {
4328 localtime_r( &_tmp_dt, &gmdt );
4329 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
4331 localtime_r( &_tmp_dt, &gmdt );
4332 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
4335 jsonObjectSetIndex( object, fmIndex, jsonNewObject(dt_string) );
4339 case DBI_TYPE_BINARY :
4340 osrfLogError( OSRF_LOG_MARK,
4341 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
4349 static jsonObject* oilsMakeJSONFromResult( dbi_result result ) {
4350 if(!result) return jsonNULL;
4352 jsonObject* object = jsonNewObject(NULL);
4355 char dt_string[256];
4359 int columnIndex = 1;
4361 unsigned short type;
4362 const char* columnName;
4364 /* cycle through the column list */
4365 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
4367 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
4369 fmIndex = -1; // reset the position
4371 /* determine the field type and storage attributes */
4372 type = dbi_result_get_field_type(result, columnName);
4373 attr = dbi_result_get_field_attribs(result, columnName);
4375 if (dbi_result_field_is_null(result, columnName)) {
4376 jsonObjectSetKey( object, columnName, jsonNewObject(NULL) );
4381 case DBI_TYPE_INTEGER :
4383 if( attr & DBI_INTEGER_SIZE8 )
4384 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_longlong(result, columnName)) );
4386 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_int(result, columnName)) );
4389 case DBI_TYPE_DECIMAL :
4390 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_double(result, columnName)) );
4393 case DBI_TYPE_STRING :
4394 jsonObjectSetKey( object, columnName, jsonNewObject(dbi_result_get_string(result, columnName)) );
4397 case DBI_TYPE_DATETIME :
4399 memset(dt_string, '\0', sizeof(dt_string));
4400 memset(&gmdt, '\0', sizeof(gmdt));
4402 _tmp_dt = dbi_result_get_datetime(result, columnName);
4405 if (!(attr & DBI_DATETIME_DATE)) {
4406 gmtime_r( &_tmp_dt, &gmdt );
4407 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
4408 } else if (!(attr & DBI_DATETIME_TIME)) {
4409 localtime_r( &_tmp_dt, &gmdt );
4410 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
4412 localtime_r( &_tmp_dt, &gmdt );
4413 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
4416 jsonObjectSetKey( object, columnName, jsonNewObject(dt_string) );
4419 case DBI_TYPE_BINARY :
4420 osrfLogError( OSRF_LOG_MARK,
4421 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
4429 // Interpret a string as true or false
4430 static int str_is_true( const char* str ) {
4431 if( NULL == str || strcasecmp( str, "true" ) )
4437 // Interpret a jsonObject as true or false
4438 static int obj_is_true( const jsonObject* obj ) {
4441 else switch( obj->type )
4449 if( strcasecmp( obj->value.s, "true" ) )
4453 case JSON_NUMBER : // Support 1/0 for perl's sake
4454 if( jsonObjectGetNumber( obj ) == 1.0 )
4463 // Translate a numeric code into a text string identifying a type of
4464 // jsonObject. To be used for building error messages.
4465 static const char* json_type( int code ) {
4471 return "JSON_ARRAY";
4473 return "JSON_STRING";
4475 return "JSON_NUMBER";
4481 return "(unrecognized)";