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*, const jsonObject*, const char* );
65 static char* searchPredicate ( const char*, osrfHash*, jsonObject* );
66 static char* searchJOIN ( const jsonObject*, osrfHash* );
67 static char* searchWHERE ( const jsonObject*, osrfHash*, int, osrfMethodContext* );
68 static char* buildSELECT ( jsonObject*, jsonObject*, osrfHash*, osrfMethodContext* );
70 static char* SELECT ( osrfMethodContext*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, int );
72 void userDataFree( void* );
73 static void sessionDataFree( char*, void* );
74 static char* getSourceDefinition( osrfHash* );
75 static int str_is_true( const char* str );
76 static int obj_is_true( const jsonObject* obj );
79 static jsonObject* verifyUserPCRUD( osrfMethodContext* );
80 static int verifyObjectPCRUD( osrfMethodContext*, const jsonObject* );
83 static dbi_conn writehandle; /* our MASTER db connection */
84 static dbi_conn dbhandle; /* our CURRENT db connection */
85 //static osrfHash * readHandles;
86 static jsonObject* jsonNULL = NULL; //
87 static int max_flesh_depth = 100;
89 /* called when this process is about to exit */
90 void osrfAppChildExit() {
91 osrfLogDebug(OSRF_LOG_MARK, "Child is exiting, disconnecting from database...");
94 if (writehandle == dbhandle) same = 1;
96 dbi_conn_query(writehandle, "ROLLBACK;");
97 dbi_conn_close(writehandle);
100 if (dbhandle && !same)
101 dbi_conn_close(dbhandle);
103 // XXX add cleanup of readHandles whenever that gets used
108 int osrfAppInitialize() {
110 osrfLogInfo(OSRF_LOG_MARK, "Initializing the CStore Server...");
111 osrfLogInfo(OSRF_LOG_MARK, "Finding XML file...");
113 if (!oilsIDLInit( osrf_settings_host_value("/IDL") )) return 1; /* return non-zero to indicate error */
115 growing_buffer* method_name = buffer_init(64);
117 // Generic search thingy
118 buffer_add(method_name, MODULENAME);
119 buffer_add(method_name, ".json_query");
120 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
121 "doJSONSearch", "", 1, OSRF_METHOD_STREAMING );
124 // first we register all the transaction and savepoint methods
125 buffer_reset(method_name);
126 OSRF_BUFFER_ADD(method_name, MODULENAME);
127 OSRF_BUFFER_ADD(method_name, ".transaction.begin");
128 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
129 "beginTransaction", "", 0, 0 );
131 buffer_reset(method_name);
132 OSRF_BUFFER_ADD(method_name, MODULENAME);
133 OSRF_BUFFER_ADD(method_name, ".transaction.commit");
134 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
135 "commitTransaction", "", 0, 0 );
137 buffer_reset(method_name);
138 OSRF_BUFFER_ADD(method_name, MODULENAME);
139 OSRF_BUFFER_ADD(method_name, ".transaction.rollback");
140 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
141 "rollbackTransaction", "", 0, 0 );
143 buffer_reset(method_name);
144 OSRF_BUFFER_ADD(method_name, MODULENAME);
145 OSRF_BUFFER_ADD(method_name, ".savepoint.set");
146 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
147 "setSavepoint", "", 1, 0 );
149 buffer_reset(method_name);
150 OSRF_BUFFER_ADD(method_name, MODULENAME);
151 OSRF_BUFFER_ADD(method_name, ".savepoint.release");
152 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
153 "releaseSavepoint", "", 1, 0 );
155 buffer_reset(method_name);
156 OSRF_BUFFER_ADD(method_name, MODULENAME);
157 OSRF_BUFFER_ADD(method_name, ".savepoint.rollback");
158 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
159 "rollbackSavepoint", "", 1, 0 );
161 buffer_free(method_name);
163 static const char* global_method[] = {
171 const int global_method_count
172 = sizeof( global_method ) / sizeof ( global_method[0] );
176 osrfStringArray* classes = osrfHashKeys( oilsIDL() );
177 osrfLogDebug(OSRF_LOG_MARK, "%d classes loaded", classes->size );
178 osrfLogDebug(OSRF_LOG_MARK,
179 "At least %d methods will be generated", classes->size * global_method_count);
181 while ( (classname = osrfStringArrayGetString(classes, c_index++)) ) {
182 osrfLogInfo(OSRF_LOG_MARK, "Generating class methods for %s", classname);
184 osrfHash* idlClass = osrfHashGet(oilsIDL(), classname);
186 if (!osrfStringArrayContains( osrfHashGet(idlClass, "controller"), MODULENAME )) {
187 osrfLogInfo(OSRF_LOG_MARK, "%s is not listed as a controller for %s, moving on", MODULENAME, classname);
191 if ( str_is_true( osrfHashGet(idlClass, "virtual") ) ) {
192 osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
196 // Look up some other attributes of the current class
197 const char* idlClass_fieldmapper = osrfHashGet(idlClass, "fieldmapper");
198 const char* readonly = osrfHashGet(idlClass, "readonly");
200 osrfHash* idlClass_permacrud = osrfHashGet(idlClass, "permacrud");
204 for( i = 0; i < global_method_count; ++i ) {
205 const char* method_type = global_method[ i ];
206 osrfLogDebug(OSRF_LOG_MARK,
207 "Using files to build %s class methods for %s", method_type, classname);
209 if (!idlClass_fieldmapper) continue;
212 if (!idlClass_permacrud) continue;
214 const char* tmp_method = method_type;
215 if ( *tmp_method == 'i' || *tmp_method == 's') {
216 tmp_method = "retrieve";
218 if (!osrfHashGet( idlClass_permacrud, tmp_method )) continue;
221 if ( str_is_true( readonly ) &&
222 ( *method_type == 'c' || *method_type == 'u' || *method_type == 'd')
225 osrfHash* method_meta = osrfNewHash();
226 osrfHashSet(method_meta, idlClass, "class");
228 method_name = buffer_init(64);
230 buffer_fadd(method_name, "%s.%s.%s", MODULENAME, method_type, classname);
234 char* _fm = strdup( idlClass_fieldmapper );
235 part = strtok_r(_fm, ":", &st_tmp);
237 buffer_fadd(method_name, "%s.direct.%s", MODULENAME, part);
239 while ((part = strtok_r(NULL, ":", &st_tmp))) {
240 OSRF_BUFFER_ADD_CHAR(method_name, '.');
241 OSRF_BUFFER_ADD(method_name, part);
243 OSRF_BUFFER_ADD_CHAR(method_name, '.');
244 OSRF_BUFFER_ADD(method_name, method_type);
248 char* method = buffer_release(method_name);
250 osrfHashSet( method_meta, method, "methodname" );
251 osrfHashSet( method_meta, strdup(method_type), "methodtype" );
254 if (*method_type == 'i' || *method_type == 's') {
255 flags = flags | OSRF_METHOD_STREAMING;
258 osrfAppRegisterExtendedMethod(
261 "dispatchCRUDMethod",
275 static char* getSourceDefinition( osrfHash* class ) {
277 char* tabledef = osrfHashGet(class, "tablename");
280 growing_buffer* tablebuf = buffer_init(128);
281 tabledef = osrfHashGet(class, "source_definition");
284 buffer_fadd( tablebuf, "(%s)", tabledef );
285 tabledef = buffer_release(tablebuf);
287 tabledef = strdup(tabledef);
294 * Connects to the database
296 int osrfAppChildInit() {
298 osrfLogDebug(OSRF_LOG_MARK, "Attempting to initialize libdbi...");
299 dbi_initialize(NULL);
300 osrfLogDebug(OSRF_LOG_MARK, "... libdbi initialized.");
302 char* driver = osrf_settings_host_value("/apps/%s/app_settings/driver", MODULENAME);
303 char* user = osrf_settings_host_value("/apps/%s/app_settings/database/user", MODULENAME);
304 char* host = osrf_settings_host_value("/apps/%s/app_settings/database/host", MODULENAME);
305 char* port = osrf_settings_host_value("/apps/%s/app_settings/database/port", MODULENAME);
306 char* db = osrf_settings_host_value("/apps/%s/app_settings/database/db", MODULENAME);
307 char* pw = osrf_settings_host_value("/apps/%s/app_settings/database/pw", MODULENAME);
308 char* md = osrf_settings_host_value("/apps/%s/app_settings/max_query_recursion", MODULENAME);
310 osrfLogDebug(OSRF_LOG_MARK, "Attempting to load the database driver [%s]...", driver);
311 writehandle = dbi_conn_new(driver);
314 osrfLogError(OSRF_LOG_MARK, "Error loading database driver [%s]", driver);
317 osrfLogDebug(OSRF_LOG_MARK, "Database driver [%s] seems OK", driver);
319 osrfLogInfo(OSRF_LOG_MARK, "%s connecting to database. host=%s, "
320 "port=%s, user=%s, pw=%s, db=%s", MODULENAME, host, port, user, pw, db );
322 if(host) dbi_conn_set_option(writehandle, "host", host );
323 if(port) dbi_conn_set_option_numeric( writehandle, "port", atoi(port) );
324 if(user) dbi_conn_set_option(writehandle, "username", user);
325 if(pw) dbi_conn_set_option(writehandle, "password", pw );
326 if(db) dbi_conn_set_option(writehandle, "dbname", db );
328 if(md) max_flesh_depth = atoi(md);
329 if(max_flesh_depth < 0) max_flesh_depth = 1;
330 if(max_flesh_depth > 1000) max_flesh_depth = 1000;
339 if (dbi_conn_connect(writehandle) < 0) {
341 if (dbi_conn_connect(writehandle) < 0) {
342 dbi_conn_error(writehandle, &err);
343 osrfLogError( OSRF_LOG_MARK, "Error connecting to database: %s", err);
348 osrfLogInfo(OSRF_LOG_MARK, "%s successfully connected to the database", MODULENAME);
354 osrfStringArray* classes = osrfHashKeys( oilsIDL() );
356 while ( (classname = osrfStringArrayGetString(classes, i++)) ) {
357 osrfHash* class = osrfHashGet( oilsIDL(), classname );
358 osrfHash* fields = osrfHashGet( class, "fields" );
360 if( str_is_true( osrfHashGet(class, "virtual") ) ) {
361 osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
365 char* tabledef = getSourceDefinition(class);
367 growing_buffer* sql_buf = buffer_init(32);
368 buffer_fadd( sql_buf, "SELECT * FROM %s AS x WHERE 1=0;", tabledef );
372 char* sql = buffer_release(sql_buf);
373 osrfLogDebug(OSRF_LOG_MARK, "%s Investigatory SQL = %s", MODULENAME, sql);
375 dbi_result result = dbi_conn_query(writehandle, sql);
381 const char* columnName;
383 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
385 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
387 /* fetch the fieldmapper index */
388 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
390 osrfLogDebug(OSRF_LOG_MARK, "Found [%s] in IDL hash...", (char*)columnName);
392 /* determine the field type and storage attributes */
393 type = dbi_result_get_field_type(result, columnName);
394 attr = dbi_result_get_field_attribs(result, columnName);
398 case DBI_TYPE_INTEGER :
400 if ( !osrfHashGet(_f, "primitive") )
401 osrfHashSet(_f,"number", "primitive");
403 if( attr & DBI_INTEGER_SIZE8 )
404 osrfHashSet(_f,"INT8", "datatype");
406 osrfHashSet(_f,"INT", "datatype");
409 case DBI_TYPE_DECIMAL :
410 if ( !osrfHashGet(_f, "primitive") )
411 osrfHashSet(_f,"number", "primitive");
413 osrfHashSet(_f,"NUMERIC", "datatype");
416 case DBI_TYPE_STRING :
417 if ( !osrfHashGet(_f, "primitive") )
418 osrfHashSet(_f,"string", "primitive");
419 osrfHashSet(_f,"TEXT", "datatype");
422 case DBI_TYPE_DATETIME :
423 if ( !osrfHashGet(_f, "primitive") )
424 osrfHashSet(_f,"string", "primitive");
426 osrfHashSet(_f,"TIMESTAMP", "datatype");
429 case DBI_TYPE_BINARY :
430 if ( !osrfHashGet(_f, "primitive") )
431 osrfHashSet(_f,"string", "primitive");
433 osrfHashSet(_f,"BYTEA", "datatype");
438 "Setting [%s] to primitive [%s] and datatype [%s]...",
440 osrfHashGet(_f, "primitive"),
441 osrfHashGet(_f, "datatype")
445 dbi_result_free(result);
447 osrfLogDebug(OSRF_LOG_MARK, "No data found for class [%s]...", (char*)classname);
451 osrfStringArrayFree(classes);
456 void userDataFree( void* blob ) {
457 osrfHashFree( (osrfHash*)blob );
461 static void sessionDataFree( char* key, void* item ) {
462 if (!(strcmp(key,"xact_id"))) {
464 dbi_conn_query(writehandle, "ROLLBACK;");
471 int beginTransaction ( osrfMethodContext* ctx ) {
472 if(osrfMethodVerifyContext( ctx )) {
473 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
478 jsonObject* user = verifyUserPCRUD( ctx );
479 if (!user) return -1;
480 jsonObjectFree(user);
483 dbi_result result = dbi_conn_query(writehandle, "START TRANSACTION;");
485 osrfLogError(OSRF_LOG_MARK, "%s: Error starting transaction", MODULENAME );
486 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error starting transaction" );
489 jsonObject* ret = jsonNewObject(ctx->session->session_id);
490 osrfAppRespondComplete( ctx, ret );
493 if (!ctx->session->userData) {
494 ctx->session->userData = osrfNewHash();
495 osrfHashSetCallback((osrfHash*)ctx->session->userData, &sessionDataFree);
498 osrfHashSet( (osrfHash*)ctx->session->userData, strdup( ctx->session->session_id ), "xact_id" );
499 ctx->session->userDataFree = &userDataFree;
505 int setSavepoint ( osrfMethodContext* ctx ) {
506 if(osrfMethodVerifyContext( ctx )) {
507 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
514 jsonObject* user = verifyUserPCRUD( ctx );
515 if (!user) return -1;
516 jsonObjectFree(user);
519 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
520 osrfAppSessionStatus(
522 OSRF_STATUS_INTERNALSERVERERROR,
523 "osrfMethodException",
525 "No active transaction -- required for savepoints"
530 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
532 dbi_result result = dbi_conn_queryf(writehandle, "SAVEPOINT \"%s\";", spName);
536 "%s: Error creating savepoint %s in transaction %s",
539 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
541 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error creating savepoint" );
545 jsonObject* ret = jsonNewObject(spName);
546 osrfAppRespondComplete( ctx, ret );
553 int releaseSavepoint ( osrfMethodContext* ctx ) {
554 if(osrfMethodVerifyContext( ctx )) {
555 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
562 jsonObject* user = verifyUserPCRUD( ctx );
563 if (!user) return -1;
564 jsonObjectFree(user);
567 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
568 osrfAppSessionStatus(
570 OSRF_STATUS_INTERNALSERVERERROR,
571 "osrfMethodException",
573 "No active transaction -- required for savepoints"
578 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
580 dbi_result result = dbi_conn_queryf(writehandle, "RELEASE SAVEPOINT \"%s\";", spName);
584 "%s: Error releasing savepoint %s in transaction %s",
587 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
589 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error releasing savepoint" );
593 jsonObject* ret = jsonNewObject(spName);
594 osrfAppRespondComplete( ctx, ret );
601 int rollbackSavepoint ( osrfMethodContext* ctx ) {
602 if(osrfMethodVerifyContext( ctx )) {
603 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
610 jsonObject* user = verifyUserPCRUD( ctx );
611 if (!user) return -1;
612 jsonObjectFree(user);
615 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
616 osrfAppSessionStatus(
618 OSRF_STATUS_INTERNALSERVERERROR,
619 "osrfMethodException",
621 "No active transaction -- required for savepoints"
626 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
628 dbi_result result = dbi_conn_queryf(writehandle, "ROLLBACK TO SAVEPOINT \"%s\";", spName);
632 "%s: Error rolling back savepoint %s in transaction %s",
635 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
637 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back savepoint" );
641 jsonObject* ret = jsonNewObject(spName);
642 osrfAppRespondComplete( ctx, ret );
649 int commitTransaction ( osrfMethodContext* ctx ) {
650 if(osrfMethodVerifyContext( ctx )) {
651 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
656 jsonObject* user = verifyUserPCRUD( ctx );
657 if (!user) return -1;
658 jsonObjectFree(user);
661 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
662 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to commit" );
666 dbi_result result = dbi_conn_query(writehandle, "COMMIT;");
668 osrfLogError(OSRF_LOG_MARK, "%s: Error committing transaction", MODULENAME );
669 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error committing transaction" );
672 osrfHashRemove(ctx->session->userData, "xact_id");
673 jsonObject* ret = jsonNewObject(ctx->session->session_id);
674 osrfAppRespondComplete( ctx, ret );
680 int rollbackTransaction ( osrfMethodContext* ctx ) {
681 if(osrfMethodVerifyContext( ctx )) {
682 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
687 jsonObject* user = verifyUserPCRUD( ctx );
688 if (!user) return -1;
689 jsonObjectFree(user);
692 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
693 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to roll back" );
697 dbi_result result = dbi_conn_query(writehandle, "ROLLBACK;");
699 osrfLogError(OSRF_LOG_MARK, "%s: Error rolling back transaction", MODULENAME );
700 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back transaction" );
703 osrfHashRemove(ctx->session->userData, "xact_id");
704 jsonObject* ret = jsonNewObject(ctx->session->session_id);
705 osrfAppRespondComplete( ctx, ret );
711 int dispatchCRUDMethod ( osrfMethodContext* ctx ) {
712 if(osrfMethodVerifyContext( ctx )) {
713 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
717 osrfHash* meta = (osrfHash*) ctx->method->userData;
718 osrfHash* class_obj = osrfHashGet( meta, "class" );
722 const char* methodtype = osrfHashGet(meta, "methodtype");
723 jsonObject * obj = NULL;
725 if (!strcmp(methodtype, "create")) {
726 obj = doCreate(ctx, &err);
727 osrfAppRespondComplete( ctx, obj );
729 else if (!strcmp(methodtype, "retrieve")) {
730 obj = doRetrieve(ctx, &err);
731 osrfAppRespondComplete( ctx, obj );
733 else if (!strcmp(methodtype, "update")) {
734 obj = doUpdate(ctx, &err);
735 osrfAppRespondComplete( ctx, obj );
737 else if (!strcmp(methodtype, "delete")) {
738 obj = doDelete(ctx, &err);
739 osrfAppRespondComplete( ctx, obj );
741 else if (!strcmp(methodtype, "search")) {
743 jsonObject* _p = jsonObjectClone( ctx->params );
746 _p = jsonParseString("[]");
747 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 1)));
748 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 2)));
751 obj = doFieldmapperSearch(ctx, class_obj, _p, &err);
757 jsonIterator* itr = jsonNewIterator( obj );
758 while ((cur = jsonIteratorNext( itr ))) {
760 if(!verifyObjectPCRUD(ctx, cur)) continue;
762 osrfAppRespond( ctx, cur );
764 jsonIteratorFree(itr);
765 osrfAppRespondComplete( ctx, NULL );
767 } else if (!strcmp(methodtype, "id_list")) {
769 jsonObject* _p = jsonObjectClone( ctx->params );
772 _p = jsonParseString("[]");
773 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 1)));
774 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 2)));
777 if (jsonObjectGetIndex( _p, 1 )) {
778 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "select" );
779 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "no_i18n" );
780 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh" );
781 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh_columns" );
783 jsonObjectSetIndex( _p, 1, jsonNewObjectType(JSON_HASH) );
786 jsonObjectSetKey( jsonObjectGetIndex( _p, 1 ), "no_i18n", jsonNewBoolObject( 1 ) );
789 jsonObjectGetIndex( _p, 1 ),
792 "{ \"%s\":[\"%s\"] }",
793 osrfHashGet( class_obj, "classname" ),
794 osrfHashGet( class_obj, "primarykey" )
798 obj = doFieldmapperSearch(ctx, class_obj, _p, &err);
804 jsonIterator* itr = jsonNewIterator( obj );
805 while ((cur = jsonIteratorNext( itr ))) {
807 if(!verifyObjectPCRUD(ctx, cur)) continue;
811 oilsFMGetObject( cur, osrfHashGet( class_obj, "primarykey" ) )
814 jsonIteratorFree(itr);
815 osrfAppRespondComplete( ctx, NULL );
818 osrfAppRespondComplete( ctx, obj );
826 static int verifyObjectClass ( osrfMethodContext* ctx, const jsonObject* param ) {
829 osrfHash* meta = (osrfHash*) ctx->method->userData;
830 osrfHash* class = osrfHashGet( meta, "class" );
832 if (!param->classname || (strcmp( osrfHashGet(class, "classname"), param->classname ))) {
834 growing_buffer* msg = buffer_init(128);
837 "%s: %s method for type %s was passed a %s",
839 osrfHashGet(meta, "methodtype"),
840 osrfHashGet(class, "classname"),
844 char* m = buffer_release(msg);
845 osrfAppSessionStatus( ctx->session, OSRF_STATUS_BADREQUEST, "osrfMethodException", ctx->request, m );
853 ret = verifyObjectPCRUD( ctx, param );
861 static jsonObject* verifyUserPCRUD( osrfMethodContext* ctx ) {
862 char* auth = jsonObjectToSimpleString( jsonObjectGetIndex( ctx->params, 0 ) );
863 jsonObject* auth_object = jsonNewObject(auth);
864 jsonObject* user = oilsUtilsQuickReq("open-ils.auth","open-ils.auth.session.retrieve", auth_object);
865 jsonObjectFree(auth_object);
867 if (!user->classname || strcmp(user->classname, "au")) {
869 growing_buffer* msg = buffer_init(128);
872 "%s: permacrud received a bad auth token: %s",
877 char* m = buffer_release(msg);
878 osrfAppSessionStatus( ctx->session, OSRF_STATUS_UNAUTHORIZED, "osrfMethodException", ctx->request, m );
881 jsonObjectFree(user);
890 static int verifyObjectPCRUD ( osrfMethodContext* ctx, const jsonObject* obj ) {
892 dbhandle = writehandle;
894 osrfHash* meta = (osrfHash*) ctx->method->userData;
895 osrfHash* class = osrfHashGet( meta, "class" );
896 char* method_type = strdup( osrfHashGet(meta, "methodtype") );
899 if ( ( *method_type == 's' || *method_type == 'i' ) ) {
901 method_type = strdup("retrieve"); // search and id_list are equivelant to retrieve for this
902 } else if ( *method_type == 'u' || *method_type == 'd' ) {
903 fetch = 1; // MUST go to the db for the object for update and delete
906 osrfHash* pcrud = osrfHashGet( osrfHashGet(class, "permacrud"), method_type );
910 // No permacrud for this method type on this class
912 growing_buffer* msg = buffer_init(128);
915 "%s: %s on class %s has no permacrud IDL entry",
917 osrfHashGet(meta, "methodtype"),
918 osrfHashGet(class, "classname")
921 char* m = buffer_release(msg);
922 osrfAppSessionStatus( ctx->session, OSRF_STATUS_FORBIDDEN, "osrfMethodException", ctx->request, m );
929 jsonObject* user = verifyUserPCRUD( ctx );
932 int userid = atoi( oilsFMGetString( user, "id" ) );
933 jsonObjectFree(user);
935 osrfStringArray* permission = osrfHashGet(pcrud, "permission");
936 osrfStringArray* local_context = osrfHashGet(pcrud, "local_context");
937 osrfHash* foreign_context = osrfHashGet(pcrud, "foreign_context");
939 osrfStringArray* context_org_array = osrfNewStringArray(1);
942 char* pkey_value = NULL;
943 if ( str_is_true( osrfHashGet(pcrud, "global_required") ) ) {
944 osrfLogDebug( OSRF_LOG_MARK, "global-level permissions required, fetching top of the org tree" );
946 // check for perm at top of org tree
947 jsonObject* _tmp_params = jsonParseString("[{\"parent_ou\":null}]");
948 jsonObject* _list = doFieldmapperSearch(ctx, osrfHashGet( oilsIDL(), "aou" ), _tmp_params, &err);
950 jsonObject* _tree_top = jsonObjectGetIndex(_list, 0);
953 jsonObjectFree(_tmp_params);
954 jsonObjectFree(_list);
956 growing_buffer* msg = buffer_init(128);
957 OSRF_BUFFER_ADD( msg, MODULENAME );
958 OSRF_BUFFER_ADD( msg,
959 ": Internal error, could not find the top of the org tree (parent_ou = NULL)" );
961 char* m = buffer_release(msg);
962 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, m );
968 osrfStringArrayAdd( context_org_array, oilsFMGetString( _tree_top, "id" ) );
969 osrfLogDebug( OSRF_LOG_MARK, "top of the org tree is %s", osrfStringArrayGetString(context_org_array, 0) );
971 jsonObjectFree(_tmp_params);
972 jsonObjectFree(_list);
975 osrfLogDebug( OSRF_LOG_MARK, "global-level permissions not required, fetching context org ids" );
976 char* pkey = osrfHashGet(class, "primarykey");
977 jsonObject *param = NULL;
979 if (obj->classname) {
980 pkey_value = oilsFMGetString( obj, pkey );
981 if (!fetch) param = jsonObjectClone(obj);
982 osrfLogDebug( OSRF_LOG_MARK, "Object supplied, using primary key value of %s", pkey_value );
984 pkey_value = jsonObjectToSimpleString( obj );
986 osrfLogDebug( OSRF_LOG_MARK, "Object not supplied, using primary key value of %s and retrieving from the database", pkey_value );
990 jsonObject* _tmp_params = jsonParseStringFmt("[{\"%s\":\"%s\"}]", pkey, pkey_value);
991 jsonObject* _list = doFieldmapperSearch(
998 param = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1000 jsonObjectFree(_tmp_params);
1001 jsonObjectFree(_list);
1005 osrfLogDebug( OSRF_LOG_MARK, "Object not found in the database with primary key %s of %s", pkey, pkey_value );
1007 growing_buffer* msg = buffer_init(128);
1010 "%s: no object found with primary key %s of %s",
1016 char* m = buffer_release(msg);
1017 osrfAppSessionStatus(
1019 OSRF_STATUS_INTERNALSERVERERROR,
1020 "osrfMethodException",
1026 if (pkey_value) free(pkey_value);
1031 if (local_context->size > 0) {
1032 osrfLogDebug( OSRF_LOG_MARK, "%d class-local context field(s) specified", local_context->size);
1034 char* lcontext = NULL;
1035 while ( (lcontext = osrfStringArrayGetString(local_context, i++)) ) {
1036 osrfStringArrayAdd( context_org_array, oilsFMGetString( param, lcontext ) );
1039 "adding class-local field %s (value: %s) to the context org list",
1041 osrfStringArrayGetString(context_org_array, context_org_array->size - 1)
1046 osrfStringArray* class_list;
1048 if (foreign_context) {
1049 class_list = osrfHashKeys( foreign_context );
1050 osrfLogDebug( OSRF_LOG_MARK, "%d foreign context classes(s) specified", class_list->size);
1052 if (class_list->size > 0) {
1055 char* class_name = NULL;
1056 while ( (class_name = osrfStringArrayGetString(class_list, i++)) ) {
1057 osrfHash* fcontext = osrfHashGet(foreign_context, class_name);
1061 "%d foreign context fields(s) specified for class %s",
1062 ((osrfStringArray*)osrfHashGet(fcontext,"context"))->size,
1066 char* foreign_pkey = osrfHashGet(fcontext, "field");
1067 char* foreign_pkey_value = oilsFMGetString(param, osrfHashGet(fcontext, "fkey"));
1069 jsonObject* _tmp_params = jsonParseStringFmt(
1070 "[{\"%s\":\"%s\"}]",
1075 jsonObject* _list = doFieldmapperSearch(
1077 osrfHashGet( oilsIDL(), class_name ),
1082 jsonObject* _fparam = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1083 jsonObjectFree(_tmp_params);
1084 jsonObjectFree(_list);
1086 osrfStringArray* jump_list = osrfHashGet(fcontext, "jump");
1088 if (_fparam && jump_list) {
1091 while ( (flink = osrfStringArrayGetString(jump_list, k++)) && _fparam ) {
1092 free(foreign_pkey_value);
1094 osrfHash* foreign_link_hash = oilsIDLFindPath( "/%s/links/%s", _fparam->classname, flink );
1096 foreign_pkey_value = oilsFMGetString(_fparam, flink);
1097 foreign_pkey = osrfHashGet( foreign_link_hash, "key" );
1099 _tmp_params = jsonParseStringFmt(
1100 "[{\"%s\":\"%s\"}]",
1105 _list = doFieldmapperSearch(
1107 osrfHashGet( oilsIDL(), osrfHashGet( foreign_link_hash, "class" ) ),
1112 _fparam = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1113 jsonObjectFree(_tmp_params);
1114 jsonObjectFree(_list);
1121 growing_buffer* msg = buffer_init(128);
1124 "%s: no object found with primary key %s of %s",
1130 char* m = buffer_release(msg);
1131 osrfAppSessionStatus(
1133 OSRF_STATUS_INTERNALSERVERERROR,
1134 "osrfMethodException",
1140 osrfStringArrayFree(class_list);
1141 free(foreign_pkey_value);
1142 jsonObjectFree(param);
1147 free(foreign_pkey_value);
1150 char* foreign_field = NULL;
1151 while ( (foreign_field = osrfStringArrayGetString(osrfHashGet(fcontext,"context"), j++)) ) {
1152 osrfStringArrayAdd( context_org_array, oilsFMGetString( _fparam, foreign_field ) );
1155 "adding foreign class %s field %s (value: %s) to the context org list",
1158 osrfStringArrayGetString(context_org_array, context_org_array->size - 1)
1162 jsonObjectFree(_fparam);
1165 osrfStringArrayFree(class_list);
1169 jsonObjectFree(param);
1172 char* context_org = NULL;
1176 if (permission->size == 0) {
1177 osrfLogDebug( OSRF_LOG_MARK, "No permission specified for this action, passing through" );
1182 while ( (perm = osrfStringArrayGetString(permission, i++)) ) {
1184 while ( (context_org = osrfStringArrayGetString(context_org_array, j++)) ) {
1190 "Checking object permission [%s] for user %d on object %s (class %s) at org %d",
1194 osrfHashGet(class, "classname"),
1198 result = dbi_conn_queryf(
1200 "SELECT permission.usr_has_object_perm(%d, '%s', '%s', '%s', %d) AS has_perm;",
1203 osrfHashGet(class, "classname"),
1211 "Recieved a result for object permission [%s] for user %d on object %s (class %s) at org %d",
1215 osrfHashGet(class, "classname"),
1219 if (dbi_result_first_row(result)) {
1220 jsonObject* return_val = oilsMakeJSONFromResult( result );
1221 char* has_perm = jsonObjectToSimpleString( jsonObjectGetKeyConst(return_val, "has_perm") );
1225 "Status of object permission [%s] for user %d on object %s (class %s) at org %d is %s",
1229 osrfHashGet(class, "classname"),
1234 if ( *has_perm == 't' ) OK = 1;
1236 jsonObjectFree(return_val);
1239 dbi_result_free(result);
1244 osrfLogDebug( OSRF_LOG_MARK, "Checking non-object permission [%s] for user %d at org %d", perm, userid, atoi(context_org) );
1245 result = dbi_conn_queryf(
1247 "SELECT permission.usr_has_perm(%d, '%s', %d) AS has_perm;",
1254 osrfLogDebug( OSRF_LOG_MARK, "Recieved a result for permission [%s] for user %d at org %d", perm, userid, atoi(context_org) );
1255 if (dbi_result_first_row(result)) {
1256 jsonObject* return_val = oilsMakeJSONFromResult( result );
1257 char* has_perm = jsonObjectToSimpleString( jsonObjectGetKeyConst(return_val, "has_perm") );
1258 osrfLogDebug( OSRF_LOG_MARK, "Status of permission [%s] for user %d at org %d is [%s]", perm, userid, atoi(context_org), has_perm );
1259 if ( *has_perm == 't' ) OK = 1;
1261 jsonObjectFree(return_val);
1264 dbi_result_free(result);
1272 if (pkey_value) free(pkey_value);
1273 osrfStringArrayFree(context_org_array);
1280 static jsonObject* doCreate(osrfMethodContext* ctx, int* err ) {
1282 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1284 jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
1285 jsonObject* options = jsonObjectGetIndex( ctx->params, 2 );
1287 jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
1288 jsonObject* options = jsonObjectGetIndex( ctx->params, 1 );
1291 if (!verifyObjectClass(ctx, target)) {
1296 osrfLogDebug( OSRF_LOG_MARK, "Object seems to be of the correct type" );
1298 if (!ctx->session || !ctx->session->userData || !osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
1299 osrfLogError( OSRF_LOG_MARK, "No active transaction -- required for CREATE" );
1301 osrfAppSessionStatus(
1303 OSRF_STATUS_BADREQUEST,
1304 "osrfMethodException",
1306 "No active transaction -- required for CREATE"
1312 // The following test is harmless but redundant. If a class is
1313 // readonly, we don't register a create method for it.
1314 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
1315 osrfAppSessionStatus(
1317 OSRF_STATUS_BADREQUEST,
1318 "osrfMethodException",
1320 "Cannot INSERT readonly class"
1327 char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
1329 // Set the last_xact_id
1330 int index = oilsIDL_ntop( target->classname, "last_xact_id" );
1332 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
1333 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
1336 osrfLogDebug( OSRF_LOG_MARK, "There is a transaction running..." );
1338 dbhandle = writehandle;
1340 osrfHash* fields = osrfHashGet(meta, "fields");
1341 char* pkey = osrfHashGet(meta, "primarykey");
1342 char* seq = osrfHashGet(meta, "sequence");
1344 growing_buffer* table_buf = buffer_init(128);
1345 growing_buffer* col_buf = buffer_init(128);
1346 growing_buffer* val_buf = buffer_init(128);
1348 OSRF_BUFFER_ADD(table_buf, "INSERT INTO ");
1349 OSRF_BUFFER_ADD(table_buf, osrfHashGet(meta, "tablename"));
1350 OSRF_BUFFER_ADD_CHAR( col_buf, '(' );
1351 buffer_add(val_buf,"VALUES (");
1357 osrfStringArray* field_list = osrfHashKeys( fields );
1358 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
1360 osrfHash* field = osrfHashGet( fields, field_name );
1362 if( str_is_true( osrfHashGet( field, "virtual" ) ) )
1365 const jsonObject* field_object = oilsFMGetObject( target, field_name );
1368 if (field_object && field_object->classname) {
1369 value = oilsFMGetString(
1371 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
1374 value = jsonObjectToSimpleString( field_object );
1381 OSRF_BUFFER_ADD_CHAR( col_buf, ',' );
1382 OSRF_BUFFER_ADD_CHAR( val_buf, ',' );
1385 buffer_add(col_buf, field_name);
1387 if (!field_object || field_object->type == JSON_NULL) {
1388 buffer_add( val_buf, "DEFAULT" );
1390 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1391 if ( !strcmp(osrfHashGet(field, "datatype"), "INT8") ) {
1392 buffer_fadd( val_buf, "%lld", atoll(value) );
1394 } else if ( !strcmp(osrfHashGet(field, "datatype"), "INT") ) {
1395 buffer_fadd( val_buf, "%d", atoi(value) );
1397 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
1398 buffer_fadd( val_buf, "%f", atof(value) );
1401 if ( dbi_conn_quote_string(writehandle, &value) ) {
1402 OSRF_BUFFER_ADD( val_buf, value );
1405 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
1406 osrfAppSessionStatus(
1408 OSRF_STATUS_INTERNALSERVERERROR,
1409 "osrfMethodException",
1411 "Error quoting string -- please see the error log for more details"
1414 buffer_free(table_buf);
1415 buffer_free(col_buf);
1416 buffer_free(val_buf);
1427 OSRF_BUFFER_ADD_CHAR( col_buf, ')' );
1428 OSRF_BUFFER_ADD_CHAR( val_buf, ')' );
1430 char* table_str = buffer_release(table_buf);
1431 char* col_str = buffer_release(col_buf);
1432 char* val_str = buffer_release(val_buf);
1433 growing_buffer* sql = buffer_init(128);
1434 buffer_fadd( sql, "%s %s %s;", table_str, col_str, val_str );
1439 char* query = buffer_release(sql);
1441 osrfLogDebug(OSRF_LOG_MARK, "%s: Insert SQL [%s]", MODULENAME, query);
1444 dbi_result result = dbi_conn_query(writehandle, query);
1446 jsonObject* obj = NULL;
1449 obj = jsonNewObject(NULL);
1452 "%s ERROR inserting %s object using query [%s]",
1454 osrfHashGet(meta, "fieldmapper"),
1457 osrfAppSessionStatus(
1459 OSRF_STATUS_INTERNALSERVERERROR,
1460 "osrfMethodException",
1462 "INSERT error -- please see the error log for more details"
1467 char* id = oilsFMGetString(target, pkey);
1469 unsigned long long new_id = dbi_conn_sequence_last(writehandle, seq);
1470 growing_buffer* _id = buffer_init(10);
1471 buffer_fadd(_id, "%lld", new_id);
1472 id = buffer_release(_id);
1475 // Find quietness specification, if present
1476 char* quiet_str = NULL;
1478 const jsonObject* quiet_obj = jsonObjectGetKeyConst( options, "quiet" );
1480 quiet_str = jsonObjectToSimpleString( quiet_obj );
1483 if( str_is_true( quiet_str ) ) { // if quietness is specified
1484 obj = jsonNewObject(id);
1488 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
1489 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH));
1492 jsonObjectGetIndex(fake_params, 0),
1497 jsonObject* list = doFieldmapperSearch( ctx,meta, fake_params, err);
1500 jsonObjectFree( fake_params );
1503 obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
1506 jsonObjectFree( list );
1507 jsonObjectFree( fake_params );
1510 if(quiet_str) free(quiet_str);
1521 static jsonObject* doRetrieve(osrfMethodContext* ctx, int* err ) {
1531 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1533 char* id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, id_pos));
1534 jsonObject* order_hash = jsonObjectGetIndex(ctx->params, order_pos);
1538 "%s retrieving %s object with primary key value of %s",
1540 osrfHashGet(meta, "fieldmapper"),
1545 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
1546 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH));
1549 jsonObjectGetIndex(fake_params, 0),
1550 osrfHashGet(meta, "primarykey"),
1551 jsonObjectClone(jsonObjectGetIndex(ctx->params, id_pos))
1555 if (order_hash) jsonObjectPush(fake_params, jsonObjectClone(order_hash) );
1557 jsonObject* list = doFieldmapperSearch( ctx,meta, fake_params, err);
1560 jsonObjectFree( fake_params );
1564 jsonObject* obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
1566 jsonObjectFree( list );
1567 jsonObjectFree( fake_params );
1570 if(!verifyObjectPCRUD(ctx, obj)) {
1571 jsonObjectFree(obj);
1574 growing_buffer* msg = buffer_init(128);
1575 OSRF_BUFFER_ADD( msg, MODULENAME );
1576 OSRF_BUFFER_ADD( msg, ": Insufficient permissions to retrieve object" );
1578 char* m = buffer_release(msg);
1579 osrfAppSessionStatus( ctx->session, OSRF_STATUS_NOTALLOWED, "osrfMethodException", ctx->request, m );
1590 static char* jsonNumberToDBString ( osrfHash* field, const jsonObject* value ) {
1591 growing_buffer* val_buf = buffer_init(32);
1593 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
1594 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%ld", (long)jsonObjectGetNumber(value) );
1596 char* val_str = jsonObjectToSimpleString(value);
1597 buffer_fadd( val_buf, "%ld", atol(val_str) );
1601 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
1602 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%f", jsonObjectGetNumber(value) );
1604 char* val_str = jsonObjectToSimpleString(value);
1605 buffer_fadd( val_buf, "%f", atof(val_str) );
1610 return buffer_release(val_buf);
1613 static char* searchINPredicate (const char* class, osrfHash* field,
1614 const jsonObject* node, const char* op) {
1615 growing_buffer* sql_buf = buffer_init(32);
1621 osrfHashGet(field, "name")
1625 buffer_add(sql_buf, "IN (");
1626 } else if (!(strcasecmp(op,"not in"))) {
1627 buffer_add(sql_buf, "NOT IN (");
1629 buffer_add(sql_buf, "IN (");
1632 int in_item_index = 0;
1633 int in_item_first = 1;
1634 jsonObject* in_item;
1635 while ( (in_item = jsonObjectGetIndex(node, in_item_index++)) ) {
1640 buffer_add(sql_buf, ", ");
1642 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1643 char* val = jsonNumberToDBString( field, in_item );
1644 OSRF_BUFFER_ADD( sql_buf, val );
1648 char* key_string = jsonObjectToSimpleString(in_item);
1649 if ( dbi_conn_quote_string(dbhandle, &key_string) ) {
1650 OSRF_BUFFER_ADD( sql_buf, key_string );
1653 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, key_string);
1655 buffer_free(sql_buf);
1661 OSRF_BUFFER_ADD_CHAR( sql_buf, ')' );
1663 return buffer_release(sql_buf);
1666 // Receive a JSON_ARRAY representing a function call. The first
1667 // entry in the array is the function name. The rest are parameters.
1668 static char* searchValueTransform( const jsonObject* array ) {
1669 growing_buffer* sql_buf = buffer_init(32);
1672 jsonObject* func_item;
1674 // Get the function name
1675 if( array->size > 0 ) {
1676 func_item = jsonObjectGetIndex( array, 0 );
1677 val = jsonObjectToSimpleString( func_item );
1678 OSRF_BUFFER_ADD( sql_buf, val );
1679 OSRF_BUFFER_ADD( sql_buf, "( " );
1683 // Get the parameters
1684 int func_item_index = 1; // We already grabbed the zeroth entry
1685 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1687 // Add a separator comma, if we need one
1688 if( func_item_index > 2 )
1689 buffer_add( sql_buf, ", " );
1691 // Add the current parameter
1692 if (func_item->type == JSON_NULL) {
1693 buffer_add( sql_buf, "NULL" );
1695 val = jsonObjectToSimpleString(func_item);
1696 if ( dbi_conn_quote_string(dbhandle, &val) ) {
1697 OSRF_BUFFER_ADD( sql_buf, val );
1700 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1701 buffer_free(sql_buf);
1708 buffer_add( sql_buf, " )" );
1710 return buffer_release(sql_buf);
1713 static char* searchFunctionPredicate (const char* class, osrfHash* field,
1714 const jsonObject* node, const char* node_key) {
1715 growing_buffer* sql_buf = buffer_init(32);
1717 char* val = searchValueTransform(node);
1723 osrfHashGet(field, "name"),
1730 return buffer_release(sql_buf);
1733 // class is a class name
1734 // field is a field definition as stored in the IDL
1735 // node comes from the method parameter, and represents an entry in the SELECT list
1736 static char* searchFieldTransform (const char* class, osrfHash* field, const jsonObject* node) {
1737 growing_buffer* sql_buf = buffer_init(32);
1739 char* field_transform = jsonObjectToSimpleString( jsonObjectGetKeyConst( node, "transform" ) );
1740 char* transform_subcolumn = jsonObjectToSimpleString( jsonObjectGetKeyConst( node, "result_field" ) );
1742 if(transform_subcolumn)
1743 OSRF_BUFFER_ADD_CHAR( sql_buf, '(' ); // enclose transform in parentheses
1745 if (field_transform) {
1746 buffer_fadd( sql_buf, "%s(\"%s\".%s", field_transform, class, osrfHashGet(field, "name"));
1747 const jsonObject* array = jsonObjectGetKeyConst( node, "params" );
1750 int func_item_index = 0;
1751 jsonObject* func_item;
1752 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1754 char* val = jsonObjectToSimpleString(func_item);
1757 buffer_add( sql_buf, ",NULL" );
1758 } else if ( dbi_conn_quote_string(dbhandle, &val) ) {
1759 OSRF_BUFFER_ADD_CHAR( sql_buf, ',' );
1760 OSRF_BUFFER_ADD( sql_buf, val );
1762 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1763 free(transform_subcolumn);
1764 free(field_transform);
1766 buffer_free(sql_buf);
1773 buffer_add( sql_buf, " )" );
1776 buffer_fadd( sql_buf, "\"%s\".%s", class, osrfHashGet(field, "name"));
1779 if (transform_subcolumn)
1780 buffer_fadd( sql_buf, ").\"%s\"", transform_subcolumn );
1782 if (field_transform) free(field_transform);
1783 if (transform_subcolumn) free(transform_subcolumn);
1785 return buffer_release(sql_buf);
1788 static char* searchFieldTransformPredicate (const char* class, osrfHash* field, jsonObject* node, const char* node_key) {
1789 char* field_transform = searchFieldTransform( class, field, node );
1792 if (!jsonObjectGetKeyConst( node, "value" )) {
1793 value = searchWHERE( node, osrfHashGet( oilsIDL(), class ), AND_OP_JOIN, NULL );
1794 } else if (jsonObjectGetKeyConst( node, "value" )->type == JSON_ARRAY) {
1795 value = searchValueTransform(jsonObjectGetKeyConst( node, "value" ));
1796 } else if (jsonObjectGetKeyConst( node, "value" )->type == JSON_HASH) {
1797 value = searchWHERE( jsonObjectGetKeyConst( node, "value" ), osrfHashGet( oilsIDL(), class ), AND_OP_JOIN, NULL );
1798 } else if (jsonObjectGetKeyConst( node, "value" )->type != JSON_NULL) {
1799 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1800 value = jsonNumberToDBString( field, jsonObjectGetKeyConst( node, "value" ) );
1802 value = jsonObjectToSimpleString(jsonObjectGetKeyConst( node, "value" ));
1803 if ( !dbi_conn_quote_string(dbhandle, &value) ) {
1804 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, value);
1806 free(field_transform);
1812 growing_buffer* sql_buf = buffer_init(32);
1823 free(field_transform);
1825 return buffer_release(sql_buf);
1828 static char* searchSimplePredicate (const char* orig_op, const char* class,
1829 osrfHash* field, const jsonObject* node) {
1833 if (node->type != JSON_NULL) {
1834 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1835 val = jsonNumberToDBString( field, node );
1837 val = jsonObjectToSimpleString(node);
1841 char* pred = searchWriteSimplePredicate( class, field, osrfHashGet(field, "name"), orig_op, val );
1848 static char* searchWriteSimplePredicate ( const char* class, osrfHash* field,
1849 const char* left, const char* orig_op, const char* right ) {
1853 if (right == NULL) {
1854 val = strdup("NULL");
1856 if (strcmp( orig_op, "=" ))
1857 op = strdup("IS NOT");
1861 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1862 val = strdup(right);
1863 op = strdup(orig_op);
1866 val = strdup(right);
1867 if ( !dbi_conn_quote_string(dbhandle, &val) ) {
1868 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1872 op = strdup(orig_op);
1875 growing_buffer* sql_buf = buffer_init(16);
1876 buffer_fadd( sql_buf, "\"%s\".%s %s %s", class, left, op, val );
1880 return buffer_release(sql_buf);
1883 static char* searchBETWEENPredicate (const char* class, osrfHash* field, jsonObject* node) {
1888 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1889 x_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,0));
1890 y_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,1));
1893 x_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,0));
1894 y_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,1));
1895 if ( !(dbi_conn_quote_string(dbhandle, &x_string) && dbi_conn_quote_string(dbhandle, &y_string)) ) {
1896 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key strings [%s] and [%s]", MODULENAME, x_string, y_string);
1903 growing_buffer* sql_buf = buffer_init(32);
1904 buffer_fadd( sql_buf, "%s BETWEEN %s AND %s", osrfHashGet(field, "name"), x_string, y_string );
1908 return buffer_release(sql_buf);
1911 static char* searchPredicate ( const char* class, osrfHash* field, jsonObject* node ) {
1914 if (node->type == JSON_ARRAY) { // equality IN search
1915 pred = searchINPredicate( class, field, node, NULL );
1916 } else if (node->type == JSON_HASH) { // non-equality search
1917 jsonObject* pred_node;
1918 jsonIterator* pred_itr = jsonNewIterator( node );
1919 while ( (pred_node = jsonIteratorNext( pred_itr )) ) {
1920 if ( !(strcasecmp( pred_itr->key,"between" )) )
1921 pred = searchBETWEENPredicate( class, field, pred_node );
1922 else if ( !(strcasecmp( pred_itr->key,"in" )) || !(strcasecmp( pred_itr->key,"not in" )) )
1923 pred = searchINPredicate( class, field, pred_node, pred_itr->key );
1924 else if ( pred_node->type == JSON_ARRAY )
1925 pred = searchFunctionPredicate( class, field, pred_node, pred_itr->key );
1926 else if ( pred_node->type == JSON_HASH )
1927 pred = searchFieldTransformPredicate( class, field, pred_node, pred_itr->key );
1929 pred = searchSimplePredicate( pred_itr->key, class, field, pred_node );
1933 jsonIteratorFree(pred_itr);
1934 } else if (node->type == JSON_NULL) { // IS NULL search
1935 growing_buffer* _p = buffer_init(64);
1938 "\"%s\".%s IS NULL",
1940 osrfHashGet(field, "name")
1942 pred = buffer_release(_p);
1943 } else { // equality search
1944 pred = searchSimplePredicate( "=", class, field, node );
1963 field : call_number,
1979 static char* searchJOIN ( const jsonObject* join_hash, osrfHash* leftmeta ) {
1981 const jsonObject* working_hash;
1982 jsonObject* freeable_hash = NULL;
1984 if (join_hash->type == JSON_STRING) {
1985 // create a wrapper around a copy of the original
1986 char* _tmp = jsonObjectToSimpleString( join_hash );
1987 freeable_hash = jsonNewObjectType(JSON_HASH);
1988 jsonObjectSetKey(freeable_hash, _tmp, NULL);
1990 working_hash = freeable_hash;
1993 working_hash = join_hash;
1995 growing_buffer* join_buf = buffer_init(128);
1996 char* leftclass = osrfHashGet(leftmeta, "classname");
1998 jsonObject* snode = NULL;
1999 jsonIterator* search_itr = jsonNewIterator( working_hash );
2001 jsonObjectFree(freeable_hash);
2003 while ( (snode = jsonIteratorNext( search_itr )) ) {
2004 osrfHash* idlClass = osrfHashGet( oilsIDL(), search_itr->key );
2006 char* class = osrfHashGet(idlClass, "classname");
2008 char* fkey = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "fkey" ) );
2009 char* field = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "field" ) );
2011 if (field && !fkey) {
2012 fkey = (char*)oilsIDLFindPath("/%s/links/%s/key", class, field);
2016 "%s: JOIN failed. No link defined from %s.%s to %s",
2022 buffer_free(join_buf);
2024 jsonIteratorFree(search_itr);
2027 fkey = strdup( fkey );
2029 } else if (!field && fkey) {
2030 field = (char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, fkey );
2034 "%s: JOIN failed. No link defined from %s.%s to %s",
2040 buffer_free(join_buf);
2042 jsonIteratorFree(search_itr);
2045 field = strdup( field );
2047 } else if (!field && !fkey) {
2048 osrfHash* _links = oilsIDLFindPath("/%s/links", leftclass);
2051 osrfStringArray* keys = osrfHashKeys( _links );
2052 while ( (fkey = osrfStringArrayGetString(keys, i++)) ) {
2053 fkey = strdup(osrfStringArrayGetString(keys, i++));
2054 if ( !strcmp( (char*)oilsIDLFindPath("/%s/links/%s/class", leftclass, fkey), class) ) {
2055 field = strdup( (char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, fkey) );
2061 osrfStringArrayFree(keys);
2063 if (!field && !fkey) {
2064 _links = oilsIDLFindPath("/%s/links", class);
2067 keys = osrfHashKeys( _links );
2068 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
2069 field = strdup(osrfStringArrayGetString(keys, i++));
2070 if ( !strcmp( (char*)oilsIDLFindPath("/%s/links/%s/class", class, field), class) ) {
2071 fkey = strdup( (char*)oilsIDLFindPath("/%s/links/%s/key", class, field) );
2077 osrfStringArrayFree(keys);
2080 if (!field && !fkey) {
2083 "%s: JOIN failed. No link defined between %s and %s",
2088 buffer_free(join_buf);
2089 jsonIteratorFree(search_itr);
2095 char* type = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "type" ) );
2097 if ( !strcasecmp(type,"left") ) {
2098 buffer_add(join_buf, " LEFT JOIN");
2099 } else if ( !strcasecmp(type,"right") ) {
2100 buffer_add(join_buf, " RIGHT JOIN");
2101 } else if ( !strcasecmp(type,"full") ) {
2102 buffer_add(join_buf, " FULL JOIN");
2104 buffer_add(join_buf, " INNER JOIN");
2107 buffer_add(join_buf, " INNER JOIN");
2111 char* table = getSourceDefinition(idlClass);
2112 buffer_fadd(join_buf, " %s AS \"%s\" ON ( \"%s\".%s = \"%s\".%s", table, class, class, field, leftclass, fkey);
2115 const jsonObject* filter = jsonObjectGetKeyConst( snode, "filter" );
2117 char* filter_op = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "filter_op" ) );
2119 if (!strcasecmp("or",filter_op)) {
2120 buffer_add( join_buf, " OR " );
2122 buffer_add( join_buf, " AND " );
2125 buffer_add( join_buf, " AND " );
2128 char* jpred = searchWHERE( filter, idlClass, AND_OP_JOIN, NULL );
2129 OSRF_BUFFER_ADD_CHAR( join_buf, ' ' );
2130 OSRF_BUFFER_ADD( join_buf, jpred );
2135 buffer_add(join_buf, " ) ");
2137 const jsonObject* join_filter = jsonObjectGetKeyConst( snode, "join" );
2139 char* jpred = searchJOIN( join_filter, idlClass );
2140 OSRF_BUFFER_ADD_CHAR( join_buf, ' ' );
2141 OSRF_BUFFER_ADD( join_buf, jpred );
2149 jsonIteratorFree(search_itr);
2151 return buffer_release(join_buf);
2156 { +class : { -or|-and : { field : { op : value }, ... } ... }, ... }
2157 { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }
2158 [ { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }, ... ]
2162 static char* searchWHERE ( const jsonObject* search_hash, osrfHash* meta, int opjoin_type, osrfMethodContext* ctx ) {
2166 "%s: Entering searchWHERE; search_hash addr = %p, meta addr = %p, opjoin_type = %d, ctx addr = %p",
2174 growing_buffer* sql_buf = buffer_init(128);
2176 jsonObject* node = NULL;
2179 if ( search_hash->type == JSON_ARRAY ) {
2180 osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_ARRAY", MODULENAME);
2181 jsonIterator* search_itr = jsonNewIterator( search_hash );
2182 while ( (node = jsonIteratorNext( search_itr )) ) {
2186 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2187 else buffer_add(sql_buf, " AND ");
2190 char* subpred = searchWHERE( node, meta, opjoin_type, ctx );
2191 buffer_fadd(sql_buf, "( %s )", subpred);
2194 jsonIteratorFree(search_itr);
2196 } else if ( search_hash->type == JSON_HASH ) {
2197 osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_HASH", MODULENAME);
2198 jsonIterator* search_itr = jsonNewIterator( search_hash );
2199 while ( (node = jsonIteratorNext( search_itr )) ) {
2204 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2205 else buffer_add(sql_buf, " AND ");
2208 if ( !strncmp("+",search_itr->key,1) ) {
2209 if ( node->type == JSON_STRING ) {
2210 char* subpred = jsonObjectToSimpleString( node );
2211 buffer_fadd(sql_buf, " \"%s\".%s ", search_itr->key + 1, subpred);
2214 char* subpred = searchWHERE( node, osrfHashGet( oilsIDL(), search_itr->key + 1 ), AND_OP_JOIN, ctx );
2215 buffer_fadd(sql_buf, "( %s )", subpred);
2218 } else if ( !strcasecmp("-or",search_itr->key) ) {
2219 char* subpred = searchWHERE( node, meta, OR_OP_JOIN, ctx );
2220 buffer_fadd(sql_buf, "( %s )", subpred);
2222 } else if ( !strcasecmp("-and",search_itr->key) ) {
2223 char* subpred = searchWHERE( node, meta, AND_OP_JOIN, ctx );
2224 buffer_fadd(sql_buf, "( %s )", subpred);
2226 } else if ( !strcasecmp("-exists",search_itr->key) ) {
2227 char* subpred = SELECT(
2229 jsonObjectGetKey( node, "select" ),
2230 jsonObjectGetKey( node, "from" ),
2231 jsonObjectGetKey( node, "where" ),
2232 jsonObjectGetKey( node, "having" ),
2233 jsonObjectGetKey( node, "order_by" ),
2234 jsonObjectGetKey( node, "limit" ),
2235 jsonObjectGetKey( node, "offset" ),
2239 buffer_fadd(sql_buf, "EXISTS ( %s )", subpred);
2241 } else if ( !strcasecmp("-not-exists",search_itr->key) ) {
2242 char* subpred = SELECT(
2244 jsonObjectGetKey( node, "select" ),
2245 jsonObjectGetKey( node, "from" ),
2246 jsonObjectGetKey( node, "where" ),
2247 jsonObjectGetKey( node, "having" ),
2248 jsonObjectGetKey( node, "order_by" ),
2249 jsonObjectGetKey( node, "limit" ),
2250 jsonObjectGetKey( node, "offset" ),
2254 buffer_fadd(sql_buf, "NOT EXISTS ( %s )", subpred);
2258 char* class = osrfHashGet(meta, "classname");
2259 osrfHash* fields = osrfHashGet(meta, "fields");
2260 osrfHash* field = osrfHashGet( fields, search_itr->key );
2264 char* table = getSourceDefinition(meta);
2267 "%s: Attempt to reference non-existent column %s on %s (%s)",
2273 buffer_free(sql_buf);
2275 jsonIteratorFree(search_itr);
2279 char* subpred = searchPredicate( class, field, node );
2280 buffer_add( sql_buf, subpred );
2284 jsonIteratorFree(search_itr);
2287 // ERROR ... only hash and array allowed at this level
2288 char* predicate_string = jsonObjectToJSON( search_hash );
2291 "%s: Invalid predicate structure: %s",
2295 buffer_free(sql_buf);
2296 free(predicate_string);
2301 return buffer_release(sql_buf);
2304 static char* SELECT (
2305 /* method context */ osrfMethodContext* ctx,
2307 /* SELECT */ jsonObject* selhash,
2308 /* FROM */ jsonObject* join_hash,
2309 /* WHERE */ jsonObject* search_hash,
2310 /* HAVING */ jsonObject* having_hash,
2311 /* ORDER BY */ jsonObject* order_hash,
2312 /* LIMIT */ jsonObject* limit,
2313 /* OFFSET */ jsonObject* offset,
2314 /* flags */ int flags
2316 const char* locale = osrf_message_get_last_locale();
2318 // in case we don't get a select list
2319 jsonObject* defaultselhash = NULL;
2321 // general tmp objects
2322 const jsonObject* tmp_const;
2323 jsonObject* selclass = NULL;
2324 jsonObject* selfield = NULL;
2325 jsonObject* snode = NULL;
2326 jsonObject* onode = NULL;
2328 char* string = NULL;
2329 int from_function = 0;
2334 // the core search class
2335 char* core_class = NULL;
2337 // metadata about the core search class
2338 osrfHash* core_meta = NULL;
2340 // punt if there's no core class
2341 if (!join_hash || ( join_hash->type == JSON_HASH && !join_hash->size ))
2344 // get the core class -- the only key of the top level FROM clause, or a string
2345 if (join_hash->type == JSON_HASH) {
2346 jsonIterator* tmp_itr = jsonNewIterator( join_hash );
2347 snode = jsonIteratorNext( tmp_itr );
2349 core_class = strdup( tmp_itr->key );
2352 jsonObject* extra = jsonIteratorNext( tmp_itr );
2354 jsonIteratorFree( tmp_itr );
2357 // There shouldn't be more than one entry in join_hash
2359 return NULL; // Malformed join_hash; extra entry
2361 } else if (join_hash->type == JSON_ARRAY) {
2363 core_class = jsonObjectToSimpleString( jsonObjectGetIndex(join_hash, 0) );
2366 } else if (join_hash->type == JSON_STRING) {
2367 core_class = jsonObjectToSimpleString( join_hash );
2373 // punt if we don't know about the core class (and it's not a function)
2374 if (!from_function && !(core_meta = osrfHashGet( oilsIDL(), core_class ))) {
2379 // if the select list is empty, or the core class field list is '*',
2380 // build the default select list ...
2382 selhash = defaultselhash = jsonNewObjectType(JSON_HASH);
2383 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2384 } else if ( (tmp_const = jsonObjectGetKeyConst( selhash, core_class )) && tmp_const->type == JSON_STRING ) {
2385 char* _x = jsonObjectToSimpleString( tmp_const );
2386 if (!strncmp( "*", _x, 1 )) {
2387 jsonObjectRemoveKey( selhash, core_class );
2388 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2394 growing_buffer* sql_buf = buffer_init(128);
2396 // temp buffer for the SELECT list
2397 growing_buffer* select_buf = buffer_init(128);
2398 growing_buffer* order_buf = buffer_init(128);
2399 growing_buffer* group_buf = buffer_init(128);
2400 growing_buffer* having_buf = buffer_init(128);
2402 // Build a select list
2403 if(from_function) // From a function we select everything
2404 OSRF_BUFFER_ADD_CHAR( select_buf, '*' );
2407 // If we need to build a default list, do so
2408 jsonObject* _tmp = jsonObjectGetKey( selhash, core_class );
2409 if ( _tmp && !_tmp->size ) {
2413 osrfHash* core_fields = osrfHashGet( core_meta, "fields" );
2415 osrfStringArray* keys = osrfHashKeys( core_fields );
2416 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
2417 if( ! str_is_true( osrfHashGet( osrfHashGet( core_fields, field ), "virtual" ) ) )
2418 jsonObjectPush( _tmp, jsonNewObject( field ) ); // not virtual; use it
2420 osrfStringArrayFree(keys);
2423 // Now build the actual select list
2425 jsonObject* is_agg = jsonObjectFindPath(selhash, "//aggregate");
2428 jsonIterator* selclass_itr = jsonNewIterator( selhash );
2429 while ( (selclass = jsonIteratorNext( selclass_itr )) ) { // For each class
2431 // round trip through the idl, just to be safe
2432 const char* cname = selclass_itr->key;
2433 osrfHash* idlClass = osrfHashGet( oilsIDL(), cname );
2435 // No such class. Skip it.
2438 // Make sure the target relation is in the join tree.
2440 // At this point join_hash is a step down from the join_hash we
2441 // received as a parameter. If the original was a JSON_STRING,
2442 // then json_hash is now NULL. If the original was a JSON_HASH,
2443 // then json_hash is now the first (and only) entry in it,
2444 // denoting the core class. We've already excluded the
2445 // possibility that the original was a JSON_ARRAY, because in
2446 // that case from_function would be non-NULL, and we wouldn't
2449 if ( strcmp( core_class, cname )) {
2451 // There's only one class in the FROM clause,
2452 // and this isn't it. Skip it.
2455 if (join_hash->type == JSON_STRING) {
2456 string = jsonObjectToSimpleString(join_hash);
2457 int different = strcmp( string, cname );
2460 // There's only one class in the FROM clause,
2461 // and this isn't it. Skip it.
2464 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", cname);
2465 unsigned long size = found->size;
2466 jsonObjectFree( found );
2468 // No such class anywhere in the join tree. Skip it.
2473 // Look up some attributes of the current class, so that we
2474 // don't have to look them up again for each field
2475 osrfHash* class_field_set = osrfHashGet( idlClass, "fields" );
2476 char* class_pkey = osrfHashGet( idlClass, "primarykey" );
2477 char* class_tname = osrfHashGet( idlClass, "tablename" );
2479 // stitch together the column list ...
2480 jsonIterator* select_itr = jsonNewIterator( selclass );
2481 while ( (selfield = jsonIteratorNext( select_itr )) ) { // for each SELECT column
2483 // If we need a separator comma, add one
2487 OSRF_BUFFER_ADD_CHAR( select_buf, ',' );
2490 // ... if it's a string, just toss it on the pile
2491 if (selfield->type == JSON_STRING) {
2493 // again, just to be safe
2494 const char* _requested_col = selfield->value.s;
2495 osrfHash* field = osrfHashGet( class_field_set, _requested_col );
2496 if (!field) continue; // No such field in current class; skip it
2498 const char* col_name = osrfHashGet(field, "name");
2502 if (flags & DISABLE_I18N)
2505 i18n = osrfHashGet(field, "i18n");
2507 if( str_is_true( i18n ) ) {
2508 buffer_fadd( select_buf,
2509 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2510 class_tname, cname, col_name, class_pkey, cname, class_pkey, locale, col_name );
2512 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2515 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2518 // ... but it could be an object, in which case we check for a Field Transform
2521 char* _column = jsonObjectToSimpleString( jsonObjectGetKeyConst( selfield, "column" ) );
2523 // Get the field definition from the IDL
2524 osrfHash* field = osrfHashGet( class_field_set, _column );
2525 if (!field) continue; // No such field defined in IDL. Skip it.
2527 // Decide what to use as a column alias
2529 if ((tmp_const = jsonObjectGetKeyConst( selfield, "alias" ))) {
2530 _alias = jsonObjectToSimpleString( tmp_const );
2532 } else { // Use column name as its own alias
2535 _column = NULL; // To emphasize that we're through with _column
2537 if (jsonObjectGetKeyConst( selfield, "transform" )) {
2538 char* transform_str = searchFieldTransform(cname, field, selfield);
2539 buffer_fadd(select_buf, " %s AS \"%s\"", transform_str, _alias);
2540 free(transform_str);
2543 const char* fname = osrfHashGet(field, "name");
2547 if (flags & DISABLE_I18N)
2550 i18n = osrfHashGet(field, "i18n");
2552 if( str_is_true( i18n ) ) {
2553 buffer_fadd( select_buf,
2554 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2555 class_tname, cname, fname, class_pkey, cname, class_pkey, locale, _alias);
2557 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, fname, _alias);
2560 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, fname, _alias);
2567 if (is_agg->size || (flags & SELECT_DISTINCT)) {
2569 const jsonObject* aggregate_obj = jsonObjectGetKey( selfield, "aggregate" );
2570 if ( ! obj_is_true( aggregate_obj ) ) {
2574 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
2577 buffer_fadd(group_buf, " %d", sel_pos);
2579 } else if (is_agg = jsonObjectGetKey( selfield, "having" )) {
2583 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
2586 _column = searchFieldTransform(cname, field, selfield);
2587 OSRF_BUFFER_ADD_CHAR(group_buf, ' ');
2588 OSRF_BUFFER_ADD(group_buf, _column);
2589 _column = searchFieldTransform(cname, field, selfield);
2595 } // end while -- iterating across SELECT columns
2597 jsonIteratorFree(select_itr);
2598 } // end while -- iterating across classes
2600 jsonIteratorFree(selclass_itr);
2602 if (is_agg) jsonObjectFree(is_agg);
2606 char* col_list = buffer_release(select_buf);
2608 if (from_function) table = searchValueTransform(join_hash);
2609 else table = getSourceDefinition(core_meta);
2611 // Put it all together
2612 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\" ", col_list, table, core_class );
2616 if (!from_function) {
2617 // Now, walk the join tree and add that clause
2619 char* join_clause = searchJOIN( join_hash, core_meta );
2620 buffer_add(sql_buf, join_clause);
2624 // Build a WHERE clause, if there is one
2625 if ( search_hash ) {
2626 buffer_add(sql_buf, " WHERE ");
2628 // and it's on the WHERE clause
2629 char* pred = searchWHERE( search_hash, core_meta, AND_OP_JOIN, ctx );
2632 buffer_add(sql_buf, pred);
2636 osrfAppSessionStatus(
2638 OSRF_STATUS_INTERNALSERVERERROR,
2639 "osrfMethodException",
2641 "Severe query error in WHERE predicate -- see error log for more details"
2645 buffer_free(having_buf);
2646 buffer_free(group_buf);
2647 buffer_free(order_buf);
2648 buffer_free(sql_buf);
2649 if (defaultselhash) jsonObjectFree(defaultselhash);
2654 // Build a HAVING clause, if there is one
2655 if ( having_hash ) {
2656 buffer_add(sql_buf, " HAVING ");
2658 // and it's on the the WHERE clause
2659 char* pred = searchWHERE( having_hash, core_meta, AND_OP_JOIN, ctx );
2662 buffer_add(sql_buf, pred);
2666 osrfAppSessionStatus(
2668 OSRF_STATUS_INTERNALSERVERERROR,
2669 "osrfMethodException",
2671 "Severe query error in HAVING predicate -- see error log for more details"
2675 buffer_free(having_buf);
2676 buffer_free(group_buf);
2677 buffer_free(order_buf);
2678 buffer_free(sql_buf);
2679 if (defaultselhash) jsonObjectFree(defaultselhash);
2684 // Build an ORDER BY clause, if there is one
2686 jsonIterator* class_itr = jsonNewIterator( order_hash );
2687 while ( (snode = jsonIteratorNext( class_itr )) ) {
2689 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
2692 if ( snode->type == JSON_HASH ) {
2694 jsonIterator* order_itr = jsonNewIterator( snode );
2695 while ( (onode = jsonIteratorNext( order_itr )) ) {
2697 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
2700 char* direction = NULL;
2701 if ( onode->type == JSON_HASH ) {
2702 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
2703 string = searchFieldTransform(
2705 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
2709 growing_buffer* field_buf = buffer_init(16);
2710 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
2711 string = buffer_release(field_buf);
2714 if ( (tmp_const = jsonObjectGetKeyConst( onode, "direction" )) ) {
2715 direction = jsonObjectToSimpleString(tmp_const);
2716 if (!strncasecmp(direction, "d", 1)) {
2718 direction = " DESC";
2726 string = strdup(order_itr->key);
2727 direction = jsonObjectToSimpleString(onode);
2728 if (!strncasecmp(direction, "d", 1)) {
2730 direction = " DESC";
2740 buffer_add(order_buf, ", ");
2743 buffer_add(order_buf, string);
2747 buffer_add(order_buf, direction);
2751 // jsonIteratorFree(order_itr);
2753 } else if ( snode->type == JSON_ARRAY ) {
2755 jsonIterator* order_itr = jsonNewIterator( snode );
2756 while ( (onode = jsonIteratorNext( order_itr )) ) {
2758 char* _f = jsonObjectToSimpleString( onode );
2760 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, _f))
2766 buffer_add(order_buf, ", ");
2769 buffer_add(order_buf, _f);
2773 // jsonIteratorFree(order_itr);
2776 // IT'S THE OOOOOOOOOOOLD STYLE!
2778 osrfLogError(OSRF_LOG_MARK, "%s: Possible SQL injection attempt; direct order by is not allowed", MODULENAME);
2780 osrfAppSessionStatus(
2782 OSRF_STATUS_INTERNALSERVERERROR,
2783 "osrfMethodException",
2785 "Severe query error -- see error log for more details"
2790 buffer_free(having_buf);
2791 buffer_free(group_buf);
2792 buffer_free(order_buf);
2793 buffer_free(sql_buf);
2794 if (defaultselhash) jsonObjectFree(defaultselhash);
2795 jsonIteratorFree(class_itr);
2800 // jsonIteratorFree(class_itr);
2804 string = buffer_release(group_buf);
2806 if (strlen(string)) {
2807 OSRF_BUFFER_ADD( sql_buf, " GROUP BY " );
2808 OSRF_BUFFER_ADD( sql_buf, string );
2813 string = buffer_release(having_buf);
2815 if (strlen(string)) {
2816 OSRF_BUFFER_ADD( sql_buf, " HAVING " );
2817 OSRF_BUFFER_ADD( sql_buf, string );
2822 string = buffer_release(order_buf);
2824 if (strlen(string)) {
2825 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
2826 OSRF_BUFFER_ADD( sql_buf, string );
2832 string = jsonObjectToSimpleString(limit);
2833 buffer_fadd( sql_buf, " LIMIT %d", atoi(string) );
2838 string = jsonObjectToSimpleString(offset);
2839 buffer_fadd( sql_buf, " OFFSET %d", atoi(string) );
2843 if (!(flags & SUBSELECT)) OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
2846 if (defaultselhash) jsonObjectFree(defaultselhash);
2848 return buffer_release(sql_buf);
2852 static char* buildSELECT ( jsonObject* search_hash, jsonObject* order_hash, osrfHash* meta, osrfMethodContext* ctx ) {
2854 const char* locale = osrf_message_get_last_locale();
2856 osrfHash* fields = osrfHashGet(meta, "fields");
2857 char* core_class = osrfHashGet(meta, "classname");
2859 const jsonObject* join_hash = jsonObjectGetKeyConst( order_hash, "join" );
2861 jsonObject* node = NULL;
2862 jsonObject* snode = NULL;
2863 jsonObject* onode = NULL;
2864 const jsonObject* _tmp = NULL;
2865 jsonObject* selhash = NULL;
2866 jsonObject* defaultselhash = NULL;
2868 growing_buffer* sql_buf = buffer_init(128);
2869 growing_buffer* select_buf = buffer_init(128);
2871 if ( !(selhash = jsonObjectGetKey( order_hash, "select" )) ) {
2872 defaultselhash = jsonNewObjectType(JSON_HASH);
2873 selhash = defaultselhash;
2876 if ( !jsonObjectGetKeyConst(selhash,core_class) ) {
2877 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2878 jsonObject* flist = jsonObjectGetKey( selhash, core_class );
2883 osrfStringArray* keys = osrfHashKeys( fields );
2884 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
2885 if( ! str_is_true( osrfHashGet( osrfHashGet( fields, field ), "virtual" ) ) )
2886 jsonObjectPush( flist, jsonNewObject( field ) );
2888 osrfStringArrayFree(keys);
2892 jsonIterator* class_itr = jsonNewIterator( selhash );
2893 while ( (snode = jsonIteratorNext( class_itr )) ) {
2895 osrfHash* idlClass = osrfHashGet( oilsIDL(), class_itr->key );
2896 if (!idlClass) continue;
2897 char* cname = osrfHashGet(idlClass, "classname");
2899 if (strcmp(core_class,class_itr->key)) {
2900 if (!join_hash) continue;
2902 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", class_itr->key);
2904 jsonObjectFree(found);
2908 jsonObjectFree(found);
2911 jsonIterator* select_itr = jsonNewIterator( snode );
2912 while ( (node = jsonIteratorNext( select_itr )) ) {
2913 char* item_str = jsonObjectToSimpleString(node);
2914 osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), item_str );
2916 char* fname = osrfHashGet(field, "name");
2918 if (!field) continue;
2923 OSRF_BUFFER_ADD_CHAR(select_buf, ',');
2928 const jsonObject* no_i18n_obj = jsonObjectGetKey( order_hash, "no_i18n" );
2929 if ( obj_is_true( no_i18n_obj ) ) // Suppress internationalization?
2932 i18n = osrfHashGet(field, "i18n");
2934 if( str_is_true( i18n ) ) {
2935 char* pkey = osrfHashGet(idlClass, "primarykey");
2936 char* tname = osrfHashGet(idlClass, "tablename");
2938 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);
2940 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
2943 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
2947 jsonIteratorFree(select_itr);
2950 jsonIteratorFree(class_itr);
2952 char* col_list = buffer_release(select_buf);
2953 char* table = getSourceDefinition(meta);
2955 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\"", col_list, table, core_class );
2960 char* join_clause = searchJOIN( join_hash, meta );
2961 OSRF_BUFFER_ADD_CHAR(sql_buf, ' ');
2962 OSRF_BUFFER_ADD(sql_buf, join_clause);
2966 osrfLogDebug(OSRF_LOG_MARK, "%s pre-predicate SQL = %s",
2967 MODULENAME, OSRF_BUFFER_C_STR(sql_buf));
2969 buffer_add(sql_buf, " WHERE ");
2971 char* pred = searchWHERE( search_hash, meta, AND_OP_JOIN, ctx );
2973 osrfAppSessionStatus(
2975 OSRF_STATUS_INTERNALSERVERERROR,
2976 "osrfMethodException",
2978 "Severe query error -- see error log for more details"
2980 buffer_free(sql_buf);
2981 if(defaultselhash) jsonObjectFree(defaultselhash);
2984 buffer_add(sql_buf, pred);
2989 char* string = NULL;
2990 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "order_by" )) ){
2992 growing_buffer* order_buf = buffer_init(128);
2995 jsonIterator* class_itr = jsonNewIterator( _tmp );
2996 while ( (snode = jsonIteratorNext( class_itr )) ) {
2998 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
3001 if ( snode->type == JSON_HASH ) {
3003 jsonIterator* order_itr = jsonNewIterator( snode );
3004 while ( (onode = jsonIteratorNext( order_itr )) ) {
3006 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
3009 char* direction = NULL;
3010 if ( onode->type == JSON_HASH ) {
3011 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
3012 string = searchFieldTransform(
3014 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
3018 growing_buffer* field_buf = buffer_init(16);
3019 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
3020 string = buffer_release(field_buf);
3023 if ( (_tmp = jsonObjectGetKeyConst( onode, "direction" )) ) {
3024 direction = jsonObjectToSimpleString(_tmp);
3025 if (!strncasecmp(direction, "d", 1)) {
3027 direction = " DESC";
3035 string = strdup(order_itr->key);
3036 direction = jsonObjectToSimpleString(onode);
3037 if (!strncasecmp(direction, "d", 1)) {
3039 direction = " DESC";
3049 buffer_add(order_buf, ", ");
3052 buffer_add(order_buf, string);
3056 buffer_add(order_buf, direction);
3061 jsonIteratorFree(order_itr);
3064 string = jsonObjectToSimpleString(snode);
3065 buffer_add(order_buf, string);
3072 jsonIteratorFree(class_itr);
3074 string = buffer_release(order_buf);
3076 if (strlen(string)) {
3077 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
3078 OSRF_BUFFER_ADD( sql_buf, string );
3084 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "limit" )) ){
3085 string = jsonObjectToSimpleString(_tmp);
3094 _tmp = jsonObjectGetKeyConst( order_hash, "offset" );
3096 string = jsonObjectToSimpleString(_tmp);
3106 if (defaultselhash) jsonObjectFree(defaultselhash);
3108 OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
3109 return buffer_release(sql_buf);
3112 int doJSONSearch ( osrfMethodContext* ctx ) {
3113 if(osrfMethodVerifyContext( ctx )) {
3114 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
3118 osrfLogDebug(OSRF_LOG_MARK, "Recieved query request");
3123 dbhandle = writehandle;
3125 jsonObject* hash = jsonObjectGetIndex(ctx->params, 0);
3129 if ( obj_is_true( jsonObjectGetKey( hash, "distinct" ) ) )
3130 flags |= SELECT_DISTINCT;
3132 if ( obj_is_true( jsonObjectGetKey( hash, "no_i18n" ) ) )
3133 flags |= DISABLE_I18N;
3135 osrfLogDebug(OSRF_LOG_MARK, "Building SQL ...");
3138 jsonObjectGetKey( hash, "select" ),
3139 jsonObjectGetKey( hash, "from" ),
3140 jsonObjectGetKey( hash, "where" ),
3141 jsonObjectGetKey( hash, "having" ),
3142 jsonObjectGetKey( hash, "order_by" ),
3143 jsonObjectGetKey( hash, "limit" ),
3144 jsonObjectGetKey( hash, "offset" ),
3153 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3154 dbi_result result = dbi_conn_query(dbhandle, sql);
3157 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3159 if (dbi_result_first_row(result)) {
3160 /* JSONify the result */
3161 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3164 jsonObject* return_val = oilsMakeJSONFromResult( result );
3165 osrfAppRespond( ctx, return_val );
3166 jsonObjectFree( return_val );
3167 } while (dbi_result_next_row(result));
3170 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
3173 osrfAppRespondComplete( ctx, NULL );
3175 /* clean up the query */
3176 dbi_result_free(result);
3180 osrfLogError(OSRF_LOG_MARK, "%s: Error with query [%s]", MODULENAME, sql);
3181 osrfAppSessionStatus(
3183 OSRF_STATUS_INTERNALSERVERERROR,
3184 "osrfMethodException",
3186 "Severe query error -- see error log for more details"
3194 static jsonObject* doFieldmapperSearch ( osrfMethodContext* ctx, osrfHash* meta,
3195 const jsonObject* params, int* err ) {
3198 dbhandle = writehandle;
3200 osrfHash* links = osrfHashGet(meta, "links");
3201 osrfHash* fields = osrfHashGet(meta, "fields");
3202 char* core_class = osrfHashGet(meta, "classname");
3203 char* pkey = osrfHashGet(meta, "primarykey");
3205 const jsonObject* _tmp;
3207 jsonObject* search_hash = jsonObjectGetIndex(params, 0);
3208 jsonObject* order_hash = jsonObjectGetIndex(params, 1);
3210 char* sql = buildSELECT( search_hash, order_hash, meta, ctx );
3212 osrfLogDebug(OSRF_LOG_MARK, "Problem building query, returning NULL");
3217 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3219 dbi_result result = dbi_conn_query(dbhandle, sql);
3220 if( NULL == result ) {
3221 osrfLogError(OSRF_LOG_MARK, "%s: Error retrieving %s with query [%s]",
3222 MODULENAME, osrfHashGet(meta, "fieldmapper"), sql);
3223 osrfAppSessionStatus(
3225 OSRF_STATUS_INTERNALSERVERERROR,
3226 "osrfMethodException",
3228 "Severe query error -- see error log for more details"
3235 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3238 jsonObject* res_list = jsonNewObjectType(JSON_ARRAY);
3239 osrfHash* dedup = osrfNewHash();
3241 if (dbi_result_first_row(result)) {
3242 /* JSONify the result */
3243 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3245 obj = oilsMakeFieldmapperFromResult( result, meta );
3246 char* pkey_val = oilsFMGetString( obj, pkey );
3247 if ( osrfHashGet( dedup, pkey_val ) ) {
3248 jsonObjectFree(obj);
3251 osrfHashSet( dedup, pkey_val, pkey_val );
3252 jsonObjectPush(res_list, obj);
3254 } while (dbi_result_next_row(result));
3256 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s",
3260 osrfHashFree(dedup);
3261 /* clean up the query */
3262 dbi_result_free(result);
3265 if (res_list->size && order_hash) {
3266 _tmp = jsonObjectGetKeyConst( order_hash, "flesh" );
3268 int x = (int)jsonObjectGetNumber(_tmp);
3269 if (x == -1 || x > max_flesh_depth) x = max_flesh_depth;
3271 const jsonObject* temp_blob;
3272 if ((temp_blob = jsonObjectGetKeyConst( order_hash, "flesh_fields" )) && x > 0) {
3274 jsonObject* flesh_blob = jsonObjectClone( temp_blob );
3275 const jsonObject* flesh_fields = jsonObjectGetKeyConst( flesh_blob, core_class );
3277 osrfStringArray* link_fields = NULL;
3280 if (flesh_fields->size == 1) {
3281 char* _t = jsonObjectToSimpleString( jsonObjectGetIndex( flesh_fields, 0 ) );
3282 if (!strcmp(_t,"*")) link_fields = osrfHashKeys( links );
3288 link_fields = osrfNewStringArray(1);
3289 jsonIterator* _i = jsonNewIterator( flesh_fields );
3290 while ((_f = jsonIteratorNext( _i ))) {
3291 osrfStringArrayAdd( link_fields, jsonObjectToSimpleString( _f ) );
3293 jsonIteratorFree(_i);
3298 jsonIterator* itr = jsonNewIterator( res_list );
3299 while ((cur = jsonIteratorNext( itr ))) {
3304 while ( (link_field = osrfStringArrayGetString(link_fields, i++)) ) {
3306 osrfLogDebug(OSRF_LOG_MARK, "Starting to flesh %s", link_field);
3308 osrfHash* kid_link = osrfHashGet(links, link_field);
3309 if (!kid_link) continue;
3311 osrfHash* field = osrfHashGet(fields, link_field);
3312 if (!field) continue;
3314 osrfHash* value_field = field;
3316 osrfHash* kid_idl = osrfHashGet(oilsIDL(), osrfHashGet(kid_link, "class"));
3317 if (!kid_idl) continue;
3319 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3320 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3323 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) { // might_have
3324 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3327 osrfStringArray* link_map = osrfHashGet( kid_link, "map" );
3329 if (link_map->size > 0) {
3330 jsonObject* _kid_key = jsonNewObjectType(JSON_ARRAY);
3333 jsonNewObject( osrfStringArrayGetString( link_map, 0 ) )
3338 osrfHashGet(kid_link, "class"),
3345 "Link field: %s, remote class: %s, fkey: %s, reltype: %s",
3346 osrfHashGet(kid_link, "field"),
3347 osrfHashGet(kid_link, "class"),
3348 osrfHashGet(kid_link, "key"),
3349 osrfHashGet(kid_link, "reltype")
3352 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
3353 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // search hash
3354 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // order/flesh hash
3356 osrfLogDebug(OSRF_LOG_MARK, "Creating dummy params object...");
3359 jsonObjectToSimpleString(
3362 atoi( osrfHashGet(value_field, "array_position") )
3367 osrfLogDebug(OSRF_LOG_MARK, "Nothing to search for!");
3372 jsonObjectGetIndex(fake_params, 0),
3373 osrfHashGet(kid_link, "key"),
3374 jsonNewObject( search_key )
3381 jsonObjectGetIndex(fake_params, 1),
3383 jsonNewNumberObject( (double)(x - 1 + link_map->size) )
3387 jsonObjectSetKey( jsonObjectGetIndex(fake_params, 1), "flesh_fields", jsonObjectClone(flesh_blob) );
3389 if (jsonObjectGetKeyConst(order_hash, "order_by")) {
3391 jsonObjectGetIndex(fake_params, 1),
3393 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "order_by"))
3397 if (jsonObjectGetKeyConst(order_hash, "select")) {
3399 jsonObjectGetIndex(fake_params, 1),
3401 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "select"))
3405 jsonObject* kids = doFieldmapperSearch(ctx, kid_idl, fake_params, err);
3408 jsonObjectFree( fake_params );
3409 osrfStringArrayFree(link_fields);
3410 jsonIteratorFree(itr);
3411 jsonObjectFree(res_list);
3412 jsonObjectFree(flesh_blob);
3416 osrfLogDebug(OSRF_LOG_MARK, "Search for %s return %d linked objects", osrfHashGet(kid_link, "class"), kids->size);
3418 jsonObject* X = NULL;
3419 if ( link_map->size > 0 && kids->size > 0 ) {
3421 kids = jsonNewObjectType(JSON_ARRAY);
3423 jsonObject* _k_node;
3424 jsonIterator* _k = jsonNewIterator( X );
3425 while ((_k_node = jsonIteratorNext( _k ))) {
3431 (unsigned long)atoi(
3437 osrfHashGet(kid_link, "class")
3441 osrfStringArrayGetString( link_map, 0 )
3450 jsonIteratorFree(_k);
3453 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_a" )) || !(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) {
3454 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3457 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3458 jsonObjectClone( jsonObjectGetIndex(kids, 0) )
3462 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3463 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3466 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3467 jsonObjectClone( kids )
3472 jsonObjectFree(kids);
3476 jsonObjectFree( kids );
3477 jsonObjectFree( fake_params );
3479 osrfLogDebug(OSRF_LOG_MARK, "Fleshing of %s complete", osrfHashGet(kid_link, "field"));
3480 osrfLogDebug(OSRF_LOG_MARK, "%s", jsonObjectToJSON(cur));
3484 jsonObjectFree( flesh_blob );
3485 osrfStringArrayFree(link_fields);
3486 jsonIteratorFree(itr);
3495 static jsonObject* doUpdate(osrfMethodContext* ctx, int* err ) {
3497 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3499 jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
3501 jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
3504 if (!verifyObjectClass(ctx, target)) {
3509 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3510 osrfAppSessionStatus(
3512 OSRF_STATUS_BADREQUEST,
3513 "osrfMethodException",
3515 "No active transaction -- required for UPDATE"
3521 // The following test is harmless but redundant. If a class is
3522 // readonly, we don't register an update method for it.
3523 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
3524 osrfAppSessionStatus(
3526 OSRF_STATUS_BADREQUEST,
3527 "osrfMethodException",
3529 "Cannot UPDATE readonly class"
3535 dbhandle = writehandle;
3537 char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
3539 // Set the last_xact_id
3540 int index = oilsIDL_ntop( target->classname, "last_xact_id" );
3542 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
3543 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
3546 char* pkey = osrfHashGet(meta, "primarykey");
3547 osrfHash* fields = osrfHashGet(meta, "fields");
3549 char* id = oilsFMGetString( target, pkey );
3553 "%s updating %s object with %s = %s",
3555 osrfHashGet(meta, "fieldmapper"),
3560 growing_buffer* sql = buffer_init(128);
3561 buffer_fadd(sql,"UPDATE %s SET", osrfHashGet(meta, "tablename"));
3566 osrfStringArray* field_list = osrfHashKeys( fields );
3567 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
3569 osrfHash* field = osrfHashGet( fields, field_name );
3571 if(!( strcmp( field_name, pkey ) )) continue;
3572 if( str_is_true( osrfHashGet(osrfHashGet(fields,field_name), "virtual") ) )
3575 const jsonObject* field_object = oilsFMGetObject( target, field_name );
3578 if (field_object && field_object->classname) {
3579 value = oilsFMGetString(
3581 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
3584 value = jsonObjectToSimpleString( field_object );
3587 osrfLogDebug( OSRF_LOG_MARK, "Updating %s object with %s = %s", osrfHashGet(meta, "fieldmapper"), field_name, value);
3589 if (!field_object || field_object->type == JSON_NULL) {
3590 if ( !(!( strcmp( osrfHashGet(meta, "classname"), "au" ) ) && !( strcmp( field_name, "passwd" ) )) ) { // arg at the special case!
3591 if (first) first = 0;
3592 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3593 buffer_fadd( sql, " %s = NULL", field_name );
3596 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
3597 if (first) first = 0;
3598 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3600 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
3601 buffer_fadd( sql, " %s = %ld", field_name, atol(value) );
3602 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
3603 buffer_fadd( sql, " %s = %f", field_name, atof(value) );
3606 osrfLogDebug( OSRF_LOG_MARK, "%s is of type %s", field_name, osrfHashGet(field, "datatype"));
3609 if ( dbi_conn_quote_string(dbhandle, &value) ) {
3610 if (first) first = 0;
3611 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3612 buffer_fadd( sql, " %s = %s", field_name, value );
3615 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
3616 osrfAppSessionStatus(
3618 OSRF_STATUS_INTERNALSERVERERROR,
3619 "osrfMethodException",
3621 "Error quoting string -- please see the error log for more details"
3635 jsonObject* obj = jsonNewObject(id);
3637 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
3638 dbi_conn_quote_string(dbhandle, &id);
3640 buffer_fadd( sql, " WHERE %s = %s;", pkey, id );
3642 char* query = buffer_release(sql);
3643 osrfLogDebug(OSRF_LOG_MARK, "%s: Update SQL [%s]", MODULENAME, query);
3645 dbi_result result = dbi_conn_query(dbhandle, query);
3649 jsonObjectFree(obj);
3650 obj = jsonNewObject(NULL);
3653 "%s ERROR updating %s object with %s = %s",
3655 osrfHashGet(meta, "fieldmapper"),
3666 static jsonObject* doDelete(osrfMethodContext* ctx, int* err ) {
3668 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3670 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3671 osrfAppSessionStatus(
3673 OSRF_STATUS_BADREQUEST,
3674 "osrfMethodException",
3676 "No active transaction -- required for DELETE"
3682 // The following test is harmless but redundant. If a class is
3683 // readonly, we don't register a delete method for it.
3684 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
3685 osrfAppSessionStatus(
3687 OSRF_STATUS_BADREQUEST,
3688 "osrfMethodException",
3690 "Cannot DELETE readonly class"
3696 dbhandle = writehandle;
3700 char* pkey = osrfHashGet(meta, "primarykey");
3708 if (jsonObjectGetIndex(ctx->params, _obj_pos)->classname) {
3709 if (!verifyObjectClass(ctx, jsonObjectGetIndex( ctx->params, _obj_pos ))) {
3714 id = oilsFMGetString( jsonObjectGetIndex(ctx->params, _obj_pos), pkey );
3717 if (!verifyObjectPCRUD( ctx, NULL )) {
3722 id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, _obj_pos));
3727 "%s deleting %s object with %s = %s",
3729 osrfHashGet(meta, "fieldmapper"),
3734 obj = jsonNewObject(id);
3736 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
3737 dbi_conn_quote_string(writehandle, &id);
3739 dbi_result result = dbi_conn_queryf(writehandle, "DELETE FROM %s WHERE %s = %s;", osrfHashGet(meta, "tablename"), pkey, id);
3742 jsonObjectFree(obj);
3743 obj = jsonNewObject(NULL);
3746 "%s ERROR deleting %s object with %s = %s",
3748 osrfHashGet(meta, "fieldmapper"),
3761 static jsonObject* oilsMakeFieldmapperFromResult( dbi_result result, osrfHash* meta) {
3762 if(!(result && meta)) return jsonNULL;
3764 jsonObject* object = jsonNewObject(NULL);
3765 jsonObjectSetClass(object, osrfHashGet(meta, "classname"));
3767 osrfHash* fields = osrfHashGet(meta, "fields");
3769 osrfLogInternal(OSRF_LOG_MARK, "Setting object class to %s ", object->classname);
3773 char dt_string[256];
3777 int columnIndex = 1;
3779 unsigned short type;
3780 const char* columnName;
3782 /* cycle through the column list */
3783 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
3785 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
3787 fmIndex = -1; // reset the position
3789 /* determine the field type and storage attributes */
3790 type = dbi_result_get_field_type(result, columnName);
3791 attr = dbi_result_get_field_attribs(result, columnName);
3793 /* fetch the fieldmapper index */
3794 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
3796 if ( str_is_true( osrfHashGet(_f, "virtual") ) )
3799 const char* pos = (char*)osrfHashGet(_f, "array_position");
3800 if ( !pos ) continue;
3802 fmIndex = atoi( pos );
3803 osrfLogInternal(OSRF_LOG_MARK, "... Found column at position [%s]...", pos);
3808 if (dbi_result_field_is_null(result, columnName)) {
3809 jsonObjectSetIndex( object, fmIndex, jsonNewObject(NULL) );
3814 case DBI_TYPE_INTEGER :
3816 if( attr & DBI_INTEGER_SIZE8 )
3817 jsonObjectSetIndex( object, fmIndex,
3818 jsonNewNumberObject(dbi_result_get_longlong(result, columnName)));
3820 jsonObjectSetIndex( object, fmIndex,
3821 jsonNewNumberObject(dbi_result_get_int(result, columnName)));
3825 case DBI_TYPE_DECIMAL :
3826 jsonObjectSetIndex( object, fmIndex,
3827 jsonNewNumberObject(dbi_result_get_double(result, columnName)));
3830 case DBI_TYPE_STRING :
3836 jsonNewObject( dbi_result_get_string(result, columnName) )
3841 case DBI_TYPE_DATETIME :
3843 memset(dt_string, '\0', sizeof(dt_string));
3844 memset(&gmdt, '\0', sizeof(gmdt));
3846 _tmp_dt = dbi_result_get_datetime(result, columnName);
3849 if (!(attr & DBI_DATETIME_DATE)) {
3850 gmtime_r( &_tmp_dt, &gmdt );
3851 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
3852 } else if (!(attr & DBI_DATETIME_TIME)) {
3853 localtime_r( &_tmp_dt, &gmdt );
3854 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
3856 localtime_r( &_tmp_dt, &gmdt );
3857 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
3860 jsonObjectSetIndex( object, fmIndex, jsonNewObject(dt_string) );
3864 case DBI_TYPE_BINARY :
3865 osrfLogError( OSRF_LOG_MARK,
3866 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
3874 static jsonObject* oilsMakeJSONFromResult( dbi_result result ) {
3875 if(!result) return jsonNULL;
3877 jsonObject* object = jsonNewObject(NULL);
3880 char dt_string[256];
3884 int columnIndex = 1;
3886 unsigned short type;
3887 const char* columnName;
3889 /* cycle through the column list */
3890 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
3892 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
3894 fmIndex = -1; // reset the position
3896 /* determine the field type and storage attributes */
3897 type = dbi_result_get_field_type(result, columnName);
3898 attr = dbi_result_get_field_attribs(result, columnName);
3900 if (dbi_result_field_is_null(result, columnName)) {
3901 jsonObjectSetKey( object, columnName, jsonNewObject(NULL) );
3906 case DBI_TYPE_INTEGER :
3908 if( attr & DBI_INTEGER_SIZE8 )
3909 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_longlong(result, columnName)) );
3911 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_int(result, columnName)) );
3914 case DBI_TYPE_DECIMAL :
3915 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_double(result, columnName)) );
3918 case DBI_TYPE_STRING :
3919 jsonObjectSetKey( object, columnName, jsonNewObject(dbi_result_get_string(result, columnName)) );
3922 case DBI_TYPE_DATETIME :
3924 memset(dt_string, '\0', sizeof(dt_string));
3925 memset(&gmdt, '\0', sizeof(gmdt));
3927 _tmp_dt = dbi_result_get_datetime(result, columnName);
3930 if (!(attr & DBI_DATETIME_DATE)) {
3931 gmtime_r( &_tmp_dt, &gmdt );
3932 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
3933 } else if (!(attr & DBI_DATETIME_TIME)) {
3934 localtime_r( &_tmp_dt, &gmdt );
3935 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
3937 localtime_r( &_tmp_dt, &gmdt );
3938 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
3941 jsonObjectSetKey( object, columnName, jsonNewObject(dt_string) );
3944 case DBI_TYPE_BINARY :
3945 osrfLogError( OSRF_LOG_MARK,
3946 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
3954 // Interpret a string as true or false
3955 static int str_is_true( const char* str ) {
3956 if( NULL == str || strcasecmp( str, "true" ) )
3962 // Interpret a jsonObject as true or false
3963 static int obj_is_true( const jsonObject* obj ) {
3966 else switch( obj->type )
3974 if( strcasecmp( obj->value.s, "true" ) )
3978 case JSON_NUMBER : // Support 1/0 for perl's sake
3979 if( jsonObjectGetNumber( obj ) == 1.0 )