1 #include "opensrf/osrf_application.h"
2 #include "opensrf/osrf_settings.h"
3 #include "opensrf/osrf_message.h"
4 #include "opensrf/utils.h"
5 #include "opensrf/osrf_json.h"
6 #include "opensrf/log.h"
7 #include "openils/oils_utils.h"
16 # define MODULENAME "open-ils.reporter-store"
19 # define MODULENAME "open-ils.pcrud"
21 # define MODULENAME "open-ils.cstore"
26 #define DISABLE_I18N 2
27 #define SELECT_DISTINCT 1
31 int osrfAppChildInit();
32 int osrfAppInitialize();
33 void osrfAppChildExit();
35 static int verifyObjectClass ( osrfMethodContext*, const jsonObject* );
37 int beginTransaction ( osrfMethodContext* );
38 int commitTransaction ( osrfMethodContext* );
39 int rollbackTransaction ( osrfMethodContext* );
41 int setSavepoint ( osrfMethodContext* );
42 int releaseSavepoint ( osrfMethodContext* );
43 int rollbackSavepoint ( osrfMethodContext* );
45 int doJSONSearch ( osrfMethodContext* );
47 int dispatchCRUDMethod ( osrfMethodContext* );
48 static jsonObject* doCreate ( osrfMethodContext*, int* );
49 static jsonObject* doRetrieve ( osrfMethodContext*, int* );
50 static jsonObject* doUpdate ( osrfMethodContext*, int* );
51 static jsonObject* doDelete ( osrfMethodContext*, int* );
52 static jsonObject* doFieldmapperSearch ( osrfMethodContext*, osrfHash*,
53 const jsonObject*, int* );
54 static jsonObject* oilsMakeFieldmapperFromResult( dbi_result, osrfHash* );
55 static jsonObject* oilsMakeJSONFromResult( dbi_result );
57 static char* searchWriteSimplePredicate ( const char*, osrfHash*,
58 const char*, const char*, const char* );
59 static char* searchSimplePredicate ( const char*, const char*, osrfHash*, const jsonObject* );
60 static char* searchFunctionPredicate ( const char*, osrfHash*, const jsonObject*, const char* );
61 static char* searchFieldTransform ( const char*, osrfHash*, const jsonObject*);
62 static char* searchFieldTransformPredicate ( const char*, osrfHash*, jsonObject*, const char* );
63 static char* searchBETWEENPredicate ( const char*, osrfHash*, jsonObject* );
64 static char* searchINPredicate ( const char*, osrfHash*,
65 jsonObject*, const char*, osrfMethodContext* );
66 static char* searchPredicate ( const char*, osrfHash*, jsonObject*, osrfMethodContext* );
67 static char* searchJOIN ( const jsonObject*, osrfHash* );
68 static char* searchWHERE ( const jsonObject*, osrfHash*, int, osrfMethodContext* );
69 static char* buildSELECT ( jsonObject*, jsonObject*, osrfHash*, osrfMethodContext* );
71 char* SELECT ( osrfMethodContext*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, int );
73 void userDataFree( void* );
74 static void sessionDataFree( char*, void* );
75 static char* getSourceDefinition( osrfHash* );
76 static int str_is_true( const char* str );
77 static int obj_is_true( const jsonObject* obj );
80 static jsonObject* verifyUserPCRUD( osrfMethodContext* );
81 static int verifyObjectPCRUD( osrfMethodContext*, const jsonObject* );
84 static dbi_conn writehandle; /* our MASTER db connection */
85 static dbi_conn dbhandle; /* our CURRENT db connection */
86 //static osrfHash * readHandles;
87 static jsonObject* jsonNULL = NULL; //
88 static int max_flesh_depth = 100;
90 /* called when this process is about to exit */
91 void osrfAppChildExit() {
92 osrfLogDebug(OSRF_LOG_MARK, "Child is exiting, disconnecting from database...");
95 if (writehandle == dbhandle) same = 1;
97 dbi_conn_query(writehandle, "ROLLBACK;");
98 dbi_conn_close(writehandle);
101 if (dbhandle && !same)
102 dbi_conn_close(dbhandle);
104 // XXX add cleanup of readHandles whenever that gets used
109 int osrfAppInitialize() {
111 osrfLogInfo(OSRF_LOG_MARK, "Initializing the CStore Server...");
112 osrfLogInfo(OSRF_LOG_MARK, "Finding XML file...");
114 if (!oilsIDLInit( osrf_settings_host_value("/IDL") )) return 1; /* return non-zero to indicate error */
116 growing_buffer* method_name = buffer_init(64);
118 // Generic search thingy
119 buffer_add(method_name, MODULENAME);
120 buffer_add(method_name, ".json_query");
121 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
122 "doJSONSearch", "", 1, OSRF_METHOD_STREAMING );
125 // first we register all the transaction and savepoint methods
126 buffer_reset(method_name);
127 OSRF_BUFFER_ADD(method_name, MODULENAME);
128 OSRF_BUFFER_ADD(method_name, ".transaction.begin");
129 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
130 "beginTransaction", "", 0, 0 );
132 buffer_reset(method_name);
133 OSRF_BUFFER_ADD(method_name, MODULENAME);
134 OSRF_BUFFER_ADD(method_name, ".transaction.commit");
135 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
136 "commitTransaction", "", 0, 0 );
138 buffer_reset(method_name);
139 OSRF_BUFFER_ADD(method_name, MODULENAME);
140 OSRF_BUFFER_ADD(method_name, ".transaction.rollback");
141 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
142 "rollbackTransaction", "", 0, 0 );
144 buffer_reset(method_name);
145 OSRF_BUFFER_ADD(method_name, MODULENAME);
146 OSRF_BUFFER_ADD(method_name, ".savepoint.set");
147 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
148 "setSavepoint", "", 1, 0 );
150 buffer_reset(method_name);
151 OSRF_BUFFER_ADD(method_name, MODULENAME);
152 OSRF_BUFFER_ADD(method_name, ".savepoint.release");
153 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
154 "releaseSavepoint", "", 1, 0 );
156 buffer_reset(method_name);
157 OSRF_BUFFER_ADD(method_name, MODULENAME);
158 OSRF_BUFFER_ADD(method_name, ".savepoint.rollback");
159 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
160 "rollbackSavepoint", "", 1, 0 );
162 buffer_free(method_name);
164 static const char* global_method[] = {
172 const int global_method_count
173 = sizeof( global_method ) / sizeof ( global_method[0] );
177 osrfStringArray* classes = osrfHashKeys( oilsIDL() );
178 osrfLogDebug(OSRF_LOG_MARK, "%d classes loaded", classes->size );
179 osrfLogDebug(OSRF_LOG_MARK,
180 "At least %d methods will be generated", classes->size * global_method_count);
182 while ( (classname = osrfStringArrayGetString(classes, c_index++)) ) {
183 osrfLogInfo(OSRF_LOG_MARK, "Generating class methods for %s", classname);
185 osrfHash* idlClass = osrfHashGet(oilsIDL(), classname);
187 if (!osrfStringArrayContains( osrfHashGet(idlClass, "controller"), MODULENAME )) {
188 osrfLogInfo(OSRF_LOG_MARK, "%s is not listed as a controller for %s, moving on", MODULENAME, classname);
192 if ( str_is_true( osrfHashGet(idlClass, "virtual") ) ) {
193 osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
197 // Look up some other attributes of the current class
198 const char* idlClass_fieldmapper = osrfHashGet(idlClass, "fieldmapper");
199 const char* readonly = osrfHashGet(idlClass, "readonly");
201 osrfHash* idlClass_permacrud = osrfHashGet(idlClass, "permacrud");
205 for( i = 0; i < global_method_count; ++i ) {
206 const char* method_type = global_method[ i ];
207 osrfLogDebug(OSRF_LOG_MARK,
208 "Using files to build %s class methods for %s", method_type, classname);
210 if (!idlClass_fieldmapper) continue;
213 if (!idlClass_permacrud) continue;
215 const char* tmp_method = method_type;
216 if ( *tmp_method == 'i' || *tmp_method == 's') {
217 tmp_method = "retrieve";
219 if (!osrfHashGet( idlClass_permacrud, tmp_method )) continue;
222 if ( str_is_true( readonly ) &&
223 ( *method_type == 'c' || *method_type == 'u' || *method_type == 'd')
226 osrfHash* method_meta = osrfNewHash();
227 osrfHashSet(method_meta, idlClass, "class");
229 method_name = buffer_init(64);
231 buffer_fadd(method_name, "%s.%s.%s", MODULENAME, method_type, classname);
235 char* _fm = strdup( idlClass_fieldmapper );
236 part = strtok_r(_fm, ":", &st_tmp);
238 buffer_fadd(method_name, "%s.direct.%s", MODULENAME, part);
240 while ((part = strtok_r(NULL, ":", &st_tmp))) {
241 OSRF_BUFFER_ADD_CHAR(method_name, '.');
242 OSRF_BUFFER_ADD(method_name, part);
244 OSRF_BUFFER_ADD_CHAR(method_name, '.');
245 OSRF_BUFFER_ADD(method_name, method_type);
249 char* method = buffer_release(method_name);
251 osrfHashSet( method_meta, method, "methodname" );
252 osrfHashSet( method_meta, strdup(method_type), "methodtype" );
255 if (*method_type == 'i' || *method_type == 's') {
256 flags = flags | OSRF_METHOD_STREAMING;
259 osrfAppRegisterExtendedMethod(
262 "dispatchCRUDMethod",
276 static char* getSourceDefinition( osrfHash* class ) {
278 char* tabledef = osrfHashGet(class, "tablename");
281 tabledef = strdup(tabledef);
283 tabledef = osrfHashGet(class, "source_definition");
285 growing_buffer* tablebuf = buffer_init(128);
286 buffer_fadd( tablebuf, "(%s)", tabledef );
287 tabledef = buffer_release(tablebuf);
289 const char* classname = osrfHashGet( class, "classname" );
294 "%s ERROR No tablename or source_definition for class \"%s\"",
305 * Connects to the database
307 int osrfAppChildInit() {
309 osrfLogDebug(OSRF_LOG_MARK, "Attempting to initialize libdbi...");
310 dbi_initialize(NULL);
311 osrfLogDebug(OSRF_LOG_MARK, "... libdbi initialized.");
313 char* driver = osrf_settings_host_value("/apps/%s/app_settings/driver", MODULENAME);
314 char* user = osrf_settings_host_value("/apps/%s/app_settings/database/user", MODULENAME);
315 char* host = osrf_settings_host_value("/apps/%s/app_settings/database/host", MODULENAME);
316 char* port = osrf_settings_host_value("/apps/%s/app_settings/database/port", MODULENAME);
317 char* db = osrf_settings_host_value("/apps/%s/app_settings/database/db", MODULENAME);
318 char* pw = osrf_settings_host_value("/apps/%s/app_settings/database/pw", MODULENAME);
319 char* md = osrf_settings_host_value("/apps/%s/app_settings/max_query_recursion", MODULENAME);
321 osrfLogDebug(OSRF_LOG_MARK, "Attempting to load the database driver [%s]...", driver);
322 writehandle = dbi_conn_new(driver);
325 osrfLogError(OSRF_LOG_MARK, "Error loading database driver [%s]", driver);
328 osrfLogDebug(OSRF_LOG_MARK, "Database driver [%s] seems OK", driver);
330 osrfLogInfo(OSRF_LOG_MARK, "%s connecting to database. host=%s, "
331 "port=%s, user=%s, pw=%s, db=%s", MODULENAME, host, port, user, pw, db );
333 if(host) dbi_conn_set_option(writehandle, "host", host );
334 if(port) dbi_conn_set_option_numeric( writehandle, "port", atoi(port) );
335 if(user) dbi_conn_set_option(writehandle, "username", user);
336 if(pw) dbi_conn_set_option(writehandle, "password", pw );
337 if(db) dbi_conn_set_option(writehandle, "dbname", db );
339 if(md) max_flesh_depth = atoi(md);
340 if(max_flesh_depth < 0) max_flesh_depth = 1;
341 if(max_flesh_depth > 1000) max_flesh_depth = 1000;
350 if (dbi_conn_connect(writehandle) < 0) {
352 if (dbi_conn_connect(writehandle) < 0) {
353 dbi_conn_error(writehandle, &err);
354 osrfLogError( OSRF_LOG_MARK, "Error connecting to database: %s", err);
359 osrfLogInfo(OSRF_LOG_MARK, "%s successfully connected to the database", MODULENAME);
365 osrfStringArray* classes = osrfHashKeys( oilsIDL() );
367 while ( (classname = osrfStringArrayGetString(classes, i++)) ) {
368 osrfHash* class = osrfHashGet( oilsIDL(), classname );
369 osrfHash* fields = osrfHashGet( class, "fields" );
371 if( str_is_true( osrfHashGet(class, "virtual") ) ) {
372 osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
376 char* tabledef = getSourceDefinition(class);
378 tabledef = strdup( "(null)" );
380 growing_buffer* sql_buf = buffer_init(32);
381 buffer_fadd( sql_buf, "SELECT * FROM %s AS x WHERE 1=0;", tabledef );
385 char* sql = buffer_release(sql_buf);
386 osrfLogDebug(OSRF_LOG_MARK, "%s Investigatory SQL = %s", MODULENAME, sql);
388 dbi_result result = dbi_conn_query(writehandle, sql);
394 const char* columnName;
396 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
398 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
400 /* fetch the fieldmapper index */
401 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
403 osrfLogDebug(OSRF_LOG_MARK, "Found [%s] in IDL hash...", (char*)columnName);
405 /* determine the field type and storage attributes */
406 type = dbi_result_get_field_type(result, columnName);
407 attr = dbi_result_get_field_attribs(result, columnName);
411 case DBI_TYPE_INTEGER :
413 if ( !osrfHashGet(_f, "primitive") )
414 osrfHashSet(_f,"number", "primitive");
416 if( attr & DBI_INTEGER_SIZE8 )
417 osrfHashSet(_f,"INT8", "datatype");
419 osrfHashSet(_f,"INT", "datatype");
422 case DBI_TYPE_DECIMAL :
423 if ( !osrfHashGet(_f, "primitive") )
424 osrfHashSet(_f,"number", "primitive");
426 osrfHashSet(_f,"NUMERIC", "datatype");
429 case DBI_TYPE_STRING :
430 if ( !osrfHashGet(_f, "primitive") )
431 osrfHashSet(_f,"string", "primitive");
432 osrfHashSet(_f,"TEXT", "datatype");
435 case DBI_TYPE_DATETIME :
436 if ( !osrfHashGet(_f, "primitive") )
437 osrfHashSet(_f,"string", "primitive");
439 osrfHashSet(_f,"TIMESTAMP", "datatype");
442 case DBI_TYPE_BINARY :
443 if ( !osrfHashGet(_f, "primitive") )
444 osrfHashSet(_f,"string", "primitive");
446 osrfHashSet(_f,"BYTEA", "datatype");
451 "Setting [%s] to primitive [%s] and datatype [%s]...",
453 osrfHashGet(_f, "primitive"),
454 osrfHashGet(_f, "datatype")
458 dbi_result_free(result);
460 osrfLogDebug(OSRF_LOG_MARK, "No data found for class [%s]...", (char*)classname);
464 osrfStringArrayFree(classes);
469 void userDataFree( void* blob ) {
470 osrfHashFree( (osrfHash*)blob );
474 static void sessionDataFree( char* key, void* item ) {
475 if (!(strcmp(key,"xact_id"))) {
477 dbi_conn_query(writehandle, "ROLLBACK;");
484 int beginTransaction ( osrfMethodContext* ctx ) {
485 if(osrfMethodVerifyContext( ctx )) {
486 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
491 jsonObject* user = verifyUserPCRUD( ctx );
492 if (!user) return -1;
493 jsonObjectFree(user);
496 dbi_result result = dbi_conn_query(writehandle, "START TRANSACTION;");
498 osrfLogError(OSRF_LOG_MARK, "%s: Error starting transaction", MODULENAME );
499 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error starting transaction" );
502 jsonObject* ret = jsonNewObject(ctx->session->session_id);
503 osrfAppRespondComplete( ctx, ret );
506 if (!ctx->session->userData) {
507 ctx->session->userData = osrfNewHash();
508 osrfHashSetCallback((osrfHash*)ctx->session->userData, &sessionDataFree);
511 osrfHashSet( (osrfHash*)ctx->session->userData, strdup( ctx->session->session_id ), "xact_id" );
512 ctx->session->userDataFree = &userDataFree;
518 int setSavepoint ( osrfMethodContext* ctx ) {
519 if(osrfMethodVerifyContext( ctx )) {
520 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
527 jsonObject* user = verifyUserPCRUD( ctx );
528 if (!user) return -1;
529 jsonObjectFree(user);
532 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
533 osrfAppSessionStatus(
535 OSRF_STATUS_INTERNALSERVERERROR,
536 "osrfMethodException",
538 "No active transaction -- required for savepoints"
543 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
545 dbi_result result = dbi_conn_queryf(writehandle, "SAVEPOINT \"%s\";", spName);
549 "%s: Error creating savepoint %s in transaction %s",
552 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
554 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error creating savepoint" );
558 jsonObject* ret = jsonNewObject(spName);
559 osrfAppRespondComplete( ctx, ret );
566 int releaseSavepoint ( osrfMethodContext* ctx ) {
567 if(osrfMethodVerifyContext( ctx )) {
568 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
575 jsonObject* user = verifyUserPCRUD( ctx );
576 if (!user) return -1;
577 jsonObjectFree(user);
580 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
581 osrfAppSessionStatus(
583 OSRF_STATUS_INTERNALSERVERERROR,
584 "osrfMethodException",
586 "No active transaction -- required for savepoints"
591 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
593 dbi_result result = dbi_conn_queryf(writehandle, "RELEASE SAVEPOINT \"%s\";", spName);
597 "%s: Error releasing savepoint %s in transaction %s",
600 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
602 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error releasing savepoint" );
606 jsonObject* ret = jsonNewObject(spName);
607 osrfAppRespondComplete( ctx, ret );
614 int rollbackSavepoint ( osrfMethodContext* ctx ) {
615 if(osrfMethodVerifyContext( ctx )) {
616 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
623 jsonObject* user = verifyUserPCRUD( ctx );
624 if (!user) return -1;
625 jsonObjectFree(user);
628 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
629 osrfAppSessionStatus(
631 OSRF_STATUS_INTERNALSERVERERROR,
632 "osrfMethodException",
634 "No active transaction -- required for savepoints"
639 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
641 dbi_result result = dbi_conn_queryf(writehandle, "ROLLBACK TO SAVEPOINT \"%s\";", spName);
645 "%s: Error rolling back savepoint %s in transaction %s",
648 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
650 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back savepoint" );
654 jsonObject* ret = jsonNewObject(spName);
655 osrfAppRespondComplete( ctx, ret );
662 int commitTransaction ( osrfMethodContext* ctx ) {
663 if(osrfMethodVerifyContext( ctx )) {
664 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
669 jsonObject* user = verifyUserPCRUD( ctx );
670 if (!user) return -1;
671 jsonObjectFree(user);
674 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
675 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to commit" );
679 dbi_result result = dbi_conn_query(writehandle, "COMMIT;");
681 osrfLogError(OSRF_LOG_MARK, "%s: Error committing transaction", MODULENAME );
682 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error committing transaction" );
685 osrfHashRemove(ctx->session->userData, "xact_id");
686 jsonObject* ret = jsonNewObject(ctx->session->session_id);
687 osrfAppRespondComplete( ctx, ret );
693 int rollbackTransaction ( osrfMethodContext* ctx ) {
694 if(osrfMethodVerifyContext( ctx )) {
695 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
700 jsonObject* user = verifyUserPCRUD( ctx );
701 if (!user) return -1;
702 jsonObjectFree(user);
705 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
706 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to roll back" );
710 dbi_result result = dbi_conn_query(writehandle, "ROLLBACK;");
712 osrfLogError(OSRF_LOG_MARK, "%s: Error rolling back transaction", MODULENAME );
713 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back transaction" );
716 osrfHashRemove(ctx->session->userData, "xact_id");
717 jsonObject* ret = jsonNewObject(ctx->session->session_id);
718 osrfAppRespondComplete( ctx, ret );
724 int dispatchCRUDMethod ( osrfMethodContext* ctx ) {
725 if(osrfMethodVerifyContext( ctx )) {
726 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
730 osrfHash* meta = (osrfHash*) ctx->method->userData;
731 osrfHash* class_obj = osrfHashGet( meta, "class" );
735 const char* methodtype = osrfHashGet(meta, "methodtype");
736 jsonObject * obj = NULL;
738 if (!strcmp(methodtype, "create")) {
739 obj = doCreate(ctx, &err);
740 osrfAppRespondComplete( ctx, obj );
742 else if (!strcmp(methodtype, "retrieve")) {
743 obj = doRetrieve(ctx, &err);
744 osrfAppRespondComplete( ctx, obj );
746 else if (!strcmp(methodtype, "update")) {
747 obj = doUpdate(ctx, &err);
748 osrfAppRespondComplete( ctx, obj );
750 else if (!strcmp(methodtype, "delete")) {
751 obj = doDelete(ctx, &err);
752 osrfAppRespondComplete( ctx, obj );
754 else if (!strcmp(methodtype, "search")) {
756 jsonObject* _p = jsonObjectClone( ctx->params );
759 _p = jsonParseString("[]");
760 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 1)));
761 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 2)));
764 obj = doFieldmapperSearch(ctx, class_obj, _p, &err);
770 jsonIterator* itr = jsonNewIterator( obj );
771 while ((cur = jsonIteratorNext( itr ))) {
773 if(!verifyObjectPCRUD(ctx, cur)) continue;
775 osrfAppRespond( ctx, cur );
777 jsonIteratorFree(itr);
778 osrfAppRespondComplete( ctx, NULL );
780 } else if (!strcmp(methodtype, "id_list")) {
782 jsonObject* _p = jsonObjectClone( ctx->params );
785 _p = jsonParseString("[]");
786 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 1)));
787 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 2)));
790 if (jsonObjectGetIndex( _p, 1 )) {
791 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "select" );
792 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "no_i18n" );
793 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh" );
794 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh_columns" );
796 jsonObjectSetIndex( _p, 1, jsonNewObjectType(JSON_HASH) );
799 jsonObjectSetKey( jsonObjectGetIndex( _p, 1 ), "no_i18n", jsonNewBoolObject( 1 ) );
802 jsonObjectGetIndex( _p, 1 ),
805 "{ \"%s\":[\"%s\"] }",
806 osrfHashGet( class_obj, "classname" ),
807 osrfHashGet( class_obj, "primarykey" )
811 obj = doFieldmapperSearch(ctx, class_obj, _p, &err);
817 jsonIterator* itr = jsonNewIterator( obj );
818 while ((cur = jsonIteratorNext( itr ))) {
820 if(!verifyObjectPCRUD(ctx, cur)) continue;
824 oilsFMGetObject( cur, osrfHashGet( class_obj, "primarykey" ) )
827 jsonIteratorFree(itr);
828 osrfAppRespondComplete( ctx, NULL );
831 osrfAppRespondComplete( ctx, obj );
839 static int verifyObjectClass ( osrfMethodContext* ctx, const jsonObject* param ) {
842 osrfHash* meta = (osrfHash*) ctx->method->userData;
843 osrfHash* class = osrfHashGet( meta, "class" );
845 if (!param->classname || (strcmp( osrfHashGet(class, "classname"), param->classname ))) {
847 growing_buffer* msg = buffer_init(128);
850 "%s: %s method for type %s was passed a %s",
852 osrfHashGet(meta, "methodtype"),
853 osrfHashGet(class, "classname"),
857 char* m = buffer_release(msg);
858 osrfAppSessionStatus( ctx->session, OSRF_STATUS_BADREQUEST, "osrfMethodException", ctx->request, m );
866 ret = verifyObjectPCRUD( ctx, param );
874 static jsonObject* verifyUserPCRUD( osrfMethodContext* ctx ) {
875 char* auth = jsonObjectToSimpleString( jsonObjectGetIndex( ctx->params, 0 ) );
876 jsonObject* auth_object = jsonNewObject(auth);
877 jsonObject* user = oilsUtilsQuickReq("open-ils.auth","open-ils.auth.session.retrieve", auth_object);
878 jsonObjectFree(auth_object);
880 if (!user->classname || strcmp(user->classname, "au")) {
882 growing_buffer* msg = buffer_init(128);
885 "%s: permacrud received a bad auth token: %s",
890 char* m = buffer_release(msg);
891 osrfAppSessionStatus( ctx->session, OSRF_STATUS_UNAUTHORIZED, "osrfMethodException", ctx->request, m );
894 jsonObjectFree(user);
903 static int verifyObjectPCRUD ( osrfMethodContext* ctx, const jsonObject* obj ) {
905 dbhandle = writehandle;
907 osrfHash* meta = (osrfHash*) ctx->method->userData;
908 osrfHash* class = osrfHashGet( meta, "class" );
909 char* method_type = strdup( osrfHashGet(meta, "methodtype") );
912 if ( ( *method_type == 's' || *method_type == 'i' ) ) {
914 method_type = strdup("retrieve"); // search and id_list are equivelant to retrieve for this
915 } else if ( *method_type == 'u' || *method_type == 'd' ) {
916 fetch = 1; // MUST go to the db for the object for update and delete
919 osrfHash* pcrud = osrfHashGet( osrfHashGet(class, "permacrud"), method_type );
923 // No permacrud for this method type on this class
925 growing_buffer* msg = buffer_init(128);
928 "%s: %s on class %s has no permacrud IDL entry",
930 osrfHashGet(meta, "methodtype"),
931 osrfHashGet(class, "classname")
934 char* m = buffer_release(msg);
935 osrfAppSessionStatus( ctx->session, OSRF_STATUS_FORBIDDEN, "osrfMethodException", ctx->request, m );
942 jsonObject* user = verifyUserPCRUD( ctx );
945 int userid = atoi( oilsFMGetString( user, "id" ) );
946 jsonObjectFree(user);
948 osrfStringArray* permission = osrfHashGet(pcrud, "permission");
949 osrfStringArray* local_context = osrfHashGet(pcrud, "local_context");
950 osrfHash* foreign_context = osrfHashGet(pcrud, "foreign_context");
952 osrfStringArray* context_org_array = osrfNewStringArray(1);
955 char* pkey_value = NULL;
956 if ( str_is_true( osrfHashGet(pcrud, "global_required") ) ) {
957 osrfLogDebug( OSRF_LOG_MARK, "global-level permissions required, fetching top of the org tree" );
959 // check for perm at top of org tree
960 jsonObject* _tmp_params = jsonParseString("[{\"parent_ou\":null}]");
961 jsonObject* _list = doFieldmapperSearch(ctx, osrfHashGet( oilsIDL(), "aou" ), _tmp_params, &err);
963 jsonObject* _tree_top = jsonObjectGetIndex(_list, 0);
966 jsonObjectFree(_tmp_params);
967 jsonObjectFree(_list);
969 growing_buffer* msg = buffer_init(128);
970 OSRF_BUFFER_ADD( msg, MODULENAME );
971 OSRF_BUFFER_ADD( msg,
972 ": Internal error, could not find the top of the org tree (parent_ou = NULL)" );
974 char* m = buffer_release(msg);
975 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, m );
981 osrfStringArrayAdd( context_org_array, oilsFMGetString( _tree_top, "id" ) );
982 osrfLogDebug( OSRF_LOG_MARK, "top of the org tree is %s", osrfStringArrayGetString(context_org_array, 0) );
984 jsonObjectFree(_tmp_params);
985 jsonObjectFree(_list);
988 osrfLogDebug( OSRF_LOG_MARK, "global-level permissions not required, fetching context org ids" );
989 char* pkey = osrfHashGet(class, "primarykey");
990 jsonObject *param = NULL;
992 if (obj->classname) {
993 pkey_value = oilsFMGetString( obj, pkey );
994 if (!fetch) param = jsonObjectClone(obj);
995 osrfLogDebug( OSRF_LOG_MARK, "Object supplied, using primary key value of %s", pkey_value );
997 pkey_value = jsonObjectToSimpleString( obj );
999 osrfLogDebug( OSRF_LOG_MARK, "Object not supplied, using primary key value of %s and retrieving from the database", pkey_value );
1003 jsonObject* _tmp_params = jsonParseStringFmt("[{\"%s\":\"%s\"}]", pkey, pkey_value);
1004 jsonObject* _list = doFieldmapperSearch(
1011 param = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1013 jsonObjectFree(_tmp_params);
1014 jsonObjectFree(_list);
1018 osrfLogDebug( OSRF_LOG_MARK, "Object not found in the database with primary key %s of %s", pkey, pkey_value );
1020 growing_buffer* msg = buffer_init(128);
1023 "%s: no object found with primary key %s of %s",
1029 char* m = buffer_release(msg);
1030 osrfAppSessionStatus(
1032 OSRF_STATUS_INTERNALSERVERERROR,
1033 "osrfMethodException",
1039 if (pkey_value) free(pkey_value);
1044 if (local_context->size > 0) {
1045 osrfLogDebug( OSRF_LOG_MARK, "%d class-local context field(s) specified", local_context->size);
1047 char* lcontext = NULL;
1048 while ( (lcontext = osrfStringArrayGetString(local_context, i++)) ) {
1049 osrfStringArrayAdd( context_org_array, oilsFMGetString( param, lcontext ) );
1052 "adding class-local field %s (value: %s) to the context org list",
1054 osrfStringArrayGetString(context_org_array, context_org_array->size - 1)
1059 osrfStringArray* class_list;
1061 if (foreign_context) {
1062 class_list = osrfHashKeys( foreign_context );
1063 osrfLogDebug( OSRF_LOG_MARK, "%d foreign context classes(s) specified", class_list->size);
1065 if (class_list->size > 0) {
1068 char* class_name = NULL;
1069 while ( (class_name = osrfStringArrayGetString(class_list, i++)) ) {
1070 osrfHash* fcontext = osrfHashGet(foreign_context, class_name);
1074 "%d foreign context fields(s) specified for class %s",
1075 ((osrfStringArray*)osrfHashGet(fcontext,"context"))->size,
1079 char* foreign_pkey = osrfHashGet(fcontext, "field");
1080 char* foreign_pkey_value = oilsFMGetString(param, osrfHashGet(fcontext, "fkey"));
1082 jsonObject* _tmp_params = jsonParseStringFmt(
1083 "[{\"%s\":\"%s\"}]",
1088 jsonObject* _list = doFieldmapperSearch(
1090 osrfHashGet( oilsIDL(), class_name ),
1095 jsonObject* _fparam = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1096 jsonObjectFree(_tmp_params);
1097 jsonObjectFree(_list);
1099 osrfStringArray* jump_list = osrfHashGet(fcontext, "jump");
1101 if (_fparam && jump_list) {
1104 while ( (flink = osrfStringArrayGetString(jump_list, k++)) && _fparam ) {
1105 free(foreign_pkey_value);
1107 osrfHash* foreign_link_hash = oilsIDLFindPath( "/%s/links/%s", _fparam->classname, flink );
1109 foreign_pkey_value = oilsFMGetString(_fparam, flink);
1110 foreign_pkey = osrfHashGet( foreign_link_hash, "key" );
1112 _tmp_params = jsonParseStringFmt(
1113 "[{\"%s\":\"%s\"}]",
1118 _list = doFieldmapperSearch(
1120 osrfHashGet( oilsIDL(), osrfHashGet( foreign_link_hash, "class" ) ),
1125 _fparam = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1126 jsonObjectFree(_tmp_params);
1127 jsonObjectFree(_list);
1134 growing_buffer* msg = buffer_init(128);
1137 "%s: no object found with primary key %s of %s",
1143 char* m = buffer_release(msg);
1144 osrfAppSessionStatus(
1146 OSRF_STATUS_INTERNALSERVERERROR,
1147 "osrfMethodException",
1153 osrfStringArrayFree(class_list);
1154 free(foreign_pkey_value);
1155 jsonObjectFree(param);
1160 free(foreign_pkey_value);
1163 char* foreign_field = NULL;
1164 while ( (foreign_field = osrfStringArrayGetString(osrfHashGet(fcontext,"context"), j++)) ) {
1165 osrfStringArrayAdd( context_org_array, oilsFMGetString( _fparam, foreign_field ) );
1168 "adding foreign class %s field %s (value: %s) to the context org list",
1171 osrfStringArrayGetString(context_org_array, context_org_array->size - 1)
1175 jsonObjectFree(_fparam);
1178 osrfStringArrayFree(class_list);
1182 jsonObjectFree(param);
1185 char* context_org = NULL;
1189 if (permission->size == 0) {
1190 osrfLogDebug( OSRF_LOG_MARK, "No permission specified for this action, passing through" );
1195 while ( (perm = osrfStringArrayGetString(permission, i++)) ) {
1197 while ( (context_org = osrfStringArrayGetString(context_org_array, j++)) ) {
1203 "Checking object permission [%s] for user %d on object %s (class %s) at org %d",
1207 osrfHashGet(class, "classname"),
1211 result = dbi_conn_queryf(
1213 "SELECT permission.usr_has_object_perm(%d, '%s', '%s', '%s', %d) AS has_perm;",
1216 osrfHashGet(class, "classname"),
1224 "Recieved a result for object permission [%s] for user %d on object %s (class %s) at org %d",
1228 osrfHashGet(class, "classname"),
1232 if (dbi_result_first_row(result)) {
1233 jsonObject* return_val = oilsMakeJSONFromResult( result );
1234 char* has_perm = jsonObjectToSimpleString( jsonObjectGetKeyConst(return_val, "has_perm") );
1238 "Status of object permission [%s] for user %d on object %s (class %s) at org %d is %s",
1242 osrfHashGet(class, "classname"),
1247 if ( *has_perm == 't' ) OK = 1;
1249 jsonObjectFree(return_val);
1252 dbi_result_free(result);
1257 osrfLogDebug( OSRF_LOG_MARK, "Checking non-object permission [%s] for user %d at org %d", perm, userid, atoi(context_org) );
1258 result = dbi_conn_queryf(
1260 "SELECT permission.usr_has_perm(%d, '%s', %d) AS has_perm;",
1267 osrfLogDebug( OSRF_LOG_MARK, "Received a result for permission [%s] for user %d at org %d", perm, userid, atoi(context_org) );
1268 if (dbi_result_first_row(result)) {
1269 jsonObject* return_val = oilsMakeJSONFromResult( result );
1270 char* has_perm = jsonObjectToSimpleString( jsonObjectGetKeyConst(return_val, "has_perm") );
1271 osrfLogDebug( OSRF_LOG_MARK, "Status of permission [%s] for user %d at org %d is [%s]", perm, userid, atoi(context_org), has_perm );
1272 if ( *has_perm == 't' ) OK = 1;
1274 jsonObjectFree(return_val);
1277 dbi_result_free(result);
1285 if (pkey_value) free(pkey_value);
1286 osrfStringArrayFree(context_org_array);
1293 static jsonObject* doCreate(osrfMethodContext* ctx, int* err ) {
1295 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1297 jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
1298 jsonObject* options = jsonObjectGetIndex( ctx->params, 2 );
1300 jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
1301 jsonObject* options = jsonObjectGetIndex( ctx->params, 1 );
1304 if (!verifyObjectClass(ctx, target)) {
1309 osrfLogDebug( OSRF_LOG_MARK, "Object seems to be of the correct type" );
1311 if (!ctx->session || !ctx->session->userData || !osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
1312 osrfLogError( OSRF_LOG_MARK, "No active transaction -- required for CREATE" );
1314 osrfAppSessionStatus(
1316 OSRF_STATUS_BADREQUEST,
1317 "osrfMethodException",
1319 "No active transaction -- required for CREATE"
1325 // The following test is harmless but redundant. If a class is
1326 // readonly, we don't register a create method for it.
1327 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
1328 osrfAppSessionStatus(
1330 OSRF_STATUS_BADREQUEST,
1331 "osrfMethodException",
1333 "Cannot INSERT readonly class"
1340 char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
1342 // Set the last_xact_id
1343 int index = oilsIDL_ntop( target->classname, "last_xact_id" );
1345 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
1346 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
1349 osrfLogDebug( OSRF_LOG_MARK, "There is a transaction running..." );
1351 dbhandle = writehandle;
1353 osrfHash* fields = osrfHashGet(meta, "fields");
1354 char* pkey = osrfHashGet(meta, "primarykey");
1355 char* seq = osrfHashGet(meta, "sequence");
1357 growing_buffer* table_buf = buffer_init(128);
1358 growing_buffer* col_buf = buffer_init(128);
1359 growing_buffer* val_buf = buffer_init(128);
1361 OSRF_BUFFER_ADD(table_buf, "INSERT INTO ");
1362 OSRF_BUFFER_ADD(table_buf, osrfHashGet(meta, "tablename"));
1363 OSRF_BUFFER_ADD_CHAR( col_buf, '(' );
1364 buffer_add(val_buf,"VALUES (");
1370 osrfStringArray* field_list = osrfHashKeys( fields );
1371 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
1373 osrfHash* field = osrfHashGet( fields, field_name );
1375 if( str_is_true( osrfHashGet( field, "virtual" ) ) )
1378 const jsonObject* field_object = oilsFMGetObject( target, field_name );
1381 if (field_object && field_object->classname) {
1382 value = oilsFMGetString(
1384 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
1387 value = jsonObjectToSimpleString( field_object );
1394 OSRF_BUFFER_ADD_CHAR( col_buf, ',' );
1395 OSRF_BUFFER_ADD_CHAR( val_buf, ',' );
1398 buffer_add(col_buf, field_name);
1400 if (!field_object || field_object->type == JSON_NULL) {
1401 buffer_add( val_buf, "DEFAULT" );
1403 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1404 if ( !strcmp(osrfHashGet(field, "datatype"), "INT8") ) {
1405 buffer_fadd( val_buf, "%lld", atoll(value) );
1407 } else if ( !strcmp(osrfHashGet(field, "datatype"), "INT") ) {
1408 buffer_fadd( val_buf, "%d", atoi(value) );
1410 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
1411 buffer_fadd( val_buf, "%f", atof(value) );
1414 if ( dbi_conn_quote_string(writehandle, &value) ) {
1415 OSRF_BUFFER_ADD( val_buf, value );
1418 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
1419 osrfAppSessionStatus(
1421 OSRF_STATUS_INTERNALSERVERERROR,
1422 "osrfMethodException",
1424 "Error quoting string -- please see the error log for more details"
1427 buffer_free(table_buf);
1428 buffer_free(col_buf);
1429 buffer_free(val_buf);
1440 OSRF_BUFFER_ADD_CHAR( col_buf, ')' );
1441 OSRF_BUFFER_ADD_CHAR( val_buf, ')' );
1443 char* table_str = buffer_release(table_buf);
1444 char* col_str = buffer_release(col_buf);
1445 char* val_str = buffer_release(val_buf);
1446 growing_buffer* sql = buffer_init(128);
1447 buffer_fadd( sql, "%s %s %s;", table_str, col_str, val_str );
1452 char* query = buffer_release(sql);
1454 osrfLogDebug(OSRF_LOG_MARK, "%s: Insert SQL [%s]", MODULENAME, query);
1457 dbi_result result = dbi_conn_query(writehandle, query);
1459 jsonObject* obj = NULL;
1462 obj = jsonNewObject(NULL);
1465 "%s ERROR inserting %s object using query [%s]",
1467 osrfHashGet(meta, "fieldmapper"),
1470 osrfAppSessionStatus(
1472 OSRF_STATUS_INTERNALSERVERERROR,
1473 "osrfMethodException",
1475 "INSERT error -- please see the error log for more details"
1480 char* id = oilsFMGetString(target, pkey);
1482 unsigned long long new_id = dbi_conn_sequence_last(writehandle, seq);
1483 growing_buffer* _id = buffer_init(10);
1484 buffer_fadd(_id, "%lld", new_id);
1485 id = buffer_release(_id);
1488 // Find quietness specification, if present
1489 char* quiet_str = NULL;
1491 const jsonObject* quiet_obj = jsonObjectGetKeyConst( options, "quiet" );
1493 quiet_str = jsonObjectToSimpleString( quiet_obj );
1496 if( str_is_true( quiet_str ) ) { // if quietness is specified
1497 obj = jsonNewObject(id);
1501 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
1502 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH));
1505 jsonObjectGetIndex(fake_params, 0),
1510 jsonObject* list = doFieldmapperSearch( ctx,meta, fake_params, err);
1513 jsonObjectFree( fake_params );
1516 obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
1519 jsonObjectFree( list );
1520 jsonObjectFree( fake_params );
1523 if(quiet_str) free(quiet_str);
1534 static jsonObject* doRetrieve(osrfMethodContext* ctx, int* err ) {
1544 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1546 char* id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, id_pos));
1547 jsonObject* order_hash = jsonObjectGetIndex(ctx->params, order_pos);
1551 "%s retrieving %s object with primary key value of %s",
1553 osrfHashGet(meta, "fieldmapper"),
1558 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
1559 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH));
1562 jsonObjectGetIndex(fake_params, 0),
1563 osrfHashGet(meta, "primarykey"),
1564 jsonObjectClone(jsonObjectGetIndex(ctx->params, id_pos))
1568 if (order_hash) jsonObjectPush(fake_params, jsonObjectClone(order_hash) );
1570 jsonObject* list = doFieldmapperSearch( ctx,meta, fake_params, err);
1573 jsonObjectFree( fake_params );
1577 jsonObject* obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
1579 jsonObjectFree( list );
1580 jsonObjectFree( fake_params );
1583 if(!verifyObjectPCRUD(ctx, obj)) {
1584 jsonObjectFree(obj);
1587 growing_buffer* msg = buffer_init(128);
1588 OSRF_BUFFER_ADD( msg, MODULENAME );
1589 OSRF_BUFFER_ADD( msg, ": Insufficient permissions to retrieve object" );
1591 char* m = buffer_release(msg);
1592 osrfAppSessionStatus( ctx->session, OSRF_STATUS_NOTALLOWED, "osrfMethodException", ctx->request, m );
1603 static char* jsonNumberToDBString ( osrfHash* field, const jsonObject* value ) {
1604 growing_buffer* val_buf = buffer_init(32);
1606 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
1607 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%ld", (long)jsonObjectGetNumber(value) );
1609 char* val_str = jsonObjectToSimpleString(value);
1610 buffer_fadd( val_buf, "%ld", atol(val_str) );
1614 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
1615 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%f", jsonObjectGetNumber(value) );
1617 char* val_str = jsonObjectToSimpleString(value);
1618 buffer_fadd( val_buf, "%f", atof(val_str) );
1623 return buffer_release(val_buf);
1626 static char* searchINPredicate (const char* class, osrfHash* field,
1627 jsonObject* node, const char* op, osrfMethodContext* ctx ) {
1628 growing_buffer* sql_buf = buffer_init(32);
1634 osrfHashGet(field, "name")
1638 buffer_add(sql_buf, "IN (");
1639 } else if (!(strcasecmp(op,"not in"))) {
1640 buffer_add(sql_buf, "NOT IN (");
1642 buffer_add(sql_buf, "IN (");
1645 if (node->type == JSON_HASH) {
1646 // subquery predicate
1647 char* subpred = SELECT(
1649 jsonObjectGetKey( node, "select" ),
1650 jsonObjectGetKey( node, "from" ),
1651 jsonObjectGetKey( node, "where" ),
1652 jsonObjectGetKey( node, "having" ),
1653 jsonObjectGetKey( node, "order_by" ),
1654 jsonObjectGetKey( node, "limit" ),
1655 jsonObjectGetKey( node, "offset" ),
1659 buffer_add(sql_buf, subpred);
1662 } else if (node->type == JSON_ARRAY) {
1663 // litteral value list
1664 int in_item_index = 0;
1665 int in_item_first = 1;
1666 jsonObject* in_item;
1667 while ( (in_item = jsonObjectGetIndex(node, in_item_index++)) ) {
1672 buffer_add(sql_buf, ", ");
1674 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1675 char* val = jsonNumberToDBString( field, in_item );
1676 OSRF_BUFFER_ADD( sql_buf, val );
1680 char* key_string = jsonObjectToSimpleString(in_item);
1681 if ( dbi_conn_quote_string(dbhandle, &key_string) ) {
1682 OSRF_BUFFER_ADD( sql_buf, key_string );
1685 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, key_string);
1687 buffer_free(sql_buf);
1694 OSRF_BUFFER_ADD_CHAR( sql_buf, ')' );
1696 return buffer_release(sql_buf);
1699 // Receive a JSON_ARRAY representing a function call. The first
1700 // entry in the array is the function name. The rest are parameters.
1701 static char* searchValueTransform( const jsonObject* array ) {
1702 growing_buffer* sql_buf = buffer_init(32);
1705 jsonObject* func_item;
1707 // Get the function name
1708 if( array->size > 0 ) {
1709 func_item = jsonObjectGetIndex( array, 0 );
1710 val = jsonObjectToSimpleString( func_item );
1711 OSRF_BUFFER_ADD( sql_buf, val );
1712 OSRF_BUFFER_ADD( sql_buf, "( " );
1716 // Get the parameters
1717 int func_item_index = 1; // We already grabbed the zeroth entry
1718 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1720 // Add a separator comma, if we need one
1721 if( func_item_index > 2 )
1722 buffer_add( sql_buf, ", " );
1724 // Add the current parameter
1725 if (func_item->type == JSON_NULL) {
1726 buffer_add( sql_buf, "NULL" );
1728 val = jsonObjectToSimpleString(func_item);
1729 if ( dbi_conn_quote_string(dbhandle, &val) ) {
1730 OSRF_BUFFER_ADD( sql_buf, val );
1733 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1734 buffer_free(sql_buf);
1741 buffer_add( sql_buf, " )" );
1743 return buffer_release(sql_buf);
1746 static char* searchFunctionPredicate (const char* class, osrfHash* field,
1747 const jsonObject* node, const char* node_key) {
1748 growing_buffer* sql_buf = buffer_init(32);
1750 char* val = searchValueTransform(node);
1756 osrfHashGet(field, "name"),
1763 return buffer_release(sql_buf);
1766 // class is a class name
1767 // field is a field definition as stored in the IDL
1768 // node comes from the method parameter, and represents an entry in the SELECT list
1769 static char* searchFieldTransform (const char* class, osrfHash* field, const jsonObject* node) {
1770 growing_buffer* sql_buf = buffer_init(32);
1772 char* field_transform = jsonObjectToSimpleString( jsonObjectGetKeyConst( node, "transform" ) );
1773 char* transform_subcolumn = jsonObjectToSimpleString( jsonObjectGetKeyConst( node, "result_field" ) );
1775 if(transform_subcolumn)
1776 OSRF_BUFFER_ADD_CHAR( sql_buf, '(' ); // enclose transform in parentheses
1778 if (field_transform) {
1779 buffer_fadd( sql_buf, "%s(\"%s\".%s", field_transform, class, osrfHashGet(field, "name"));
1780 const jsonObject* array = jsonObjectGetKeyConst( node, "params" );
1783 int func_item_index = 0;
1784 jsonObject* func_item;
1785 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1787 char* val = jsonObjectToSimpleString(func_item);
1790 buffer_add( sql_buf, ",NULL" );
1791 } else if ( dbi_conn_quote_string(dbhandle, &val) ) {
1792 OSRF_BUFFER_ADD_CHAR( sql_buf, ',' );
1793 OSRF_BUFFER_ADD( sql_buf, val );
1795 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1796 free(transform_subcolumn);
1797 free(field_transform);
1799 buffer_free(sql_buf);
1806 buffer_add( sql_buf, " )" );
1809 buffer_fadd( sql_buf, "\"%s\".%s", class, osrfHashGet(field, "name"));
1812 if (transform_subcolumn)
1813 buffer_fadd( sql_buf, ").\"%s\"", transform_subcolumn );
1815 if (field_transform) free(field_transform);
1816 if (transform_subcolumn) free(transform_subcolumn);
1818 return buffer_release(sql_buf);
1821 static char* searchFieldTransformPredicate (const char* class, osrfHash* field, jsonObject* node, const char* node_key) {
1822 char* field_transform = searchFieldTransform( class, field, node );
1825 if (!jsonObjectGetKeyConst( node, "value" )) {
1826 value = searchWHERE( node, osrfHashGet( oilsIDL(), class ), AND_OP_JOIN, NULL );
1827 } else if (jsonObjectGetKeyConst( node, "value" )->type == JSON_ARRAY) {
1828 value = searchValueTransform(jsonObjectGetKeyConst( node, "value" ));
1829 } else if (jsonObjectGetKeyConst( node, "value" )->type == JSON_HASH) {
1830 value = searchWHERE( jsonObjectGetKeyConst( node, "value" ), osrfHashGet( oilsIDL(), class ), AND_OP_JOIN, NULL );
1831 } else if (jsonObjectGetKeyConst( node, "value" )->type != JSON_NULL) {
1832 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1833 value = jsonNumberToDBString( field, jsonObjectGetKeyConst( node, "value" ) );
1835 value = jsonObjectToSimpleString(jsonObjectGetKeyConst( node, "value" ));
1836 if ( !dbi_conn_quote_string(dbhandle, &value) ) {
1837 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, value);
1839 free(field_transform);
1845 growing_buffer* sql_buf = buffer_init(32);
1856 free(field_transform);
1858 return buffer_release(sql_buf);
1861 static char* searchSimplePredicate (const char* orig_op, const char* class,
1862 osrfHash* field, const jsonObject* node) {
1866 if (node->type != JSON_NULL) {
1867 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1868 val = jsonNumberToDBString( field, node );
1870 val = jsonObjectToSimpleString(node);
1874 char* pred = searchWriteSimplePredicate( class, field, osrfHashGet(field, "name"), orig_op, val );
1881 static char* searchWriteSimplePredicate ( const char* class, osrfHash* field,
1882 const char* left, const char* orig_op, const char* right ) {
1886 if (right == NULL) {
1887 val = strdup("NULL");
1889 if (strcmp( orig_op, "=" ))
1890 op = strdup("IS NOT");
1894 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1895 val = strdup(right);
1896 op = strdup(orig_op);
1899 val = strdup(right);
1900 if ( !dbi_conn_quote_string(dbhandle, &val) ) {
1901 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1905 op = strdup(orig_op);
1908 growing_buffer* sql_buf = buffer_init(16);
1909 buffer_fadd( sql_buf, "\"%s\".%s %s %s", class, left, op, val );
1913 return buffer_release(sql_buf);
1916 static char* searchBETWEENPredicate (const char* class, osrfHash* field, jsonObject* node) {
1921 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1922 x_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,0));
1923 y_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,1));
1926 x_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,0));
1927 y_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,1));
1928 if ( !(dbi_conn_quote_string(dbhandle, &x_string) && dbi_conn_quote_string(dbhandle, &y_string)) ) {
1929 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key strings [%s] and [%s]", MODULENAME, x_string, y_string);
1936 growing_buffer* sql_buf = buffer_init(32);
1937 buffer_fadd( sql_buf, "%s BETWEEN %s AND %s", osrfHashGet(field, "name"), x_string, y_string );
1941 return buffer_release(sql_buf);
1944 static char* searchPredicate ( const char* class, osrfHash* field,
1945 jsonObject* node, osrfMethodContext* ctx ) {
1948 if (node->type == JSON_ARRAY) { // equality IN search
1949 pred = searchINPredicate( class, field, node, NULL, ctx );
1950 } else if (node->type == JSON_HASH) { // non-equality search
1951 jsonObject* pred_node;
1952 jsonIterator* pred_itr = jsonNewIterator( node );
1953 while ( (pred_node = jsonIteratorNext( pred_itr )) ) {
1954 if ( !(strcasecmp( pred_itr->key,"between" )) )
1955 pred = searchBETWEENPredicate( class, field, pred_node );
1956 else if ( !(strcasecmp( pred_itr->key,"in" )) || !(strcasecmp( pred_itr->key,"not in" )) )
1957 pred = searchINPredicate( class, field, pred_node, pred_itr->key, ctx );
1958 else if ( pred_node->type == JSON_ARRAY )
1959 pred = searchFunctionPredicate( class, field, pred_node, pred_itr->key );
1960 else if ( pred_node->type == JSON_HASH )
1961 pred = searchFieldTransformPredicate( class, field, pred_node, pred_itr->key );
1963 pred = searchSimplePredicate( pred_itr->key, class, field, pred_node );
1967 jsonIteratorFree(pred_itr);
1968 } else if (node->type == JSON_NULL) { // IS NULL search
1969 growing_buffer* _p = buffer_init(64);
1972 "\"%s\".%s IS NULL",
1974 osrfHashGet(field, "name")
1976 pred = buffer_release(_p);
1977 } else { // equality search
1978 pred = searchSimplePredicate( "=", class, field, node );
1997 field : call_number,
2013 static char* searchJOIN ( const jsonObject* join_hash, osrfHash* leftmeta ) {
2015 const jsonObject* working_hash;
2016 jsonObject* freeable_hash = NULL;
2018 if (join_hash->type == JSON_STRING) {
2019 // create a wrapper around a copy of the original
2020 char* _tmp = jsonObjectToSimpleString( join_hash );
2021 freeable_hash = jsonNewObjectType(JSON_HASH);
2022 jsonObjectSetKey(freeable_hash, _tmp, NULL);
2024 working_hash = freeable_hash;
2027 if( join_hash->type != JSON_HASH ) {
2030 "%s: JOIN failed; expected JSON object type not found",
2035 working_hash = join_hash;
2038 growing_buffer* join_buf = buffer_init(128);
2039 const char* leftclass = osrfHashGet(leftmeta, "classname");
2041 jsonObject* snode = NULL;
2042 jsonIterator* search_itr = jsonNewIterator( working_hash );
2044 while ( (snode = jsonIteratorNext( search_itr )) ) {
2045 const char* class = search_itr->key;
2046 osrfHash* idlClass = osrfHashGet( oilsIDL(), class );
2050 "%s: JOIN failed. No class \"%s\" defined in IDL",
2054 jsonIteratorFree( search_itr );
2055 buffer_free( join_buf );
2057 jsonObjectFree( freeable_hash );
2061 char* fkey = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "fkey" ) );
2062 char* field = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "field" ) );
2064 if (field && !fkey) {
2065 fkey = (char*)oilsIDLFindPath("/%s/links/%s/key", class, field);
2069 "%s: JOIN failed. No link defined from %s.%s to %s",
2075 buffer_free(join_buf);
2077 jsonObjectFree(freeable_hash);
2079 jsonIteratorFree(search_itr);
2082 fkey = strdup( fkey );
2084 } else if (!field && fkey) {
2085 field = (char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, fkey );
2089 "%s: JOIN failed. No link defined from %s.%s to %s",
2095 buffer_free(join_buf);
2097 jsonObjectFree(freeable_hash);
2099 jsonIteratorFree(search_itr);
2102 field = strdup( field );
2104 } else if (!field && !fkey) {
2105 osrfHash* _links = oilsIDL_links( leftclass );
2107 // For each link defined for the left class:
2108 // see if the link references the joined class
2109 osrfHashIterator* itr = osrfNewHashIterator( _links );
2110 osrfHash* curr_link = NULL;
2111 while( (curr_link = osrfHashIteratorNext( itr ) ) ) {
2112 const char* other_class = osrfHashGet( curr_link, "class" );
2113 if( other_class && !strcmp( other_class, class ) ) {
2115 // Found a link between the classes
2116 fkey = strdup( osrfHashIteratorKey( itr ) );
2117 const char* other_key = osrfHashGet( curr_link, "key" );
2118 field = other_key ? strdup( other_key ) : NULL;
2122 osrfHashIteratorFree( itr );
2124 if (!field || !fkey) {
2125 // Do another such search, with the classes reversed
2126 _links = oilsIDL_links( class );
2128 // For each link defined for the joined class:
2129 // see if the link references the left class
2130 osrfHashIterator* itr = osrfNewHashIterator( _links );
2131 osrfHash* curr_link = NULL;
2132 while( (curr_link = osrfHashIteratorNext( itr ) ) ) {
2133 const char* other_class = osrfHashGet( curr_link, "class" );
2134 if( other_class && !strcmp( other_class, leftclass ) ) {
2136 // Found a link between the classes
2137 fkey = strdup( osrfHashIteratorKey( itr ) );
2138 const char* other_key = osrfHashGet( curr_link, "key" );
2139 field = other_key ? strdup( other_key ) : NULL;
2143 osrfHashIteratorFree( itr );
2146 if (!field || !fkey) {
2149 "%s: JOIN failed. No link defined between %s and %s",
2156 buffer_free(join_buf);
2158 jsonObjectFree(freeable_hash);
2159 jsonIteratorFree(search_itr);
2165 char* type = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "type" ) );
2167 if ( !strcasecmp(type,"left") ) {
2168 buffer_add(join_buf, " LEFT JOIN");
2169 } else if ( !strcasecmp(type,"right") ) {
2170 buffer_add(join_buf, " RIGHT JOIN");
2171 } else if ( !strcasecmp(type,"full") ) {
2172 buffer_add(join_buf, " FULL JOIN");
2174 buffer_add(join_buf, " INNER JOIN");
2177 buffer_add(join_buf, " INNER JOIN");
2181 char* table = getSourceDefinition(idlClass);
2185 jsonIteratorFree( search_itr );
2186 buffer_free( join_buf );
2188 jsonObjectFree( freeable_hash );
2192 buffer_fadd(join_buf, " %s AS \"%s\" ON ( \"%s\".%s = \"%s\".%s",
2193 table, class, class, field, leftclass, fkey);
2196 const jsonObject* filter = jsonObjectGetKeyConst( snode, "filter" );
2198 char* filter_op = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "filter_op" ) );
2200 if (!strcasecmp("or",filter_op)) {
2201 buffer_add( join_buf, " OR " );
2203 buffer_add( join_buf, " AND " );
2206 buffer_add( join_buf, " AND " );
2209 char* jpred = searchWHERE( filter, idlClass, AND_OP_JOIN, NULL );
2210 OSRF_BUFFER_ADD_CHAR( join_buf, ' ' );
2211 OSRF_BUFFER_ADD( join_buf, jpred );
2216 buffer_add(join_buf, " ) ");
2218 const jsonObject* join_filter = jsonObjectGetKeyConst( snode, "join" );
2220 char* jpred = searchJOIN( join_filter, idlClass );
2221 OSRF_BUFFER_ADD_CHAR( join_buf, ' ' );
2222 OSRF_BUFFER_ADD( join_buf, jpred );
2231 jsonObjectFree(freeable_hash);
2232 jsonIteratorFree(search_itr);
2234 return buffer_release(join_buf);
2239 { +class : { -or|-and : { field : { op : value }, ... } ... }, ... }
2240 { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }
2241 [ { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }, ... ]
2245 static char* searchWHERE ( const jsonObject* search_hash, osrfHash* meta, int opjoin_type, osrfMethodContext* ctx ) {
2249 "%s: Entering searchWHERE; search_hash addr = %p, meta addr = %p, opjoin_type = %d, ctx addr = %p",
2257 growing_buffer* sql_buf = buffer_init(128);
2259 jsonObject* node = NULL;
2262 if ( search_hash->type == JSON_ARRAY ) {
2263 osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_ARRAY", MODULENAME);
2264 jsonIterator* search_itr = jsonNewIterator( search_hash );
2265 while ( (node = jsonIteratorNext( search_itr )) ) {
2269 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2270 else buffer_add(sql_buf, " AND ");
2273 char* subpred = searchWHERE( node, meta, opjoin_type, ctx );
2274 buffer_fadd(sql_buf, "( %s )", subpred);
2277 jsonIteratorFree(search_itr);
2279 } else if ( search_hash->type == JSON_HASH ) {
2280 osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_HASH", MODULENAME);
2281 jsonIterator* search_itr = jsonNewIterator( search_hash );
2282 while ( (node = jsonIteratorNext( search_itr )) ) {
2287 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2288 else buffer_add(sql_buf, " AND ");
2291 if ( !strncmp("+",search_itr->key,1) ) {
2292 if ( node->type == JSON_STRING ) {
2293 char* subpred = jsonObjectToSimpleString( node );
2294 buffer_fadd(sql_buf, " \"%s\".%s ", search_itr->key + 1, subpred);
2297 char* subpred = searchWHERE( node, osrfHashGet( oilsIDL(), search_itr->key + 1 ), AND_OP_JOIN, ctx );
2298 buffer_fadd(sql_buf, "( %s )", subpred);
2301 } else if ( !strcasecmp("-or",search_itr->key) ) {
2302 char* subpred = searchWHERE( node, meta, OR_OP_JOIN, ctx );
2303 buffer_fadd(sql_buf, "( %s )", subpred);
2305 } else if ( !strcasecmp("-and",search_itr->key) ) {
2306 char* subpred = searchWHERE( node, meta, AND_OP_JOIN, ctx );
2307 buffer_fadd(sql_buf, "( %s )", subpred);
2309 } else if ( !strcasecmp("-exists",search_itr->key) ) {
2310 char* subpred = SELECT(
2312 jsonObjectGetKey( node, "select" ),
2313 jsonObjectGetKey( node, "from" ),
2314 jsonObjectGetKey( node, "where" ),
2315 jsonObjectGetKey( node, "having" ),
2316 jsonObjectGetKey( node, "order_by" ),
2317 jsonObjectGetKey( node, "limit" ),
2318 jsonObjectGetKey( node, "offset" ),
2322 buffer_fadd(sql_buf, "EXISTS ( %s )", subpred);
2324 } else if ( !strcasecmp("-not-exists",search_itr->key) ) {
2325 char* subpred = SELECT(
2327 jsonObjectGetKey( node, "select" ),
2328 jsonObjectGetKey( node, "from" ),
2329 jsonObjectGetKey( node, "where" ),
2330 jsonObjectGetKey( node, "having" ),
2331 jsonObjectGetKey( node, "order_by" ),
2332 jsonObjectGetKey( node, "limit" ),
2333 jsonObjectGetKey( node, "offset" ),
2337 buffer_fadd(sql_buf, "NOT EXISTS ( %s )", subpred);
2341 char* class = osrfHashGet(meta, "classname");
2342 osrfHash* fields = osrfHashGet(meta, "fields");
2343 osrfHash* field = osrfHashGet( fields, search_itr->key );
2347 char* table = getSourceDefinition(meta);
2349 table = strdup( "(?)" );
2352 "%s: Attempt to reference non-existent column %s on %s (%s)",
2358 buffer_free(sql_buf);
2360 jsonIteratorFree(search_itr);
2364 char* subpred = searchPredicate( class, field, node, ctx );
2365 buffer_add( sql_buf, subpred );
2369 jsonIteratorFree(search_itr);
2372 // ERROR ... only hash and array allowed at this level
2373 char* predicate_string = jsonObjectToJSON( search_hash );
2376 "%s: Invalid predicate structure: %s",
2380 buffer_free(sql_buf);
2381 free(predicate_string);
2386 return buffer_release(sql_buf);
2390 /* method context */ osrfMethodContext* ctx,
2392 /* SELECT */ jsonObject* selhash,
2393 /* FROM */ jsonObject* join_hash,
2394 /* WHERE */ jsonObject* search_hash,
2395 /* HAVING */ jsonObject* having_hash,
2396 /* ORDER BY */ jsonObject* order_hash,
2397 /* LIMIT */ jsonObject* limit,
2398 /* OFFSET */ jsonObject* offset,
2399 /* flags */ int flags
2401 const char* locale = osrf_message_get_last_locale();
2403 // in case we don't get a select list
2404 jsonObject* defaultselhash = NULL;
2406 // general tmp objects
2407 const jsonObject* tmp_const;
2408 jsonObject* selclass = NULL;
2409 jsonObject* selfield = NULL;
2410 jsonObject* snode = NULL;
2411 jsonObject* onode = NULL;
2413 char* string = NULL;
2414 int from_function = 0;
2419 // the core search class
2420 char* core_class = NULL;
2422 // metadata about the core search class
2423 osrfHash* core_meta = NULL;
2425 // punt if there's no core class
2426 if (!join_hash || ( join_hash->type == JSON_HASH && !join_hash->size ))
2429 // get the core class -- the only key of the top level FROM clause, or a string
2430 if (join_hash->type == JSON_HASH) {
2431 jsonIterator* tmp_itr = jsonNewIterator( join_hash );
2432 snode = jsonIteratorNext( tmp_itr );
2434 core_class = strdup( tmp_itr->key );
2437 jsonObject* extra = jsonIteratorNext( tmp_itr );
2439 jsonIteratorFree( tmp_itr );
2442 // There shouldn't be more than one entry in join_hash
2444 return NULL; // Malformed join_hash; extra entry
2446 } else if (join_hash->type == JSON_ARRAY) {
2448 core_class = jsonObjectToSimpleString( jsonObjectGetIndex(join_hash, 0) );
2451 } else if (join_hash->type == JSON_STRING) {
2452 core_class = jsonObjectToSimpleString( join_hash );
2458 if (!from_function) {
2459 // Get the IDL class definition for the core class
2460 core_meta = osrfHashGet( oilsIDL(), core_class );
2461 if( !core_meta ) { // Didn't find it?
2464 "%s: SELECT clause references undefined class: \"%s\"",
2469 osrfAppSessionStatus(
2471 OSRF_STATUS_INTERNALSERVERERROR,
2472 "osrfMethodException",
2474 "SELECT clause references undefined class in JSON query"
2480 // Make sure the class isn't virtual
2481 if( str_is_true( osrfHashGet( core_meta, "virtual" ) ) ) {
2484 "%s: Core class is virtual: \"%s\"",
2489 osrfAppSessionStatus(
2491 OSRF_STATUS_INTERNALSERVERERROR,
2492 "osrfMethodException",
2494 "FROM clause references virtual class in JSON query"
2501 // if the select list is empty, or the core class field list is '*',
2502 // build the default select list ...
2504 selhash = defaultselhash = jsonNewObjectType(JSON_HASH);
2505 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2506 } else if( selhash->type != JSON_HASH ) {
2507 const char* json_type;
2508 switch ( selhash->type )
2511 json_type = "JSON_ARRAY";
2514 json_type = "JSON_STRING";
2517 json_type = "JSON_NUMBER";
2520 json_type = "JSON_NULL";
2523 json_type = "JSON_BOOL";
2526 json_type = "(unrecognized)";
2531 "%s: Expected JSON_HASH for SELECT clause; found %s",
2537 osrfAppSessionStatus(
2539 OSRF_STATUS_INTERNALSERVERERROR,
2540 "osrfMethodException",
2542 "Malformed SELECT clause in JSON query"
2546 } else if ( (tmp_const = jsonObjectGetKeyConst( selhash, core_class )) && tmp_const->type == JSON_STRING ) {
2547 char* _x = jsonObjectToSimpleString( tmp_const );
2548 if (!strncmp( "*", _x, 1 )) {
2549 jsonObjectRemoveKey( selhash, core_class );
2550 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2556 growing_buffer* sql_buf = buffer_init(128);
2558 // temp buffer for the SELECT list
2559 growing_buffer* select_buf = buffer_init(128);
2560 growing_buffer* order_buf = buffer_init(128);
2561 growing_buffer* group_buf = buffer_init(128);
2562 growing_buffer* having_buf = buffer_init(128);
2564 // Build a select list
2565 if(from_function) // From a function we select everything
2566 OSRF_BUFFER_ADD_CHAR( select_buf, '*' );
2569 // If we need to build a default list, prepare to do so
2570 jsonObject* _tmp = jsonObjectGetKey( selhash, core_class );
2571 if ( _tmp && !_tmp->size ) {
2573 osrfHash* core_fields = osrfHashGet( core_meta, "fields" );
2575 osrfHashIterator* field_itr = osrfNewHashIterator( core_fields );
2576 osrfHash* field_def;
2577 while( ( field_def = osrfHashIteratorNext( field_itr ) ) ) {
2578 if( ! str_is_true( osrfHashGet( field_def, "virtual" ) ) ) {
2579 // This field is not virtual, so add it to the list
2580 jsonObjectPush( _tmp, jsonNewObject( osrfHashIteratorKey( field_itr ) ) );
2583 osrfHashIteratorFree( field_itr );
2586 // Now build the actual select list
2588 jsonObject* is_agg = jsonObjectFindPath(selhash, "//aggregate");
2591 jsonIterator* selclass_itr = jsonNewIterator( selhash );
2592 while ( (selclass = jsonIteratorNext( selclass_itr )) ) { // For each class
2594 // round trip through the idl, just to be safe
2595 const char* cname = selclass_itr->key;
2596 osrfHash* idlClass = osrfHashGet( oilsIDL(), cname );
2598 // No such class. Skip it.
2601 // Make sure the target relation is in the join tree.
2603 // At this point join_hash is a step down from the join_hash we
2604 // received as a parameter. If the original was a JSON_STRING,
2605 // then json_hash is now NULL. If the original was a JSON_HASH,
2606 // then json_hash is now the first (and only) entry in it,
2607 // denoting the core class. We've already excluded the
2608 // possibility that the original was a JSON_ARRAY, because in
2609 // that case from_function would be non-NULL, and we wouldn't
2612 int class_in_from_clause; // boolean
2614 if ( ! strcmp( core_class, cname ))
2615 // This is the core class -- no problem
2616 class_in_from_clause = 1;
2619 // There's only one class in the FROM clause, and this isn't it
2620 class_in_from_clause = 0;
2621 else if (join_hash->type == JSON_STRING) {
2622 // There's only one class in the FROM clause
2623 string = jsonObjectToSimpleString(join_hash);
2624 if ( strcmp( string, cname ) )
2625 class_in_from_clause = 0; // This isn't it
2627 class_in_from_clause = 1; // This is it
2630 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", cname);
2631 if ( 0 == found->size )
2632 class_in_from_clause = 0; // Nowhere in the join tree
2634 class_in_from_clause = 1; // Found it
2635 jsonObjectFree( found );
2639 // If the class isn't in the FROM clause, bail out
2640 if( ! class_in_from_clause ) {
2643 "%s: SELECT clause references class not in FROM clause: \"%s\"",
2648 osrfAppSessionStatus(
2650 OSRF_STATUS_INTERNALSERVERERROR,
2651 "osrfMethodException",
2653 "Selected class not in FROM clause in JSON query"
2655 jsonIteratorFree( selclass_itr );
2656 jsonObjectFree( is_agg );
2657 buffer_free( sql_buf );
2658 buffer_free( select_buf );
2659 buffer_free( order_buf );
2660 buffer_free( group_buf );
2661 buffer_free( having_buf );
2666 // Look up some attributes of the current class, so that we
2667 // don't have to look them up again for each field
2668 osrfHash* class_field_set = osrfHashGet( idlClass, "fields" );
2669 char* class_pkey = osrfHashGet( idlClass, "primarykey" );
2670 char* class_tname = osrfHashGet( idlClass, "tablename" );
2672 // stitch together the column list ...
2673 jsonIterator* select_itr = jsonNewIterator( selclass );
2674 while ( (selfield = jsonIteratorNext( select_itr )) ) { // for each SELECT column
2676 // If we need a separator comma, add one
2680 OSRF_BUFFER_ADD_CHAR( select_buf, ',' );
2683 // ... if it's a string, just toss it on the pile
2684 if (selfield->type == JSON_STRING) {
2686 // again, just to be safe
2687 const char* col_name = selfield->value.s;
2688 osrfHash* field_def = osrfHashGet( class_field_set, col_name );
2689 if ( !field_def ) continue; // No such field in current class; skip it
2693 if (flags & DISABLE_I18N)
2696 i18n = osrfHashGet(field_def, "i18n");
2698 if( str_is_true( i18n ) ) {
2699 buffer_fadd( select_buf,
2700 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2701 class_tname, cname, col_name, class_pkey, cname, class_pkey, locale, col_name );
2703 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2706 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2709 // ... but it could be an object, in which case we check for a Field Transform
2712 char* col_name = jsonObjectToSimpleString( jsonObjectGetKeyConst( selfield, "column" ) );
2714 // Get the field definition from the IDL
2715 osrfHash* field_def = osrfHashGet( class_field_set, col_name );
2716 if ( !field_def ) continue; // No such field defined in IDL. Skip it.
2718 // Decide what to use as a column alias
2720 if ((tmp_const = jsonObjectGetKeyConst( selfield, "alias" ))) {
2721 _alias = jsonObjectToSimpleString( tmp_const );
2722 } else { // Use field name as the alias
2726 if (jsonObjectGetKeyConst( selfield, "transform" )) {
2727 char* transform_str = searchFieldTransform(cname, field_def, selfield);
2728 buffer_fadd(select_buf, " %s AS \"%s\"", transform_str, _alias);
2729 free(transform_str);
2734 if (flags & DISABLE_I18N)
2737 i18n = osrfHashGet(field_def, "i18n");
2739 if( str_is_true( i18n ) ) {
2740 buffer_fadd( select_buf,
2741 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2742 class_tname, cname, col_name, class_pkey, cname, class_pkey, locale, _alias);
2744 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, _alias);
2747 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, _alias);
2751 if( _alias != col_name )
2756 if (is_agg->size || (flags & SELECT_DISTINCT)) {
2758 const jsonObject* aggregate_obj = jsonObjectGetKey( selfield, "aggregate" );
2759 if ( ! obj_is_true( aggregate_obj ) ) {
2763 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
2766 buffer_fadd(group_buf, " %d", sel_pos);
2768 } else if (is_agg = jsonObjectGetKey( selfield, "having" )) {
2772 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
2775 _column = searchFieldTransform(cname, field, selfield);
2776 OSRF_BUFFER_ADD_CHAR(group_buf, ' ');
2777 OSRF_BUFFER_ADD(group_buf, _column);
2778 _column = searchFieldTransform(cname, field, selfield);
2784 } // end while -- iterating across SELECT columns
2786 jsonIteratorFree(select_itr);
2787 } // end while -- iterating across classes
2789 jsonIteratorFree(selclass_itr);
2791 if (is_agg) jsonObjectFree(is_agg);
2795 char* col_list = buffer_release(select_buf);
2797 if (from_function) table = searchValueTransform(join_hash);
2798 else table = getSourceDefinition(core_meta);
2802 osrfAppSessionStatus(
2804 OSRF_STATUS_INTERNALSERVERERROR,
2805 "osrfMethodException",
2807 "Unable to identify table for core class"
2810 buffer_free( sql_buf );
2811 buffer_free( order_buf );
2812 buffer_free( group_buf );
2813 buffer_free( having_buf );
2814 if( defaultselhash ) jsonObjectFree( defaultselhash );
2819 // Put it all together
2820 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\" ", col_list, table, core_class );
2824 if (!from_function) {
2825 // Now, walk the join tree and add that clause
2827 char* join_clause = searchJOIN( join_hash, core_meta );
2829 buffer_add(sql_buf, join_clause);
2833 osrfAppSessionStatus(
2835 OSRF_STATUS_INTERNALSERVERERROR,
2836 "osrfMethodException",
2838 "Unable to construct JOIN clause(s)"
2840 buffer_free( sql_buf );
2841 buffer_free( order_buf );
2842 buffer_free( group_buf );
2843 buffer_free( having_buf );
2844 if( defaultselhash ) jsonObjectFree( defaultselhash );
2850 // Build a WHERE clause, if there is one
2851 if ( search_hash ) {
2852 buffer_add(sql_buf, " WHERE ");
2854 // and it's on the WHERE clause
2855 char* pred = searchWHERE( search_hash, core_meta, AND_OP_JOIN, ctx );
2858 buffer_add(sql_buf, pred);
2862 osrfAppSessionStatus(
2864 OSRF_STATUS_INTERNALSERVERERROR,
2865 "osrfMethodException",
2867 "Severe query error in WHERE predicate -- see error log for more details"
2871 buffer_free(having_buf);
2872 buffer_free(group_buf);
2873 buffer_free(order_buf);
2874 buffer_free(sql_buf);
2875 if (defaultselhash) jsonObjectFree(defaultselhash);
2880 // Build a HAVING clause, if there is one
2881 if ( having_hash ) {
2882 buffer_add(sql_buf, " HAVING ");
2884 // and it's on the the WHERE clause
2885 char* pred = searchWHERE( having_hash, core_meta, AND_OP_JOIN, ctx );
2888 buffer_add(sql_buf, pred);
2892 osrfAppSessionStatus(
2894 OSRF_STATUS_INTERNALSERVERERROR,
2895 "osrfMethodException",
2897 "Severe query error in HAVING predicate -- see error log for more details"
2901 buffer_free(having_buf);
2902 buffer_free(group_buf);
2903 buffer_free(order_buf);
2904 buffer_free(sql_buf);
2905 if (defaultselhash) jsonObjectFree(defaultselhash);
2910 // Build an ORDER BY clause, if there is one
2912 jsonIterator* class_itr = jsonNewIterator( order_hash );
2913 while ( (snode = jsonIteratorNext( class_itr )) ) {
2915 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
2918 if ( snode->type == JSON_HASH ) {
2920 jsonIterator* order_itr = jsonNewIterator( snode );
2921 while ( (onode = jsonIteratorNext( order_itr )) ) {
2923 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
2926 char* direction = NULL;
2927 if ( onode->type == JSON_HASH ) {
2928 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
2929 string = searchFieldTransform(
2931 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
2935 growing_buffer* field_buf = buffer_init(16);
2936 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
2937 string = buffer_release(field_buf);
2940 if ( (tmp_const = jsonObjectGetKeyConst( onode, "direction" )) ) {
2941 direction = jsonObjectToSimpleString(tmp_const);
2942 if (!strncasecmp(direction, "d", 1)) {
2944 direction = " DESC";
2952 string = strdup(order_itr->key);
2953 direction = jsonObjectToSimpleString(onode);
2954 if (!strncasecmp(direction, "d", 1)) {
2956 direction = " DESC";
2966 buffer_add(order_buf, ", ");
2969 buffer_add(order_buf, string);
2973 buffer_add(order_buf, direction);
2977 // jsonIteratorFree(order_itr);
2979 } else if ( snode->type == JSON_ARRAY ) {
2981 jsonIterator* order_itr = jsonNewIterator( snode );
2982 while ( (onode = jsonIteratorNext( order_itr )) ) {
2984 char* _f = jsonObjectToSimpleString( onode );
2986 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, _f))
2992 buffer_add(order_buf, ", ");
2995 buffer_add(order_buf, _f);
2999 // jsonIteratorFree(order_itr);
3002 // IT'S THE OOOOOOOOOOOLD STYLE!
3004 osrfLogError(OSRF_LOG_MARK, "%s: Possible SQL injection attempt; direct order by is not allowed", MODULENAME);
3006 osrfAppSessionStatus(
3008 OSRF_STATUS_INTERNALSERVERERROR,
3009 "osrfMethodException",
3011 "Severe query error -- see error log for more details"
3016 buffer_free(having_buf);
3017 buffer_free(group_buf);
3018 buffer_free(order_buf);
3019 buffer_free(sql_buf);
3020 if (defaultselhash) jsonObjectFree(defaultselhash);
3021 jsonIteratorFree(class_itr);
3026 // jsonIteratorFree(class_itr);
3030 string = buffer_release(group_buf);
3033 OSRF_BUFFER_ADD( sql_buf, " GROUP BY " );
3034 OSRF_BUFFER_ADD( sql_buf, string );
3039 string = buffer_release(having_buf);
3042 OSRF_BUFFER_ADD( sql_buf, " HAVING " );
3043 OSRF_BUFFER_ADD( sql_buf, string );
3048 string = buffer_release(order_buf);
3051 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
3052 OSRF_BUFFER_ADD( sql_buf, string );
3058 string = jsonObjectToSimpleString(limit);
3059 buffer_fadd( sql_buf, " LIMIT %d", atoi(string) );
3064 string = jsonObjectToSimpleString(offset);
3065 buffer_fadd( sql_buf, " OFFSET %d", atoi(string) );
3069 if (!(flags & SUBSELECT)) OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
3072 if (defaultselhash) jsonObjectFree(defaultselhash);
3074 return buffer_release(sql_buf);
3078 static char* buildSELECT ( jsonObject* search_hash, jsonObject* order_hash, osrfHash* meta, osrfMethodContext* ctx ) {
3080 const char* locale = osrf_message_get_last_locale();
3082 osrfHash* fields = osrfHashGet(meta, "fields");
3083 char* core_class = osrfHashGet(meta, "classname");
3085 const jsonObject* join_hash = jsonObjectGetKeyConst( order_hash, "join" );
3087 jsonObject* node = NULL;
3088 jsonObject* snode = NULL;
3089 jsonObject* onode = NULL;
3090 const jsonObject* _tmp = NULL;
3091 jsonObject* selhash = NULL;
3092 jsonObject* defaultselhash = NULL;
3094 growing_buffer* sql_buf = buffer_init(128);
3095 growing_buffer* select_buf = buffer_init(128);
3097 if ( !(selhash = jsonObjectGetKey( order_hash, "select" )) ) {
3098 defaultselhash = jsonNewObjectType(JSON_HASH);
3099 selhash = defaultselhash;
3102 if ( !jsonObjectGetKeyConst(selhash,core_class) ) {
3103 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
3104 jsonObject* flist = jsonObjectGetKey( selhash, core_class );
3109 osrfStringArray* keys = osrfHashKeys( fields );
3110 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
3111 if( ! str_is_true( osrfHashGet( osrfHashGet( fields, field ), "virtual" ) ) )
3112 jsonObjectPush( flist, jsonNewObject( field ) );
3114 osrfStringArrayFree(keys);
3118 jsonIterator* class_itr = jsonNewIterator( selhash );
3119 while ( (snode = jsonIteratorNext( class_itr )) ) {
3121 char* cname = class_itr->key;
3122 osrfHash* idlClass = osrfHashGet( oilsIDL(), cname );
3123 if (!idlClass) continue;
3125 if (strcmp(core_class,class_itr->key)) {
3126 if (!join_hash) continue;
3128 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", class_itr->key);
3130 jsonObjectFree(found);
3134 jsonObjectFree(found);
3137 jsonIterator* select_itr = jsonNewIterator( snode );
3138 while ( (node = jsonIteratorNext( select_itr )) ) {
3139 char* item_str = jsonObjectToSimpleString(node);
3140 osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), item_str );
3142 char* fname = osrfHashGet(field, "name");
3144 if (!field) continue;
3149 OSRF_BUFFER_ADD_CHAR(select_buf, ',');
3154 const jsonObject* no_i18n_obj = jsonObjectGetKey( order_hash, "no_i18n" );
3155 if ( obj_is_true( no_i18n_obj ) ) // Suppress internationalization?
3158 i18n = osrfHashGet(field, "i18n");
3160 if( str_is_true( i18n ) ) {
3161 char* pkey = osrfHashGet(idlClass, "primarykey");
3162 char* tname = osrfHashGet(idlClass, "tablename");
3164 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);
3166 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
3169 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
3173 jsonIteratorFree(select_itr);
3176 jsonIteratorFree(class_itr);
3178 char* col_list = buffer_release(select_buf);
3179 char* table = getSourceDefinition(meta);
3181 table = strdup( "(null)" );
3183 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\"", col_list, table, core_class );
3188 char* join_clause = searchJOIN( join_hash, meta );
3189 OSRF_BUFFER_ADD_CHAR(sql_buf, ' ');
3190 OSRF_BUFFER_ADD(sql_buf, join_clause);
3194 osrfLogDebug(OSRF_LOG_MARK, "%s pre-predicate SQL = %s",
3195 MODULENAME, OSRF_BUFFER_C_STR(sql_buf));
3197 buffer_add(sql_buf, " WHERE ");
3199 char* pred = searchWHERE( search_hash, meta, AND_OP_JOIN, ctx );
3201 osrfAppSessionStatus(
3203 OSRF_STATUS_INTERNALSERVERERROR,
3204 "osrfMethodException",
3206 "Severe query error -- see error log for more details"
3208 buffer_free(sql_buf);
3209 if(defaultselhash) jsonObjectFree(defaultselhash);
3212 buffer_add(sql_buf, pred);
3217 char* string = NULL;
3218 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "order_by" )) ){
3220 growing_buffer* order_buf = buffer_init(128);
3223 jsonIterator* class_itr = jsonNewIterator( _tmp );
3224 while ( (snode = jsonIteratorNext( class_itr )) ) {
3226 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
3229 if ( snode->type == JSON_HASH ) {
3231 jsonIterator* order_itr = jsonNewIterator( snode );
3232 while ( (onode = jsonIteratorNext( order_itr )) ) {
3234 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
3237 char* direction = NULL;
3238 if ( onode->type == JSON_HASH ) {
3239 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
3240 string = searchFieldTransform(
3242 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
3246 growing_buffer* field_buf = buffer_init(16);
3247 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
3248 string = buffer_release(field_buf);
3251 if ( (_tmp = jsonObjectGetKeyConst( onode, "direction" )) ) {
3252 direction = jsonObjectToSimpleString(_tmp);
3253 if (!strncasecmp(direction, "d", 1)) {
3255 direction = " DESC";
3263 string = strdup(order_itr->key);
3264 direction = jsonObjectToSimpleString(onode);
3265 if (!strncasecmp(direction, "d", 1)) {
3267 direction = " DESC";
3277 buffer_add(order_buf, ", ");
3280 buffer_add(order_buf, string);
3284 buffer_add(order_buf, direction);
3289 jsonIteratorFree(order_itr);
3292 string = jsonObjectToSimpleString(snode);
3293 buffer_add(order_buf, string);
3300 jsonIteratorFree(class_itr);
3302 string = buffer_release(order_buf);
3305 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
3306 OSRF_BUFFER_ADD( sql_buf, string );
3312 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "limit" )) ){
3313 string = jsonObjectToSimpleString(_tmp);
3322 _tmp = jsonObjectGetKeyConst( order_hash, "offset" );
3324 string = jsonObjectToSimpleString(_tmp);
3334 if (defaultselhash) jsonObjectFree(defaultselhash);
3336 OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
3337 return buffer_release(sql_buf);
3340 int doJSONSearch ( osrfMethodContext* ctx ) {
3341 if(osrfMethodVerifyContext( ctx )) {
3342 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
3346 osrfLogDebug(OSRF_LOG_MARK, "Recieved query request");
3351 dbhandle = writehandle;
3353 jsonObject* hash = jsonObjectGetIndex(ctx->params, 0);
3357 if ( obj_is_true( jsonObjectGetKey( hash, "distinct" ) ) )
3358 flags |= SELECT_DISTINCT;
3360 if ( obj_is_true( jsonObjectGetKey( hash, "no_i18n" ) ) )
3361 flags |= DISABLE_I18N;
3363 osrfLogDebug(OSRF_LOG_MARK, "Building SQL ...");
3366 jsonObjectGetKey( hash, "select" ),
3367 jsonObjectGetKey( hash, "from" ),
3368 jsonObjectGetKey( hash, "where" ),
3369 jsonObjectGetKey( hash, "having" ),
3370 jsonObjectGetKey( hash, "order_by" ),
3371 jsonObjectGetKey( hash, "limit" ),
3372 jsonObjectGetKey( hash, "offset" ),
3381 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3382 dbi_result result = dbi_conn_query(dbhandle, sql);
3385 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3387 if (dbi_result_first_row(result)) {
3388 /* JSONify the result */
3389 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3392 jsonObject* return_val = oilsMakeJSONFromResult( result );
3393 osrfAppRespond( ctx, return_val );
3394 jsonObjectFree( return_val );
3395 } while (dbi_result_next_row(result));
3398 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
3401 osrfAppRespondComplete( ctx, NULL );
3403 /* clean up the query */
3404 dbi_result_free(result);
3408 osrfLogError(OSRF_LOG_MARK, "%s: Error with query [%s]", MODULENAME, sql);
3409 osrfAppSessionStatus(
3411 OSRF_STATUS_INTERNALSERVERERROR,
3412 "osrfMethodException",
3414 "Severe query error -- see error log for more details"
3422 static jsonObject* doFieldmapperSearch ( osrfMethodContext* ctx, osrfHash* meta,
3423 const jsonObject* params, int* err ) {
3426 dbhandle = writehandle;
3428 osrfHash* links = osrfHashGet(meta, "links");
3429 osrfHash* fields = osrfHashGet(meta, "fields");
3430 char* core_class = osrfHashGet(meta, "classname");
3431 char* pkey = osrfHashGet(meta, "primarykey");
3433 const jsonObject* _tmp;
3435 jsonObject* search_hash = jsonObjectGetIndex(params, 0);
3436 jsonObject* order_hash = jsonObjectGetIndex(params, 1);
3438 char* sql = buildSELECT( search_hash, order_hash, meta, ctx );
3440 osrfLogDebug(OSRF_LOG_MARK, "Problem building query, returning NULL");
3445 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3447 dbi_result result = dbi_conn_query(dbhandle, sql);
3448 if( NULL == result ) {
3449 osrfLogError(OSRF_LOG_MARK, "%s: Error retrieving %s with query [%s]",
3450 MODULENAME, osrfHashGet(meta, "fieldmapper"), sql);
3451 osrfAppSessionStatus(
3453 OSRF_STATUS_INTERNALSERVERERROR,
3454 "osrfMethodException",
3456 "Severe query error -- see error log for more details"
3463 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3466 jsonObject* res_list = jsonNewObjectType(JSON_ARRAY);
3467 osrfHash* dedup = osrfNewHash();
3469 if (dbi_result_first_row(result)) {
3470 /* JSONify the result */
3471 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3473 obj = oilsMakeFieldmapperFromResult( result, meta );
3474 char* pkey_val = oilsFMGetString( obj, pkey );
3475 if ( osrfHashGet( dedup, pkey_val ) ) {
3476 jsonObjectFree(obj);
3479 osrfHashSet( dedup, pkey_val, pkey_val );
3480 jsonObjectPush(res_list, obj);
3482 } while (dbi_result_next_row(result));
3484 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s",
3488 osrfHashFree(dedup);
3489 /* clean up the query */
3490 dbi_result_free(result);
3493 if (res_list->size && order_hash) {
3494 _tmp = jsonObjectGetKeyConst( order_hash, "flesh" );
3496 int x = (int)jsonObjectGetNumber(_tmp);
3497 if (x == -1 || x > max_flesh_depth) x = max_flesh_depth;
3499 const jsonObject* temp_blob;
3500 if ((temp_blob = jsonObjectGetKeyConst( order_hash, "flesh_fields" )) && x > 0) {
3502 jsonObject* flesh_blob = jsonObjectClone( temp_blob );
3503 const jsonObject* flesh_fields = jsonObjectGetKeyConst( flesh_blob, core_class );
3505 osrfStringArray* link_fields = NULL;
3508 if (flesh_fields->size == 1) {
3509 char* _t = jsonObjectToSimpleString( jsonObjectGetIndex( flesh_fields, 0 ) );
3510 if (!strcmp(_t,"*")) link_fields = osrfHashKeys( links );
3516 link_fields = osrfNewStringArray(1);
3517 jsonIterator* _i = jsonNewIterator( flesh_fields );
3518 while ((_f = jsonIteratorNext( _i ))) {
3519 osrfStringArrayAdd( link_fields, jsonObjectToSimpleString( _f ) );
3521 jsonIteratorFree(_i);
3526 jsonIterator* itr = jsonNewIterator( res_list );
3527 while ((cur = jsonIteratorNext( itr ))) {
3532 while ( (link_field = osrfStringArrayGetString(link_fields, i++)) ) {
3534 osrfLogDebug(OSRF_LOG_MARK, "Starting to flesh %s", link_field);
3536 osrfHash* kid_link = osrfHashGet(links, link_field);
3537 if (!kid_link) continue;
3539 osrfHash* field = osrfHashGet(fields, link_field);
3540 if (!field) continue;
3542 osrfHash* value_field = field;
3544 osrfHash* kid_idl = osrfHashGet(oilsIDL(), osrfHashGet(kid_link, "class"));
3545 if (!kid_idl) continue;
3547 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3548 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3551 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) { // might_have
3552 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3555 osrfStringArray* link_map = osrfHashGet( kid_link, "map" );
3557 if (link_map->size > 0) {
3558 jsonObject* _kid_key = jsonNewObjectType(JSON_ARRAY);
3561 jsonNewObject( osrfStringArrayGetString( link_map, 0 ) )
3566 osrfHashGet(kid_link, "class"),
3573 "Link field: %s, remote class: %s, fkey: %s, reltype: %s",
3574 osrfHashGet(kid_link, "field"),
3575 osrfHashGet(kid_link, "class"),
3576 osrfHashGet(kid_link, "key"),
3577 osrfHashGet(kid_link, "reltype")
3580 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
3581 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // search hash
3582 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // order/flesh hash
3584 osrfLogDebug(OSRF_LOG_MARK, "Creating dummy params object...");
3587 jsonObjectToSimpleString(
3590 atoi( osrfHashGet(value_field, "array_position") )
3595 osrfLogDebug(OSRF_LOG_MARK, "Nothing to search for!");
3600 jsonObjectGetIndex(fake_params, 0),
3601 osrfHashGet(kid_link, "key"),
3602 jsonNewObject( search_key )
3609 jsonObjectGetIndex(fake_params, 1),
3611 jsonNewNumberObject( (double)(x - 1 + link_map->size) )
3615 jsonObjectSetKey( jsonObjectGetIndex(fake_params, 1), "flesh_fields", jsonObjectClone(flesh_blob) );
3617 if (jsonObjectGetKeyConst(order_hash, "order_by")) {
3619 jsonObjectGetIndex(fake_params, 1),
3621 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "order_by"))
3625 if (jsonObjectGetKeyConst(order_hash, "select")) {
3627 jsonObjectGetIndex(fake_params, 1),
3629 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "select"))
3633 jsonObject* kids = doFieldmapperSearch(ctx, kid_idl, fake_params, err);
3636 jsonObjectFree( fake_params );
3637 osrfStringArrayFree(link_fields);
3638 jsonIteratorFree(itr);
3639 jsonObjectFree(res_list);
3640 jsonObjectFree(flesh_blob);
3644 osrfLogDebug(OSRF_LOG_MARK, "Search for %s return %d linked objects", osrfHashGet(kid_link, "class"), kids->size);
3646 jsonObject* X = NULL;
3647 if ( link_map->size > 0 && kids->size > 0 ) {
3649 kids = jsonNewObjectType(JSON_ARRAY);
3651 jsonObject* _k_node;
3652 jsonIterator* _k = jsonNewIterator( X );
3653 while ((_k_node = jsonIteratorNext( _k ))) {
3659 (unsigned long)atoi(
3665 osrfHashGet(kid_link, "class")
3669 osrfStringArrayGetString( link_map, 0 )
3678 jsonIteratorFree(_k);
3681 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_a" )) || !(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) {
3682 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3685 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3686 jsonObjectClone( jsonObjectGetIndex(kids, 0) )
3690 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3691 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3694 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3695 jsonObjectClone( kids )
3700 jsonObjectFree(kids);
3704 jsonObjectFree( kids );
3705 jsonObjectFree( fake_params );
3707 osrfLogDebug(OSRF_LOG_MARK, "Fleshing of %s complete", osrfHashGet(kid_link, "field"));
3708 osrfLogDebug(OSRF_LOG_MARK, "%s", jsonObjectToJSON(cur));
3712 jsonObjectFree( flesh_blob );
3713 osrfStringArrayFree(link_fields);
3714 jsonIteratorFree(itr);
3723 static jsonObject* doUpdate(osrfMethodContext* ctx, int* err ) {
3725 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3727 jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
3729 jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
3732 if (!verifyObjectClass(ctx, target)) {
3737 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3738 osrfAppSessionStatus(
3740 OSRF_STATUS_BADREQUEST,
3741 "osrfMethodException",
3743 "No active transaction -- required for UPDATE"
3749 // The following test is harmless but redundant. If a class is
3750 // readonly, we don't register an update method for it.
3751 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
3752 osrfAppSessionStatus(
3754 OSRF_STATUS_BADREQUEST,
3755 "osrfMethodException",
3757 "Cannot UPDATE readonly class"
3763 dbhandle = writehandle;
3765 char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
3767 // Set the last_xact_id
3768 int index = oilsIDL_ntop( target->classname, "last_xact_id" );
3770 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
3771 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
3774 char* pkey = osrfHashGet(meta, "primarykey");
3775 osrfHash* fields = osrfHashGet(meta, "fields");
3777 char* id = oilsFMGetString( target, pkey );
3781 "%s updating %s object with %s = %s",
3783 osrfHashGet(meta, "fieldmapper"),
3788 growing_buffer* sql = buffer_init(128);
3789 buffer_fadd(sql,"UPDATE %s SET", osrfHashGet(meta, "tablename"));
3794 osrfStringArray* field_list = osrfHashKeys( fields );
3795 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
3797 osrfHash* field = osrfHashGet( fields, field_name );
3799 if(!( strcmp( field_name, pkey ) )) continue;
3800 if( str_is_true( osrfHashGet(osrfHashGet(fields,field_name), "virtual") ) )
3803 const jsonObject* field_object = oilsFMGetObject( target, field_name );
3806 if (field_object && field_object->classname) {
3807 value = oilsFMGetString(
3809 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
3812 value = jsonObjectToSimpleString( field_object );
3815 osrfLogDebug( OSRF_LOG_MARK, "Updating %s object with %s = %s", osrfHashGet(meta, "fieldmapper"), field_name, value);
3817 if (!field_object || field_object->type == JSON_NULL) {
3818 if ( !(!( strcmp( osrfHashGet(meta, "classname"), "au" ) ) && !( strcmp( field_name, "passwd" ) )) ) { // arg at the special case!
3819 if (first) first = 0;
3820 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3821 buffer_fadd( sql, " %s = NULL", field_name );
3824 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
3825 if (first) first = 0;
3826 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3828 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
3829 buffer_fadd( sql, " %s = %ld", field_name, atol(value) );
3830 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
3831 buffer_fadd( sql, " %s = %f", field_name, atof(value) );
3834 osrfLogDebug( OSRF_LOG_MARK, "%s is of type %s", field_name, osrfHashGet(field, "datatype"));
3837 if ( dbi_conn_quote_string(dbhandle, &value) ) {
3838 if (first) first = 0;
3839 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3840 buffer_fadd( sql, " %s = %s", field_name, value );
3843 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
3844 osrfAppSessionStatus(
3846 OSRF_STATUS_INTERNALSERVERERROR,
3847 "osrfMethodException",
3849 "Error quoting string -- please see the error log for more details"
3863 jsonObject* obj = jsonNewObject(id);
3865 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
3866 dbi_conn_quote_string(dbhandle, &id);
3868 buffer_fadd( sql, " WHERE %s = %s;", pkey, id );
3870 char* query = buffer_release(sql);
3871 osrfLogDebug(OSRF_LOG_MARK, "%s: Update SQL [%s]", MODULENAME, query);
3873 dbi_result result = dbi_conn_query(dbhandle, query);
3877 jsonObjectFree(obj);
3878 obj = jsonNewObject(NULL);
3881 "%s ERROR updating %s object with %s = %s",
3883 osrfHashGet(meta, "fieldmapper"),
3894 static jsonObject* doDelete(osrfMethodContext* ctx, int* err ) {
3896 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3898 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3899 osrfAppSessionStatus(
3901 OSRF_STATUS_BADREQUEST,
3902 "osrfMethodException",
3904 "No active transaction -- required for DELETE"
3910 // The following test is harmless but redundant. If a class is
3911 // readonly, we don't register a delete method for it.
3912 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
3913 osrfAppSessionStatus(
3915 OSRF_STATUS_BADREQUEST,
3916 "osrfMethodException",
3918 "Cannot DELETE readonly class"
3924 dbhandle = writehandle;
3928 char* pkey = osrfHashGet(meta, "primarykey");
3936 if (jsonObjectGetIndex(ctx->params, _obj_pos)->classname) {
3937 if (!verifyObjectClass(ctx, jsonObjectGetIndex( ctx->params, _obj_pos ))) {
3942 id = oilsFMGetString( jsonObjectGetIndex(ctx->params, _obj_pos), pkey );
3945 if (!verifyObjectPCRUD( ctx, NULL )) {
3950 id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, _obj_pos));
3955 "%s deleting %s object with %s = %s",
3957 osrfHashGet(meta, "fieldmapper"),
3962 obj = jsonNewObject(id);
3964 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
3965 dbi_conn_quote_string(writehandle, &id);
3967 dbi_result result = dbi_conn_queryf(writehandle, "DELETE FROM %s WHERE %s = %s;", osrfHashGet(meta, "tablename"), pkey, id);
3970 jsonObjectFree(obj);
3971 obj = jsonNewObject(NULL);
3974 "%s ERROR deleting %s object with %s = %s",
3976 osrfHashGet(meta, "fieldmapper"),
3989 static jsonObject* oilsMakeFieldmapperFromResult( dbi_result result, osrfHash* meta) {
3990 if(!(result && meta)) return jsonNULL;
3992 jsonObject* object = jsonNewObject(NULL);
3993 jsonObjectSetClass(object, osrfHashGet(meta, "classname"));
3995 osrfHash* fields = osrfHashGet(meta, "fields");
3997 osrfLogInternal(OSRF_LOG_MARK, "Setting object class to %s ", object->classname);
4001 char dt_string[256];
4005 int columnIndex = 1;
4007 unsigned short type;
4008 const char* columnName;
4010 /* cycle through the column list */
4011 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
4013 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
4015 fmIndex = -1; // reset the position
4017 /* determine the field type and storage attributes */
4018 type = dbi_result_get_field_type(result, columnName);
4019 attr = dbi_result_get_field_attribs(result, columnName);
4021 /* fetch the fieldmapper index */
4022 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
4024 if ( str_is_true( osrfHashGet(_f, "virtual") ) )
4027 const char* pos = (char*)osrfHashGet(_f, "array_position");
4028 if ( !pos ) continue;
4030 fmIndex = atoi( pos );
4031 osrfLogInternal(OSRF_LOG_MARK, "... Found column at position [%s]...", pos);
4036 if (dbi_result_field_is_null(result, columnName)) {
4037 jsonObjectSetIndex( object, fmIndex, jsonNewObject(NULL) );
4042 case DBI_TYPE_INTEGER :
4044 if( attr & DBI_INTEGER_SIZE8 )
4045 jsonObjectSetIndex( object, fmIndex,
4046 jsonNewNumberObject(dbi_result_get_longlong(result, columnName)));
4048 jsonObjectSetIndex( object, fmIndex,
4049 jsonNewNumberObject(dbi_result_get_int(result, columnName)));
4053 case DBI_TYPE_DECIMAL :
4054 jsonObjectSetIndex( object, fmIndex,
4055 jsonNewNumberObject(dbi_result_get_double(result, columnName)));
4058 case DBI_TYPE_STRING :
4064 jsonNewObject( dbi_result_get_string(result, columnName) )
4069 case DBI_TYPE_DATETIME :
4071 memset(dt_string, '\0', sizeof(dt_string));
4072 memset(&gmdt, '\0', sizeof(gmdt));
4074 _tmp_dt = dbi_result_get_datetime(result, columnName);
4077 if (!(attr & DBI_DATETIME_DATE)) {
4078 gmtime_r( &_tmp_dt, &gmdt );
4079 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
4080 } else if (!(attr & DBI_DATETIME_TIME)) {
4081 localtime_r( &_tmp_dt, &gmdt );
4082 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
4084 localtime_r( &_tmp_dt, &gmdt );
4085 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
4088 jsonObjectSetIndex( object, fmIndex, jsonNewObject(dt_string) );
4092 case DBI_TYPE_BINARY :
4093 osrfLogError( OSRF_LOG_MARK,
4094 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
4102 static jsonObject* oilsMakeJSONFromResult( dbi_result result ) {
4103 if(!result) return jsonNULL;
4105 jsonObject* object = jsonNewObject(NULL);
4108 char dt_string[256];
4112 int columnIndex = 1;
4114 unsigned short type;
4115 const char* columnName;
4117 /* cycle through the column list */
4118 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
4120 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
4122 fmIndex = -1; // reset the position
4124 /* determine the field type and storage attributes */
4125 type = dbi_result_get_field_type(result, columnName);
4126 attr = dbi_result_get_field_attribs(result, columnName);
4128 if (dbi_result_field_is_null(result, columnName)) {
4129 jsonObjectSetKey( object, columnName, jsonNewObject(NULL) );
4134 case DBI_TYPE_INTEGER :
4136 if( attr & DBI_INTEGER_SIZE8 )
4137 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_longlong(result, columnName)) );
4139 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_int(result, columnName)) );
4142 case DBI_TYPE_DECIMAL :
4143 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_double(result, columnName)) );
4146 case DBI_TYPE_STRING :
4147 jsonObjectSetKey( object, columnName, jsonNewObject(dbi_result_get_string(result, columnName)) );
4150 case DBI_TYPE_DATETIME :
4152 memset(dt_string, '\0', sizeof(dt_string));
4153 memset(&gmdt, '\0', sizeof(gmdt));
4155 _tmp_dt = dbi_result_get_datetime(result, columnName);
4158 if (!(attr & DBI_DATETIME_DATE)) {
4159 gmtime_r( &_tmp_dt, &gmdt );
4160 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
4161 } else if (!(attr & DBI_DATETIME_TIME)) {
4162 localtime_r( &_tmp_dt, &gmdt );
4163 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
4165 localtime_r( &_tmp_dt, &gmdt );
4166 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
4169 jsonObjectSetKey( object, columnName, jsonNewObject(dt_string) );
4172 case DBI_TYPE_BINARY :
4173 osrfLogError( OSRF_LOG_MARK,
4174 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
4182 // Interpret a string as true or false
4183 static int str_is_true( const char* str ) {
4184 if( NULL == str || strcasecmp( str, "true" ) )
4190 // Interpret a jsonObject as true or false
4191 static int obj_is_true( const jsonObject* obj ) {
4194 else switch( obj->type )
4202 if( strcasecmp( obj->value.s, "true" ) )
4206 case JSON_NUMBER : // Support 1/0 for perl's sake
4207 if( jsonObjectGetNumber( obj ) == 1.0 )