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 // punt if we don't know about the core class (and it's not a function)
2459 if (!from_function && !(core_meta = osrfHashGet( oilsIDL(), core_class ))) {
2464 // if the select list is empty, or the core class field list is '*',
2465 // build the default select list ...
2467 selhash = defaultselhash = jsonNewObjectType(JSON_HASH);
2468 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2469 } else if ( (tmp_const = jsonObjectGetKeyConst( selhash, core_class )) && tmp_const->type == JSON_STRING ) {
2470 char* _x = jsonObjectToSimpleString( tmp_const );
2471 if (!strncmp( "*", _x, 1 )) {
2472 jsonObjectRemoveKey( selhash, core_class );
2473 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2479 growing_buffer* sql_buf = buffer_init(128);
2481 // temp buffer for the SELECT list
2482 growing_buffer* select_buf = buffer_init(128);
2483 growing_buffer* order_buf = buffer_init(128);
2484 growing_buffer* group_buf = buffer_init(128);
2485 growing_buffer* having_buf = buffer_init(128);
2487 // Build a select list
2488 if(from_function) // From a function we select everything
2489 OSRF_BUFFER_ADD_CHAR( select_buf, '*' );
2492 // If we need to build a default list, prepare to do so
2493 jsonObject* _tmp = jsonObjectGetKey( selhash, core_class );
2494 if ( _tmp && !_tmp->size ) {
2496 osrfHash* core_fields = osrfHashGet( core_meta, "fields" );
2498 osrfHashIterator* field_itr = osrfNewHashIterator( core_fields );
2499 osrfHash* field_def;
2500 while( ( field_def = osrfHashIteratorNext( field_itr ) ) ) {
2501 if( ! str_is_true( osrfHashGet( field_def, "virtual" ) ) ) {
2502 // This field is not virtual, so add it to the list
2503 jsonObjectPush( _tmp, jsonNewObject( osrfHashIteratorKey( field_itr ) ) );
2506 osrfHashIteratorFree( field_itr );
2509 // Now build the actual select list
2511 jsonObject* is_agg = jsonObjectFindPath(selhash, "//aggregate");
2514 jsonIterator* selclass_itr = jsonNewIterator( selhash );
2515 while ( (selclass = jsonIteratorNext( selclass_itr )) ) { // For each class
2517 // round trip through the idl, just to be safe
2518 const char* cname = selclass_itr->key;
2519 osrfHash* idlClass = osrfHashGet( oilsIDL(), cname );
2521 // No such class. Skip it.
2524 // Make sure the target relation is in the join tree.
2526 // At this point join_hash is a step down from the join_hash we
2527 // received as a parameter. If the original was a JSON_STRING,
2528 // then json_hash is now NULL. If the original was a JSON_HASH,
2529 // then json_hash is now the first (and only) entry in it,
2530 // denoting the core class. We've already excluded the
2531 // possibility that the original was a JSON_ARRAY, because in
2532 // that case from_function would be non-NULL, and we wouldn't
2535 if ( strcmp( core_class, cname )) {
2537 // There's only one class in the FROM clause,
2538 // and this isn't it. Skip it.
2541 if (join_hash->type == JSON_STRING) {
2542 string = jsonObjectToSimpleString(join_hash);
2543 int different = strcmp( string, cname );
2546 // There's only one class in the FROM clause,
2547 // and this isn't it. Skip it.
2550 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", cname);
2551 unsigned long size = found->size;
2552 jsonObjectFree( found );
2554 // No such class anywhere in the join tree. Skip it.
2559 // Look up some attributes of the current class, so that we
2560 // don't have to look them up again for each field
2561 osrfHash* class_field_set = osrfHashGet( idlClass, "fields" );
2562 char* class_pkey = osrfHashGet( idlClass, "primarykey" );
2563 char* class_tname = osrfHashGet( idlClass, "tablename" );
2565 // stitch together the column list ...
2566 jsonIterator* select_itr = jsonNewIterator( selclass );
2567 while ( (selfield = jsonIteratorNext( select_itr )) ) { // for each SELECT column
2569 // If we need a separator comma, add one
2573 OSRF_BUFFER_ADD_CHAR( select_buf, ',' );
2576 // ... if it's a string, just toss it on the pile
2577 if (selfield->type == JSON_STRING) {
2579 // again, just to be safe
2580 const char* _requested_col = selfield->value.s;
2581 osrfHash* field = osrfHashGet( class_field_set, _requested_col );
2582 if (!field) continue; // No such field in current class; skip it
2584 const char* col_name = osrfHashGet(field, "name");
2588 if (flags & DISABLE_I18N)
2591 i18n = osrfHashGet(field, "i18n");
2593 if( str_is_true( i18n ) ) {
2594 buffer_fadd( select_buf,
2595 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2596 class_tname, cname, col_name, class_pkey, cname, class_pkey, locale, col_name );
2598 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2601 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2604 // ... but it could be an object, in which case we check for a Field Transform
2607 char* _column = jsonObjectToSimpleString( jsonObjectGetKeyConst( selfield, "column" ) );
2609 // Get the field definition from the IDL
2610 osrfHash* field = osrfHashGet( class_field_set, _column );
2611 if (!field) continue; // No such field defined in IDL. Skip it.
2613 // Decide what to use as a column alias
2615 if ((tmp_const = jsonObjectGetKeyConst( selfield, "alias" ))) {
2616 _alias = jsonObjectToSimpleString( tmp_const );
2618 } else { // Use column name as its own alias
2621 _column = NULL; // To emphasize that we're through with _column
2623 if (jsonObjectGetKeyConst( selfield, "transform" )) {
2624 char* transform_str = searchFieldTransform(cname, field, selfield);
2625 buffer_fadd(select_buf, " %s AS \"%s\"", transform_str, _alias);
2626 free(transform_str);
2629 const char* fname = osrfHashGet(field, "name");
2633 if (flags & DISABLE_I18N)
2636 i18n = osrfHashGet(field, "i18n");
2638 if( str_is_true( i18n ) ) {
2639 buffer_fadd( select_buf,
2640 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2641 class_tname, cname, fname, class_pkey, cname, class_pkey, locale, _alias);
2643 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, fname, _alias);
2646 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, fname, _alias);
2653 if (is_agg->size || (flags & SELECT_DISTINCT)) {
2655 const jsonObject* aggregate_obj = jsonObjectGetKey( selfield, "aggregate" );
2656 if ( ! obj_is_true( aggregate_obj ) ) {
2660 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
2663 buffer_fadd(group_buf, " %d", sel_pos);
2665 } else if (is_agg = jsonObjectGetKey( selfield, "having" )) {
2669 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
2672 _column = searchFieldTransform(cname, field, selfield);
2673 OSRF_BUFFER_ADD_CHAR(group_buf, ' ');
2674 OSRF_BUFFER_ADD(group_buf, _column);
2675 _column = searchFieldTransform(cname, field, selfield);
2681 } // end while -- iterating across SELECT columns
2683 jsonIteratorFree(select_itr);
2684 } // end while -- iterating across classes
2686 jsonIteratorFree(selclass_itr);
2688 if (is_agg) jsonObjectFree(is_agg);
2692 char* col_list = buffer_release(select_buf);
2694 if (from_function) table = searchValueTransform(join_hash);
2695 else table = getSourceDefinition(core_meta);
2699 osrfAppSessionStatus(
2701 OSRF_STATUS_INTERNALSERVERERROR,
2702 "osrfMethodException",
2704 "Unable to identify table for core class"
2707 buffer_free( sql_buf );
2708 buffer_free( order_buf );
2709 buffer_free( group_buf );
2710 buffer_free( having_buf );
2711 if( defaultselhash ) jsonObjectFree( defaultselhash );
2716 // Put it all together
2717 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\" ", col_list, table, core_class );
2721 if (!from_function) {
2722 // Now, walk the join tree and add that clause
2724 char* join_clause = searchJOIN( join_hash, core_meta );
2726 buffer_add(sql_buf, join_clause);
2730 osrfAppSessionStatus(
2732 OSRF_STATUS_INTERNALSERVERERROR,
2733 "osrfMethodException",
2735 "Unable to construct JOIN clause(s)"
2737 buffer_free( sql_buf );
2738 buffer_free( order_buf );
2739 buffer_free( group_buf );
2740 buffer_free( having_buf );
2741 if( defaultselhash ) jsonObjectFree( defaultselhash );
2747 // Build a WHERE clause, if there is one
2748 if ( search_hash ) {
2749 buffer_add(sql_buf, " WHERE ");
2751 // and it's on the WHERE clause
2752 char* pred = searchWHERE( search_hash, core_meta, AND_OP_JOIN, ctx );
2755 buffer_add(sql_buf, pred);
2759 osrfAppSessionStatus(
2761 OSRF_STATUS_INTERNALSERVERERROR,
2762 "osrfMethodException",
2764 "Severe query error in WHERE predicate -- see error log for more details"
2768 buffer_free(having_buf);
2769 buffer_free(group_buf);
2770 buffer_free(order_buf);
2771 buffer_free(sql_buf);
2772 if (defaultselhash) jsonObjectFree(defaultselhash);
2777 // Build a HAVING clause, if there is one
2778 if ( having_hash ) {
2779 buffer_add(sql_buf, " HAVING ");
2781 // and it's on the the WHERE clause
2782 char* pred = searchWHERE( having_hash, core_meta, AND_OP_JOIN, ctx );
2785 buffer_add(sql_buf, pred);
2789 osrfAppSessionStatus(
2791 OSRF_STATUS_INTERNALSERVERERROR,
2792 "osrfMethodException",
2794 "Severe query error in HAVING predicate -- see error log for more details"
2798 buffer_free(having_buf);
2799 buffer_free(group_buf);
2800 buffer_free(order_buf);
2801 buffer_free(sql_buf);
2802 if (defaultselhash) jsonObjectFree(defaultselhash);
2807 // Build an ORDER BY clause, if there is one
2809 jsonIterator* class_itr = jsonNewIterator( order_hash );
2810 while ( (snode = jsonIteratorNext( class_itr )) ) {
2812 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
2815 if ( snode->type == JSON_HASH ) {
2817 jsonIterator* order_itr = jsonNewIterator( snode );
2818 while ( (onode = jsonIteratorNext( order_itr )) ) {
2820 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
2823 char* direction = NULL;
2824 if ( onode->type == JSON_HASH ) {
2825 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
2826 string = searchFieldTransform(
2828 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
2832 growing_buffer* field_buf = buffer_init(16);
2833 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
2834 string = buffer_release(field_buf);
2837 if ( (tmp_const = jsonObjectGetKeyConst( onode, "direction" )) ) {
2838 direction = jsonObjectToSimpleString(tmp_const);
2839 if (!strncasecmp(direction, "d", 1)) {
2841 direction = " DESC";
2849 string = strdup(order_itr->key);
2850 direction = jsonObjectToSimpleString(onode);
2851 if (!strncasecmp(direction, "d", 1)) {
2853 direction = " DESC";
2863 buffer_add(order_buf, ", ");
2866 buffer_add(order_buf, string);
2870 buffer_add(order_buf, direction);
2874 // jsonIteratorFree(order_itr);
2876 } else if ( snode->type == JSON_ARRAY ) {
2878 jsonIterator* order_itr = jsonNewIterator( snode );
2879 while ( (onode = jsonIteratorNext( order_itr )) ) {
2881 char* _f = jsonObjectToSimpleString( onode );
2883 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, _f))
2889 buffer_add(order_buf, ", ");
2892 buffer_add(order_buf, _f);
2896 // jsonIteratorFree(order_itr);
2899 // IT'S THE OOOOOOOOOOOLD STYLE!
2901 osrfLogError(OSRF_LOG_MARK, "%s: Possible SQL injection attempt; direct order by is not allowed", MODULENAME);
2903 osrfAppSessionStatus(
2905 OSRF_STATUS_INTERNALSERVERERROR,
2906 "osrfMethodException",
2908 "Severe query error -- see error log for more details"
2913 buffer_free(having_buf);
2914 buffer_free(group_buf);
2915 buffer_free(order_buf);
2916 buffer_free(sql_buf);
2917 if (defaultselhash) jsonObjectFree(defaultselhash);
2918 jsonIteratorFree(class_itr);
2923 // jsonIteratorFree(class_itr);
2927 string = buffer_release(group_buf);
2929 if (strlen(string)) {
2930 OSRF_BUFFER_ADD( sql_buf, " GROUP BY " );
2931 OSRF_BUFFER_ADD( sql_buf, string );
2936 string = buffer_release(having_buf);
2938 if (strlen(string)) {
2939 OSRF_BUFFER_ADD( sql_buf, " HAVING " );
2940 OSRF_BUFFER_ADD( sql_buf, string );
2945 string = buffer_release(order_buf);
2947 if (strlen(string)) {
2948 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
2949 OSRF_BUFFER_ADD( sql_buf, string );
2955 string = jsonObjectToSimpleString(limit);
2956 buffer_fadd( sql_buf, " LIMIT %d", atoi(string) );
2961 string = jsonObjectToSimpleString(offset);
2962 buffer_fadd( sql_buf, " OFFSET %d", atoi(string) );
2966 if (!(flags & SUBSELECT)) OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
2969 if (defaultselhash) jsonObjectFree(defaultselhash);
2971 return buffer_release(sql_buf);
2975 static char* buildSELECT ( jsonObject* search_hash, jsonObject* order_hash, osrfHash* meta, osrfMethodContext* ctx ) {
2977 const char* locale = osrf_message_get_last_locale();
2979 osrfHash* fields = osrfHashGet(meta, "fields");
2980 char* core_class = osrfHashGet(meta, "classname");
2982 const jsonObject* join_hash = jsonObjectGetKeyConst( order_hash, "join" );
2984 jsonObject* node = NULL;
2985 jsonObject* snode = NULL;
2986 jsonObject* onode = NULL;
2987 const jsonObject* _tmp = NULL;
2988 jsonObject* selhash = NULL;
2989 jsonObject* defaultselhash = NULL;
2991 growing_buffer* sql_buf = buffer_init(128);
2992 growing_buffer* select_buf = buffer_init(128);
2994 if ( !(selhash = jsonObjectGetKey( order_hash, "select" )) ) {
2995 defaultselhash = jsonNewObjectType(JSON_HASH);
2996 selhash = defaultselhash;
2999 if ( !jsonObjectGetKeyConst(selhash,core_class) ) {
3000 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
3001 jsonObject* flist = jsonObjectGetKey( selhash, core_class );
3006 osrfStringArray* keys = osrfHashKeys( fields );
3007 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
3008 if( ! str_is_true( osrfHashGet( osrfHashGet( fields, field ), "virtual" ) ) )
3009 jsonObjectPush( flist, jsonNewObject( field ) );
3011 osrfStringArrayFree(keys);
3015 jsonIterator* class_itr = jsonNewIterator( selhash );
3016 while ( (snode = jsonIteratorNext( class_itr )) ) {
3018 char* cname = class_itr->key;
3019 osrfHash* idlClass = osrfHashGet( oilsIDL(), cname );
3020 if (!idlClass) continue;
3022 if (strcmp(core_class,class_itr->key)) {
3023 if (!join_hash) continue;
3025 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", class_itr->key);
3027 jsonObjectFree(found);
3031 jsonObjectFree(found);
3034 jsonIterator* select_itr = jsonNewIterator( snode );
3035 while ( (node = jsonIteratorNext( select_itr )) ) {
3036 char* item_str = jsonObjectToSimpleString(node);
3037 osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), item_str );
3039 char* fname = osrfHashGet(field, "name");
3041 if (!field) continue;
3046 OSRF_BUFFER_ADD_CHAR(select_buf, ',');
3051 const jsonObject* no_i18n_obj = jsonObjectGetKey( order_hash, "no_i18n" );
3052 if ( obj_is_true( no_i18n_obj ) ) // Suppress internationalization?
3055 i18n = osrfHashGet(field, "i18n");
3057 if( str_is_true( i18n ) ) {
3058 char* pkey = osrfHashGet(idlClass, "primarykey");
3059 char* tname = osrfHashGet(idlClass, "tablename");
3061 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);
3063 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
3066 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
3070 jsonIteratorFree(select_itr);
3073 jsonIteratorFree(class_itr);
3075 char* col_list = buffer_release(select_buf);
3076 char* table = getSourceDefinition(meta);
3078 table = strdup( "(null)" );
3080 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\"", col_list, table, core_class );
3085 char* join_clause = searchJOIN( join_hash, meta );
3086 OSRF_BUFFER_ADD_CHAR(sql_buf, ' ');
3087 OSRF_BUFFER_ADD(sql_buf, join_clause);
3091 osrfLogDebug(OSRF_LOG_MARK, "%s pre-predicate SQL = %s",
3092 MODULENAME, OSRF_BUFFER_C_STR(sql_buf));
3094 buffer_add(sql_buf, " WHERE ");
3096 char* pred = searchWHERE( search_hash, meta, AND_OP_JOIN, ctx );
3098 osrfAppSessionStatus(
3100 OSRF_STATUS_INTERNALSERVERERROR,
3101 "osrfMethodException",
3103 "Severe query error -- see error log for more details"
3105 buffer_free(sql_buf);
3106 if(defaultselhash) jsonObjectFree(defaultselhash);
3109 buffer_add(sql_buf, pred);
3114 char* string = NULL;
3115 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "order_by" )) ){
3117 growing_buffer* order_buf = buffer_init(128);
3120 jsonIterator* class_itr = jsonNewIterator( _tmp );
3121 while ( (snode = jsonIteratorNext( class_itr )) ) {
3123 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
3126 if ( snode->type == JSON_HASH ) {
3128 jsonIterator* order_itr = jsonNewIterator( snode );
3129 while ( (onode = jsonIteratorNext( order_itr )) ) {
3131 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
3134 char* direction = NULL;
3135 if ( onode->type == JSON_HASH ) {
3136 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
3137 string = searchFieldTransform(
3139 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
3143 growing_buffer* field_buf = buffer_init(16);
3144 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
3145 string = buffer_release(field_buf);
3148 if ( (_tmp = jsonObjectGetKeyConst( onode, "direction" )) ) {
3149 direction = jsonObjectToSimpleString(_tmp);
3150 if (!strncasecmp(direction, "d", 1)) {
3152 direction = " DESC";
3160 string = strdup(order_itr->key);
3161 direction = jsonObjectToSimpleString(onode);
3162 if (!strncasecmp(direction, "d", 1)) {
3164 direction = " DESC";
3174 buffer_add(order_buf, ", ");
3177 buffer_add(order_buf, string);
3181 buffer_add(order_buf, direction);
3186 jsonIteratorFree(order_itr);
3189 string = jsonObjectToSimpleString(snode);
3190 buffer_add(order_buf, string);
3197 jsonIteratorFree(class_itr);
3199 string = buffer_release(order_buf);
3201 if (strlen(string)) {
3202 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
3203 OSRF_BUFFER_ADD( sql_buf, string );
3209 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "limit" )) ){
3210 string = jsonObjectToSimpleString(_tmp);
3219 _tmp = jsonObjectGetKeyConst( order_hash, "offset" );
3221 string = jsonObjectToSimpleString(_tmp);
3231 if (defaultselhash) jsonObjectFree(defaultselhash);
3233 OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
3234 return buffer_release(sql_buf);
3237 int doJSONSearch ( osrfMethodContext* ctx ) {
3238 if(osrfMethodVerifyContext( ctx )) {
3239 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
3243 osrfLogDebug(OSRF_LOG_MARK, "Recieved query request");
3248 dbhandle = writehandle;
3250 jsonObject* hash = jsonObjectGetIndex(ctx->params, 0);
3254 if ( obj_is_true( jsonObjectGetKey( hash, "distinct" ) ) )
3255 flags |= SELECT_DISTINCT;
3257 if ( obj_is_true( jsonObjectGetKey( hash, "no_i18n" ) ) )
3258 flags |= DISABLE_I18N;
3260 osrfLogDebug(OSRF_LOG_MARK, "Building SQL ...");
3263 jsonObjectGetKey( hash, "select" ),
3264 jsonObjectGetKey( hash, "from" ),
3265 jsonObjectGetKey( hash, "where" ),
3266 jsonObjectGetKey( hash, "having" ),
3267 jsonObjectGetKey( hash, "order_by" ),
3268 jsonObjectGetKey( hash, "limit" ),
3269 jsonObjectGetKey( hash, "offset" ),
3278 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3279 dbi_result result = dbi_conn_query(dbhandle, sql);
3282 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3284 if (dbi_result_first_row(result)) {
3285 /* JSONify the result */
3286 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3289 jsonObject* return_val = oilsMakeJSONFromResult( result );
3290 osrfAppRespond( ctx, return_val );
3291 jsonObjectFree( return_val );
3292 } while (dbi_result_next_row(result));
3295 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
3298 osrfAppRespondComplete( ctx, NULL );
3300 /* clean up the query */
3301 dbi_result_free(result);
3305 osrfLogError(OSRF_LOG_MARK, "%s: Error with query [%s]", MODULENAME, sql);
3306 osrfAppSessionStatus(
3308 OSRF_STATUS_INTERNALSERVERERROR,
3309 "osrfMethodException",
3311 "Severe query error -- see error log for more details"
3319 static jsonObject* doFieldmapperSearch ( osrfMethodContext* ctx, osrfHash* meta,
3320 const jsonObject* params, int* err ) {
3323 dbhandle = writehandle;
3325 osrfHash* links = osrfHashGet(meta, "links");
3326 osrfHash* fields = osrfHashGet(meta, "fields");
3327 char* core_class = osrfHashGet(meta, "classname");
3328 char* pkey = osrfHashGet(meta, "primarykey");
3330 const jsonObject* _tmp;
3332 jsonObject* search_hash = jsonObjectGetIndex(params, 0);
3333 jsonObject* order_hash = jsonObjectGetIndex(params, 1);
3335 char* sql = buildSELECT( search_hash, order_hash, meta, ctx );
3337 osrfLogDebug(OSRF_LOG_MARK, "Problem building query, returning NULL");
3342 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3344 dbi_result result = dbi_conn_query(dbhandle, sql);
3345 if( NULL == result ) {
3346 osrfLogError(OSRF_LOG_MARK, "%s: Error retrieving %s with query [%s]",
3347 MODULENAME, osrfHashGet(meta, "fieldmapper"), sql);
3348 osrfAppSessionStatus(
3350 OSRF_STATUS_INTERNALSERVERERROR,
3351 "osrfMethodException",
3353 "Severe query error -- see error log for more details"
3360 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3363 jsonObject* res_list = jsonNewObjectType(JSON_ARRAY);
3364 osrfHash* dedup = osrfNewHash();
3366 if (dbi_result_first_row(result)) {
3367 /* JSONify the result */
3368 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3370 obj = oilsMakeFieldmapperFromResult( result, meta );
3371 char* pkey_val = oilsFMGetString( obj, pkey );
3372 if ( osrfHashGet( dedup, pkey_val ) ) {
3373 jsonObjectFree(obj);
3376 osrfHashSet( dedup, pkey_val, pkey_val );
3377 jsonObjectPush(res_list, obj);
3379 } while (dbi_result_next_row(result));
3381 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s",
3385 osrfHashFree(dedup);
3386 /* clean up the query */
3387 dbi_result_free(result);
3390 if (res_list->size && order_hash) {
3391 _tmp = jsonObjectGetKeyConst( order_hash, "flesh" );
3393 int x = (int)jsonObjectGetNumber(_tmp);
3394 if (x == -1 || x > max_flesh_depth) x = max_flesh_depth;
3396 const jsonObject* temp_blob;
3397 if ((temp_blob = jsonObjectGetKeyConst( order_hash, "flesh_fields" )) && x > 0) {
3399 jsonObject* flesh_blob = jsonObjectClone( temp_blob );
3400 const jsonObject* flesh_fields = jsonObjectGetKeyConst( flesh_blob, core_class );
3402 osrfStringArray* link_fields = NULL;
3405 if (flesh_fields->size == 1) {
3406 char* _t = jsonObjectToSimpleString( jsonObjectGetIndex( flesh_fields, 0 ) );
3407 if (!strcmp(_t,"*")) link_fields = osrfHashKeys( links );
3413 link_fields = osrfNewStringArray(1);
3414 jsonIterator* _i = jsonNewIterator( flesh_fields );
3415 while ((_f = jsonIteratorNext( _i ))) {
3416 osrfStringArrayAdd( link_fields, jsonObjectToSimpleString( _f ) );
3418 jsonIteratorFree(_i);
3423 jsonIterator* itr = jsonNewIterator( res_list );
3424 while ((cur = jsonIteratorNext( itr ))) {
3429 while ( (link_field = osrfStringArrayGetString(link_fields, i++)) ) {
3431 osrfLogDebug(OSRF_LOG_MARK, "Starting to flesh %s", link_field);
3433 osrfHash* kid_link = osrfHashGet(links, link_field);
3434 if (!kid_link) continue;
3436 osrfHash* field = osrfHashGet(fields, link_field);
3437 if (!field) continue;
3439 osrfHash* value_field = field;
3441 osrfHash* kid_idl = osrfHashGet(oilsIDL(), osrfHashGet(kid_link, "class"));
3442 if (!kid_idl) continue;
3444 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3445 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3448 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) { // might_have
3449 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3452 osrfStringArray* link_map = osrfHashGet( kid_link, "map" );
3454 if (link_map->size > 0) {
3455 jsonObject* _kid_key = jsonNewObjectType(JSON_ARRAY);
3458 jsonNewObject( osrfStringArrayGetString( link_map, 0 ) )
3463 osrfHashGet(kid_link, "class"),
3470 "Link field: %s, remote class: %s, fkey: %s, reltype: %s",
3471 osrfHashGet(kid_link, "field"),
3472 osrfHashGet(kid_link, "class"),
3473 osrfHashGet(kid_link, "key"),
3474 osrfHashGet(kid_link, "reltype")
3477 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
3478 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // search hash
3479 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // order/flesh hash
3481 osrfLogDebug(OSRF_LOG_MARK, "Creating dummy params object...");
3484 jsonObjectToSimpleString(
3487 atoi( osrfHashGet(value_field, "array_position") )
3492 osrfLogDebug(OSRF_LOG_MARK, "Nothing to search for!");
3497 jsonObjectGetIndex(fake_params, 0),
3498 osrfHashGet(kid_link, "key"),
3499 jsonNewObject( search_key )
3506 jsonObjectGetIndex(fake_params, 1),
3508 jsonNewNumberObject( (double)(x - 1 + link_map->size) )
3512 jsonObjectSetKey( jsonObjectGetIndex(fake_params, 1), "flesh_fields", jsonObjectClone(flesh_blob) );
3514 if (jsonObjectGetKeyConst(order_hash, "order_by")) {
3516 jsonObjectGetIndex(fake_params, 1),
3518 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "order_by"))
3522 if (jsonObjectGetKeyConst(order_hash, "select")) {
3524 jsonObjectGetIndex(fake_params, 1),
3526 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "select"))
3530 jsonObject* kids = doFieldmapperSearch(ctx, kid_idl, fake_params, err);
3533 jsonObjectFree( fake_params );
3534 osrfStringArrayFree(link_fields);
3535 jsonIteratorFree(itr);
3536 jsonObjectFree(res_list);
3537 jsonObjectFree(flesh_blob);
3541 osrfLogDebug(OSRF_LOG_MARK, "Search for %s return %d linked objects", osrfHashGet(kid_link, "class"), kids->size);
3543 jsonObject* X = NULL;
3544 if ( link_map->size > 0 && kids->size > 0 ) {
3546 kids = jsonNewObjectType(JSON_ARRAY);
3548 jsonObject* _k_node;
3549 jsonIterator* _k = jsonNewIterator( X );
3550 while ((_k_node = jsonIteratorNext( _k ))) {
3556 (unsigned long)atoi(
3562 osrfHashGet(kid_link, "class")
3566 osrfStringArrayGetString( link_map, 0 )
3575 jsonIteratorFree(_k);
3578 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_a" )) || !(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) {
3579 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3582 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3583 jsonObjectClone( jsonObjectGetIndex(kids, 0) )
3587 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3588 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3591 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3592 jsonObjectClone( kids )
3597 jsonObjectFree(kids);
3601 jsonObjectFree( kids );
3602 jsonObjectFree( fake_params );
3604 osrfLogDebug(OSRF_LOG_MARK, "Fleshing of %s complete", osrfHashGet(kid_link, "field"));
3605 osrfLogDebug(OSRF_LOG_MARK, "%s", jsonObjectToJSON(cur));
3609 jsonObjectFree( flesh_blob );
3610 osrfStringArrayFree(link_fields);
3611 jsonIteratorFree(itr);
3620 static jsonObject* doUpdate(osrfMethodContext* ctx, int* err ) {
3622 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3624 jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
3626 jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
3629 if (!verifyObjectClass(ctx, target)) {
3634 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3635 osrfAppSessionStatus(
3637 OSRF_STATUS_BADREQUEST,
3638 "osrfMethodException",
3640 "No active transaction -- required for UPDATE"
3646 // The following test is harmless but redundant. If a class is
3647 // readonly, we don't register an update method for it.
3648 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
3649 osrfAppSessionStatus(
3651 OSRF_STATUS_BADREQUEST,
3652 "osrfMethodException",
3654 "Cannot UPDATE readonly class"
3660 dbhandle = writehandle;
3662 char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
3664 // Set the last_xact_id
3665 int index = oilsIDL_ntop( target->classname, "last_xact_id" );
3667 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
3668 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
3671 char* pkey = osrfHashGet(meta, "primarykey");
3672 osrfHash* fields = osrfHashGet(meta, "fields");
3674 char* id = oilsFMGetString( target, pkey );
3678 "%s updating %s object with %s = %s",
3680 osrfHashGet(meta, "fieldmapper"),
3685 growing_buffer* sql = buffer_init(128);
3686 buffer_fadd(sql,"UPDATE %s SET", osrfHashGet(meta, "tablename"));
3691 osrfStringArray* field_list = osrfHashKeys( fields );
3692 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
3694 osrfHash* field = osrfHashGet( fields, field_name );
3696 if(!( strcmp( field_name, pkey ) )) continue;
3697 if( str_is_true( osrfHashGet(osrfHashGet(fields,field_name), "virtual") ) )
3700 const jsonObject* field_object = oilsFMGetObject( target, field_name );
3703 if (field_object && field_object->classname) {
3704 value = oilsFMGetString(
3706 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
3709 value = jsonObjectToSimpleString( field_object );
3712 osrfLogDebug( OSRF_LOG_MARK, "Updating %s object with %s = %s", osrfHashGet(meta, "fieldmapper"), field_name, value);
3714 if (!field_object || field_object->type == JSON_NULL) {
3715 if ( !(!( strcmp( osrfHashGet(meta, "classname"), "au" ) ) && !( strcmp( field_name, "passwd" ) )) ) { // arg at the special case!
3716 if (first) first = 0;
3717 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3718 buffer_fadd( sql, " %s = NULL", field_name );
3721 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
3722 if (first) first = 0;
3723 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3725 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
3726 buffer_fadd( sql, " %s = %ld", field_name, atol(value) );
3727 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
3728 buffer_fadd( sql, " %s = %f", field_name, atof(value) );
3731 osrfLogDebug( OSRF_LOG_MARK, "%s is of type %s", field_name, osrfHashGet(field, "datatype"));
3734 if ( dbi_conn_quote_string(dbhandle, &value) ) {
3735 if (first) first = 0;
3736 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3737 buffer_fadd( sql, " %s = %s", field_name, value );
3740 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
3741 osrfAppSessionStatus(
3743 OSRF_STATUS_INTERNALSERVERERROR,
3744 "osrfMethodException",
3746 "Error quoting string -- please see the error log for more details"
3760 jsonObject* obj = jsonNewObject(id);
3762 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
3763 dbi_conn_quote_string(dbhandle, &id);
3765 buffer_fadd( sql, " WHERE %s = %s;", pkey, id );
3767 char* query = buffer_release(sql);
3768 osrfLogDebug(OSRF_LOG_MARK, "%s: Update SQL [%s]", MODULENAME, query);
3770 dbi_result result = dbi_conn_query(dbhandle, query);
3774 jsonObjectFree(obj);
3775 obj = jsonNewObject(NULL);
3778 "%s ERROR updating %s object with %s = %s",
3780 osrfHashGet(meta, "fieldmapper"),
3791 static jsonObject* doDelete(osrfMethodContext* ctx, int* err ) {
3793 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3795 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3796 osrfAppSessionStatus(
3798 OSRF_STATUS_BADREQUEST,
3799 "osrfMethodException",
3801 "No active transaction -- required for DELETE"
3807 // The following test is harmless but redundant. If a class is
3808 // readonly, we don't register a delete method for it.
3809 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
3810 osrfAppSessionStatus(
3812 OSRF_STATUS_BADREQUEST,
3813 "osrfMethodException",
3815 "Cannot DELETE readonly class"
3821 dbhandle = writehandle;
3825 char* pkey = osrfHashGet(meta, "primarykey");
3833 if (jsonObjectGetIndex(ctx->params, _obj_pos)->classname) {
3834 if (!verifyObjectClass(ctx, jsonObjectGetIndex( ctx->params, _obj_pos ))) {
3839 id = oilsFMGetString( jsonObjectGetIndex(ctx->params, _obj_pos), pkey );
3842 if (!verifyObjectPCRUD( ctx, NULL )) {
3847 id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, _obj_pos));
3852 "%s deleting %s object with %s = %s",
3854 osrfHashGet(meta, "fieldmapper"),
3859 obj = jsonNewObject(id);
3861 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
3862 dbi_conn_quote_string(writehandle, &id);
3864 dbi_result result = dbi_conn_queryf(writehandle, "DELETE FROM %s WHERE %s = %s;", osrfHashGet(meta, "tablename"), pkey, id);
3867 jsonObjectFree(obj);
3868 obj = jsonNewObject(NULL);
3871 "%s ERROR deleting %s object with %s = %s",
3873 osrfHashGet(meta, "fieldmapper"),
3886 static jsonObject* oilsMakeFieldmapperFromResult( dbi_result result, osrfHash* meta) {
3887 if(!(result && meta)) return jsonNULL;
3889 jsonObject* object = jsonNewObject(NULL);
3890 jsonObjectSetClass(object, osrfHashGet(meta, "classname"));
3892 osrfHash* fields = osrfHashGet(meta, "fields");
3894 osrfLogInternal(OSRF_LOG_MARK, "Setting object class to %s ", object->classname);
3898 char dt_string[256];
3902 int columnIndex = 1;
3904 unsigned short type;
3905 const char* columnName;
3907 /* cycle through the column list */
3908 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
3910 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
3912 fmIndex = -1; // reset the position
3914 /* determine the field type and storage attributes */
3915 type = dbi_result_get_field_type(result, columnName);
3916 attr = dbi_result_get_field_attribs(result, columnName);
3918 /* fetch the fieldmapper index */
3919 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
3921 if ( str_is_true( osrfHashGet(_f, "virtual") ) )
3924 const char* pos = (char*)osrfHashGet(_f, "array_position");
3925 if ( !pos ) continue;
3927 fmIndex = atoi( pos );
3928 osrfLogInternal(OSRF_LOG_MARK, "... Found column at position [%s]...", pos);
3933 if (dbi_result_field_is_null(result, columnName)) {
3934 jsonObjectSetIndex( object, fmIndex, jsonNewObject(NULL) );
3939 case DBI_TYPE_INTEGER :
3941 if( attr & DBI_INTEGER_SIZE8 )
3942 jsonObjectSetIndex( object, fmIndex,
3943 jsonNewNumberObject(dbi_result_get_longlong(result, columnName)));
3945 jsonObjectSetIndex( object, fmIndex,
3946 jsonNewNumberObject(dbi_result_get_int(result, columnName)));
3950 case DBI_TYPE_DECIMAL :
3951 jsonObjectSetIndex( object, fmIndex,
3952 jsonNewNumberObject(dbi_result_get_double(result, columnName)));
3955 case DBI_TYPE_STRING :
3961 jsonNewObject( dbi_result_get_string(result, columnName) )
3966 case DBI_TYPE_DATETIME :
3968 memset(dt_string, '\0', sizeof(dt_string));
3969 memset(&gmdt, '\0', sizeof(gmdt));
3971 _tmp_dt = dbi_result_get_datetime(result, columnName);
3974 if (!(attr & DBI_DATETIME_DATE)) {
3975 gmtime_r( &_tmp_dt, &gmdt );
3976 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
3977 } else if (!(attr & DBI_DATETIME_TIME)) {
3978 localtime_r( &_tmp_dt, &gmdt );
3979 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
3981 localtime_r( &_tmp_dt, &gmdt );
3982 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
3985 jsonObjectSetIndex( object, fmIndex, jsonNewObject(dt_string) );
3989 case DBI_TYPE_BINARY :
3990 osrfLogError( OSRF_LOG_MARK,
3991 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
3999 static jsonObject* oilsMakeJSONFromResult( dbi_result result ) {
4000 if(!result) return jsonNULL;
4002 jsonObject* object = jsonNewObject(NULL);
4005 char dt_string[256];
4009 int columnIndex = 1;
4011 unsigned short type;
4012 const char* columnName;
4014 /* cycle through the column list */
4015 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
4017 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
4019 fmIndex = -1; // reset the position
4021 /* determine the field type and storage attributes */
4022 type = dbi_result_get_field_type(result, columnName);
4023 attr = dbi_result_get_field_attribs(result, columnName);
4025 if (dbi_result_field_is_null(result, columnName)) {
4026 jsonObjectSetKey( object, columnName, jsonNewObject(NULL) );
4031 case DBI_TYPE_INTEGER :
4033 if( attr & DBI_INTEGER_SIZE8 )
4034 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_longlong(result, columnName)) );
4036 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_int(result, columnName)) );
4039 case DBI_TYPE_DECIMAL :
4040 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_double(result, columnName)) );
4043 case DBI_TYPE_STRING :
4044 jsonObjectSetKey( object, columnName, jsonNewObject(dbi_result_get_string(result, columnName)) );
4047 case DBI_TYPE_DATETIME :
4049 memset(dt_string, '\0', sizeof(dt_string));
4050 memset(&gmdt, '\0', sizeof(gmdt));
4052 _tmp_dt = dbi_result_get_datetime(result, columnName);
4055 if (!(attr & DBI_DATETIME_DATE)) {
4056 gmtime_r( &_tmp_dt, &gmdt );
4057 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
4058 } else if (!(attr & DBI_DATETIME_TIME)) {
4059 localtime_r( &_tmp_dt, &gmdt );
4060 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
4062 localtime_r( &_tmp_dt, &gmdt );
4063 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
4066 jsonObjectSetKey( object, columnName, jsonNewObject(dt_string) );
4069 case DBI_TYPE_BINARY :
4070 osrfLogError( OSRF_LOG_MARK,
4071 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
4079 // Interpret a string as true or false
4080 static int str_is_true( const char* str ) {
4081 if( NULL == str || strcasecmp( str, "true" ) )
4087 // Interpret a jsonObject as true or false
4088 static int obj_is_true( const jsonObject* obj ) {
4091 else switch( obj->type )
4099 if( strcasecmp( obj->value.s, "true" ) )
4103 case JSON_NUMBER : // Support 1/0 for perl's sake
4104 if( jsonObjectGetNumber( obj ) == 1.0 )