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( selhash->type != JSON_HASH ) {
2470 const char* json_type;
2471 switch ( selhash->type )
2474 json_type = "JSON_ARRAY";
2477 json_type = "JSON_STRING";
2480 json_type = "JSON_NUMBER";
2483 json_type = "JSON_NULL";
2486 json_type = "JSON_BOOL";
2489 json_type = "(unrecognized)";
2494 "%s: Expected JSON_HASH for SELECT clause; found %s",
2500 osrfAppSessionStatus(
2502 OSRF_STATUS_INTERNALSERVERERROR,
2503 "osrfMethodException",
2505 "Malformed SELECT clause in JSON query"
2509 } else if ( (tmp_const = jsonObjectGetKeyConst( selhash, core_class )) && tmp_const->type == JSON_STRING ) {
2510 char* _x = jsonObjectToSimpleString( tmp_const );
2511 if (!strncmp( "*", _x, 1 )) {
2512 jsonObjectRemoveKey( selhash, core_class );
2513 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2519 growing_buffer* sql_buf = buffer_init(128);
2521 // temp buffer for the SELECT list
2522 growing_buffer* select_buf = buffer_init(128);
2523 growing_buffer* order_buf = buffer_init(128);
2524 growing_buffer* group_buf = buffer_init(128);
2525 growing_buffer* having_buf = buffer_init(128);
2527 // Build a select list
2528 if(from_function) // From a function we select everything
2529 OSRF_BUFFER_ADD_CHAR( select_buf, '*' );
2532 // If we need to build a default list, prepare to do so
2533 jsonObject* _tmp = jsonObjectGetKey( selhash, core_class );
2534 if ( _tmp && !_tmp->size ) {
2536 osrfHash* core_fields = osrfHashGet( core_meta, "fields" );
2538 osrfHashIterator* field_itr = osrfNewHashIterator( core_fields );
2539 osrfHash* field_def;
2540 while( ( field_def = osrfHashIteratorNext( field_itr ) ) ) {
2541 if( ! str_is_true( osrfHashGet( field_def, "virtual" ) ) ) {
2542 // This field is not virtual, so add it to the list
2543 jsonObjectPush( _tmp, jsonNewObject( osrfHashIteratorKey( field_itr ) ) );
2546 osrfHashIteratorFree( field_itr );
2549 // Now build the actual select list
2551 jsonObject* is_agg = jsonObjectFindPath(selhash, "//aggregate");
2554 jsonIterator* selclass_itr = jsonNewIterator( selhash );
2555 while ( (selclass = jsonIteratorNext( selclass_itr )) ) { // For each class
2557 // round trip through the idl, just to be safe
2558 const char* cname = selclass_itr->key;
2559 osrfHash* idlClass = osrfHashGet( oilsIDL(), cname );
2561 // No such class. Skip it.
2564 // Make sure the target relation is in the join tree.
2566 // At this point join_hash is a step down from the join_hash we
2567 // received as a parameter. If the original was a JSON_STRING,
2568 // then json_hash is now NULL. If the original was a JSON_HASH,
2569 // then json_hash is now the first (and only) entry in it,
2570 // denoting the core class. We've already excluded the
2571 // possibility that the original was a JSON_ARRAY, because in
2572 // that case from_function would be non-NULL, and we wouldn't
2575 if ( strcmp( core_class, cname )) {
2577 // There's only one class in the FROM clause,
2578 // and this isn't it. Skip it.
2581 if (join_hash->type == JSON_STRING) {
2582 string = jsonObjectToSimpleString(join_hash);
2583 int different = strcmp( string, cname );
2586 // There's only one class in the FROM clause,
2587 // and this isn't it. Skip it.
2590 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", cname);
2591 unsigned long size = found->size;
2592 jsonObjectFree( found );
2594 // No such class anywhere in the join tree. Skip it.
2599 // Look up some attributes of the current class, so that we
2600 // don't have to look them up again for each field
2601 osrfHash* class_field_set = osrfHashGet( idlClass, "fields" );
2602 char* class_pkey = osrfHashGet( idlClass, "primarykey" );
2603 char* class_tname = osrfHashGet( idlClass, "tablename" );
2605 // stitch together the column list ...
2606 jsonIterator* select_itr = jsonNewIterator( selclass );
2607 while ( (selfield = jsonIteratorNext( select_itr )) ) { // for each SELECT column
2609 // If we need a separator comma, add one
2613 OSRF_BUFFER_ADD_CHAR( select_buf, ',' );
2616 // ... if it's a string, just toss it on the pile
2617 if (selfield->type == JSON_STRING) {
2619 // again, just to be safe
2620 const char* col_name = selfield->value.s;
2621 osrfHash* field_def = osrfHashGet( class_field_set, col_name );
2622 if ( !field_def ) continue; // No such field in current class; skip it
2626 if (flags & DISABLE_I18N)
2629 i18n = osrfHashGet(field_def, "i18n");
2631 if( str_is_true( i18n ) ) {
2632 buffer_fadd( select_buf,
2633 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2634 class_tname, cname, col_name, class_pkey, cname, class_pkey, locale, col_name );
2636 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2639 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2642 // ... but it could be an object, in which case we check for a Field Transform
2645 char* col_name = jsonObjectToSimpleString( jsonObjectGetKeyConst( selfield, "column" ) );
2647 // Get the field definition from the IDL
2648 osrfHash* field_def = osrfHashGet( class_field_set, col_name );
2649 if ( !field_def ) continue; // No such field defined in IDL. Skip it.
2651 // Decide what to use as a column alias
2653 if ((tmp_const = jsonObjectGetKeyConst( selfield, "alias" ))) {
2654 _alias = jsonObjectToSimpleString( tmp_const );
2655 } else { // Use field name as the alias
2659 if (jsonObjectGetKeyConst( selfield, "transform" )) {
2660 char* transform_str = searchFieldTransform(cname, field_def, selfield);
2661 buffer_fadd(select_buf, " %s AS \"%s\"", transform_str, _alias);
2662 free(transform_str);
2667 if (flags & DISABLE_I18N)
2670 i18n = osrfHashGet(field_def, "i18n");
2672 if( str_is_true( i18n ) ) {
2673 buffer_fadd( select_buf,
2674 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2675 class_tname, cname, col_name, class_pkey, cname, class_pkey, locale, _alias);
2677 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, _alias);
2680 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, _alias);
2684 if( _alias != col_name )
2689 if (is_agg->size || (flags & SELECT_DISTINCT)) {
2691 const jsonObject* aggregate_obj = jsonObjectGetKey( selfield, "aggregate" );
2692 if ( ! obj_is_true( aggregate_obj ) ) {
2696 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
2699 buffer_fadd(group_buf, " %d", sel_pos);
2701 } else if (is_agg = jsonObjectGetKey( selfield, "having" )) {
2705 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
2708 _column = searchFieldTransform(cname, field, selfield);
2709 OSRF_BUFFER_ADD_CHAR(group_buf, ' ');
2710 OSRF_BUFFER_ADD(group_buf, _column);
2711 _column = searchFieldTransform(cname, field, selfield);
2717 } // end while -- iterating across SELECT columns
2719 jsonIteratorFree(select_itr);
2720 } // end while -- iterating across classes
2722 jsonIteratorFree(selclass_itr);
2724 if (is_agg) jsonObjectFree(is_agg);
2728 char* col_list = buffer_release(select_buf);
2730 if (from_function) table = searchValueTransform(join_hash);
2731 else table = getSourceDefinition(core_meta);
2735 osrfAppSessionStatus(
2737 OSRF_STATUS_INTERNALSERVERERROR,
2738 "osrfMethodException",
2740 "Unable to identify table for core class"
2743 buffer_free( sql_buf );
2744 buffer_free( order_buf );
2745 buffer_free( group_buf );
2746 buffer_free( having_buf );
2747 if( defaultselhash ) jsonObjectFree( defaultselhash );
2752 // Put it all together
2753 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\" ", col_list, table, core_class );
2757 if (!from_function) {
2758 // Now, walk the join tree and add that clause
2760 char* join_clause = searchJOIN( join_hash, core_meta );
2762 buffer_add(sql_buf, join_clause);
2766 osrfAppSessionStatus(
2768 OSRF_STATUS_INTERNALSERVERERROR,
2769 "osrfMethodException",
2771 "Unable to construct JOIN clause(s)"
2773 buffer_free( sql_buf );
2774 buffer_free( order_buf );
2775 buffer_free( group_buf );
2776 buffer_free( having_buf );
2777 if( defaultselhash ) jsonObjectFree( defaultselhash );
2783 // Build a WHERE clause, if there is one
2784 if ( search_hash ) {
2785 buffer_add(sql_buf, " WHERE ");
2787 // and it's on the WHERE clause
2788 char* pred = searchWHERE( search_hash, core_meta, AND_OP_JOIN, ctx );
2791 buffer_add(sql_buf, pred);
2795 osrfAppSessionStatus(
2797 OSRF_STATUS_INTERNALSERVERERROR,
2798 "osrfMethodException",
2800 "Severe query error in WHERE predicate -- see error log for more details"
2804 buffer_free(having_buf);
2805 buffer_free(group_buf);
2806 buffer_free(order_buf);
2807 buffer_free(sql_buf);
2808 if (defaultselhash) jsonObjectFree(defaultselhash);
2813 // Build a HAVING clause, if there is one
2814 if ( having_hash ) {
2815 buffer_add(sql_buf, " HAVING ");
2817 // and it's on the the WHERE clause
2818 char* pred = searchWHERE( having_hash, core_meta, AND_OP_JOIN, ctx );
2821 buffer_add(sql_buf, pred);
2825 osrfAppSessionStatus(
2827 OSRF_STATUS_INTERNALSERVERERROR,
2828 "osrfMethodException",
2830 "Severe query error in HAVING predicate -- see error log for more details"
2834 buffer_free(having_buf);
2835 buffer_free(group_buf);
2836 buffer_free(order_buf);
2837 buffer_free(sql_buf);
2838 if (defaultselhash) jsonObjectFree(defaultselhash);
2843 // Build an ORDER BY clause, if there is one
2845 jsonIterator* class_itr = jsonNewIterator( order_hash );
2846 while ( (snode = jsonIteratorNext( class_itr )) ) {
2848 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
2851 if ( snode->type == JSON_HASH ) {
2853 jsonIterator* order_itr = jsonNewIterator( snode );
2854 while ( (onode = jsonIteratorNext( order_itr )) ) {
2856 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
2859 char* direction = NULL;
2860 if ( onode->type == JSON_HASH ) {
2861 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
2862 string = searchFieldTransform(
2864 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
2868 growing_buffer* field_buf = buffer_init(16);
2869 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
2870 string = buffer_release(field_buf);
2873 if ( (tmp_const = jsonObjectGetKeyConst( onode, "direction" )) ) {
2874 direction = jsonObjectToSimpleString(tmp_const);
2875 if (!strncasecmp(direction, "d", 1)) {
2877 direction = " DESC";
2885 string = strdup(order_itr->key);
2886 direction = jsonObjectToSimpleString(onode);
2887 if (!strncasecmp(direction, "d", 1)) {
2889 direction = " DESC";
2899 buffer_add(order_buf, ", ");
2902 buffer_add(order_buf, string);
2906 buffer_add(order_buf, direction);
2910 // jsonIteratorFree(order_itr);
2912 } else if ( snode->type == JSON_ARRAY ) {
2914 jsonIterator* order_itr = jsonNewIterator( snode );
2915 while ( (onode = jsonIteratorNext( order_itr )) ) {
2917 char* _f = jsonObjectToSimpleString( onode );
2919 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, _f))
2925 buffer_add(order_buf, ", ");
2928 buffer_add(order_buf, _f);
2932 // jsonIteratorFree(order_itr);
2935 // IT'S THE OOOOOOOOOOOLD STYLE!
2937 osrfLogError(OSRF_LOG_MARK, "%s: Possible SQL injection attempt; direct order by is not allowed", MODULENAME);
2939 osrfAppSessionStatus(
2941 OSRF_STATUS_INTERNALSERVERERROR,
2942 "osrfMethodException",
2944 "Severe query error -- see error log for more details"
2949 buffer_free(having_buf);
2950 buffer_free(group_buf);
2951 buffer_free(order_buf);
2952 buffer_free(sql_buf);
2953 if (defaultselhash) jsonObjectFree(defaultselhash);
2954 jsonIteratorFree(class_itr);
2959 // jsonIteratorFree(class_itr);
2963 string = buffer_release(group_buf);
2966 OSRF_BUFFER_ADD( sql_buf, " GROUP BY " );
2967 OSRF_BUFFER_ADD( sql_buf, string );
2972 string = buffer_release(having_buf);
2975 OSRF_BUFFER_ADD( sql_buf, " HAVING " );
2976 OSRF_BUFFER_ADD( sql_buf, string );
2981 string = buffer_release(order_buf);
2984 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
2985 OSRF_BUFFER_ADD( sql_buf, string );
2991 string = jsonObjectToSimpleString(limit);
2992 buffer_fadd( sql_buf, " LIMIT %d", atoi(string) );
2997 string = jsonObjectToSimpleString(offset);
2998 buffer_fadd( sql_buf, " OFFSET %d", atoi(string) );
3002 if (!(flags & SUBSELECT)) OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
3005 if (defaultselhash) jsonObjectFree(defaultselhash);
3007 return buffer_release(sql_buf);
3011 static char* buildSELECT ( jsonObject* search_hash, jsonObject* order_hash, osrfHash* meta, osrfMethodContext* ctx ) {
3013 const char* locale = osrf_message_get_last_locale();
3015 osrfHash* fields = osrfHashGet(meta, "fields");
3016 char* core_class = osrfHashGet(meta, "classname");
3018 const jsonObject* join_hash = jsonObjectGetKeyConst( order_hash, "join" );
3020 jsonObject* node = NULL;
3021 jsonObject* snode = NULL;
3022 jsonObject* onode = NULL;
3023 const jsonObject* _tmp = NULL;
3024 jsonObject* selhash = NULL;
3025 jsonObject* defaultselhash = NULL;
3027 growing_buffer* sql_buf = buffer_init(128);
3028 growing_buffer* select_buf = buffer_init(128);
3030 if ( !(selhash = jsonObjectGetKey( order_hash, "select" )) ) {
3031 defaultselhash = jsonNewObjectType(JSON_HASH);
3032 selhash = defaultselhash;
3035 if ( !jsonObjectGetKeyConst(selhash,core_class) ) {
3036 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
3037 jsonObject* flist = jsonObjectGetKey( selhash, core_class );
3042 osrfStringArray* keys = osrfHashKeys( fields );
3043 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
3044 if( ! str_is_true( osrfHashGet( osrfHashGet( fields, field ), "virtual" ) ) )
3045 jsonObjectPush( flist, jsonNewObject( field ) );
3047 osrfStringArrayFree(keys);
3051 jsonIterator* class_itr = jsonNewIterator( selhash );
3052 while ( (snode = jsonIteratorNext( class_itr )) ) {
3054 char* cname = class_itr->key;
3055 osrfHash* idlClass = osrfHashGet( oilsIDL(), cname );
3056 if (!idlClass) continue;
3058 if (strcmp(core_class,class_itr->key)) {
3059 if (!join_hash) continue;
3061 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", class_itr->key);
3063 jsonObjectFree(found);
3067 jsonObjectFree(found);
3070 jsonIterator* select_itr = jsonNewIterator( snode );
3071 while ( (node = jsonIteratorNext( select_itr )) ) {
3072 char* item_str = jsonObjectToSimpleString(node);
3073 osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), item_str );
3075 char* fname = osrfHashGet(field, "name");
3077 if (!field) continue;
3082 OSRF_BUFFER_ADD_CHAR(select_buf, ',');
3087 const jsonObject* no_i18n_obj = jsonObjectGetKey( order_hash, "no_i18n" );
3088 if ( obj_is_true( no_i18n_obj ) ) // Suppress internationalization?
3091 i18n = osrfHashGet(field, "i18n");
3093 if( str_is_true( i18n ) ) {
3094 char* pkey = osrfHashGet(idlClass, "primarykey");
3095 char* tname = osrfHashGet(idlClass, "tablename");
3097 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);
3099 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
3102 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
3106 jsonIteratorFree(select_itr);
3109 jsonIteratorFree(class_itr);
3111 char* col_list = buffer_release(select_buf);
3112 char* table = getSourceDefinition(meta);
3114 table = strdup( "(null)" );
3116 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\"", col_list, table, core_class );
3121 char* join_clause = searchJOIN( join_hash, meta );
3122 OSRF_BUFFER_ADD_CHAR(sql_buf, ' ');
3123 OSRF_BUFFER_ADD(sql_buf, join_clause);
3127 osrfLogDebug(OSRF_LOG_MARK, "%s pre-predicate SQL = %s",
3128 MODULENAME, OSRF_BUFFER_C_STR(sql_buf));
3130 buffer_add(sql_buf, " WHERE ");
3132 char* pred = searchWHERE( search_hash, meta, AND_OP_JOIN, ctx );
3134 osrfAppSessionStatus(
3136 OSRF_STATUS_INTERNALSERVERERROR,
3137 "osrfMethodException",
3139 "Severe query error -- see error log for more details"
3141 buffer_free(sql_buf);
3142 if(defaultselhash) jsonObjectFree(defaultselhash);
3145 buffer_add(sql_buf, pred);
3150 char* string = NULL;
3151 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "order_by" )) ){
3153 growing_buffer* order_buf = buffer_init(128);
3156 jsonIterator* class_itr = jsonNewIterator( _tmp );
3157 while ( (snode = jsonIteratorNext( class_itr )) ) {
3159 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
3162 if ( snode->type == JSON_HASH ) {
3164 jsonIterator* order_itr = jsonNewIterator( snode );
3165 while ( (onode = jsonIteratorNext( order_itr )) ) {
3167 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
3170 char* direction = NULL;
3171 if ( onode->type == JSON_HASH ) {
3172 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
3173 string = searchFieldTransform(
3175 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
3179 growing_buffer* field_buf = buffer_init(16);
3180 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
3181 string = buffer_release(field_buf);
3184 if ( (_tmp = jsonObjectGetKeyConst( onode, "direction" )) ) {
3185 direction = jsonObjectToSimpleString(_tmp);
3186 if (!strncasecmp(direction, "d", 1)) {
3188 direction = " DESC";
3196 string = strdup(order_itr->key);
3197 direction = jsonObjectToSimpleString(onode);
3198 if (!strncasecmp(direction, "d", 1)) {
3200 direction = " DESC";
3210 buffer_add(order_buf, ", ");
3213 buffer_add(order_buf, string);
3217 buffer_add(order_buf, direction);
3222 jsonIteratorFree(order_itr);
3225 string = jsonObjectToSimpleString(snode);
3226 buffer_add(order_buf, string);
3233 jsonIteratorFree(class_itr);
3235 string = buffer_release(order_buf);
3238 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
3239 OSRF_BUFFER_ADD( sql_buf, string );
3245 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "limit" )) ){
3246 string = jsonObjectToSimpleString(_tmp);
3255 _tmp = jsonObjectGetKeyConst( order_hash, "offset" );
3257 string = jsonObjectToSimpleString(_tmp);
3267 if (defaultselhash) jsonObjectFree(defaultselhash);
3269 OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
3270 return buffer_release(sql_buf);
3273 int doJSONSearch ( osrfMethodContext* ctx ) {
3274 if(osrfMethodVerifyContext( ctx )) {
3275 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
3279 osrfLogDebug(OSRF_LOG_MARK, "Recieved query request");
3284 dbhandle = writehandle;
3286 jsonObject* hash = jsonObjectGetIndex(ctx->params, 0);
3290 if ( obj_is_true( jsonObjectGetKey( hash, "distinct" ) ) )
3291 flags |= SELECT_DISTINCT;
3293 if ( obj_is_true( jsonObjectGetKey( hash, "no_i18n" ) ) )
3294 flags |= DISABLE_I18N;
3296 osrfLogDebug(OSRF_LOG_MARK, "Building SQL ...");
3299 jsonObjectGetKey( hash, "select" ),
3300 jsonObjectGetKey( hash, "from" ),
3301 jsonObjectGetKey( hash, "where" ),
3302 jsonObjectGetKey( hash, "having" ),
3303 jsonObjectGetKey( hash, "order_by" ),
3304 jsonObjectGetKey( hash, "limit" ),
3305 jsonObjectGetKey( hash, "offset" ),
3314 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3315 dbi_result result = dbi_conn_query(dbhandle, sql);
3318 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3320 if (dbi_result_first_row(result)) {
3321 /* JSONify the result */
3322 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3325 jsonObject* return_val = oilsMakeJSONFromResult( result );
3326 osrfAppRespond( ctx, return_val );
3327 jsonObjectFree( return_val );
3328 } while (dbi_result_next_row(result));
3331 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
3334 osrfAppRespondComplete( ctx, NULL );
3336 /* clean up the query */
3337 dbi_result_free(result);
3341 osrfLogError(OSRF_LOG_MARK, "%s: Error with query [%s]", MODULENAME, sql);
3342 osrfAppSessionStatus(
3344 OSRF_STATUS_INTERNALSERVERERROR,
3345 "osrfMethodException",
3347 "Severe query error -- see error log for more details"
3355 static jsonObject* doFieldmapperSearch ( osrfMethodContext* ctx, osrfHash* meta,
3356 const jsonObject* params, int* err ) {
3359 dbhandle = writehandle;
3361 osrfHash* links = osrfHashGet(meta, "links");
3362 osrfHash* fields = osrfHashGet(meta, "fields");
3363 char* core_class = osrfHashGet(meta, "classname");
3364 char* pkey = osrfHashGet(meta, "primarykey");
3366 const jsonObject* _tmp;
3368 jsonObject* search_hash = jsonObjectGetIndex(params, 0);
3369 jsonObject* order_hash = jsonObjectGetIndex(params, 1);
3371 char* sql = buildSELECT( search_hash, order_hash, meta, ctx );
3373 osrfLogDebug(OSRF_LOG_MARK, "Problem building query, returning NULL");
3378 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3380 dbi_result result = dbi_conn_query(dbhandle, sql);
3381 if( NULL == result ) {
3382 osrfLogError(OSRF_LOG_MARK, "%s: Error retrieving %s with query [%s]",
3383 MODULENAME, osrfHashGet(meta, "fieldmapper"), sql);
3384 osrfAppSessionStatus(
3386 OSRF_STATUS_INTERNALSERVERERROR,
3387 "osrfMethodException",
3389 "Severe query error -- see error log for more details"
3396 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3399 jsonObject* res_list = jsonNewObjectType(JSON_ARRAY);
3400 osrfHash* dedup = osrfNewHash();
3402 if (dbi_result_first_row(result)) {
3403 /* JSONify the result */
3404 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3406 obj = oilsMakeFieldmapperFromResult( result, meta );
3407 char* pkey_val = oilsFMGetString( obj, pkey );
3408 if ( osrfHashGet( dedup, pkey_val ) ) {
3409 jsonObjectFree(obj);
3412 osrfHashSet( dedup, pkey_val, pkey_val );
3413 jsonObjectPush(res_list, obj);
3415 } while (dbi_result_next_row(result));
3417 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s",
3421 osrfHashFree(dedup);
3422 /* clean up the query */
3423 dbi_result_free(result);
3426 if (res_list->size && order_hash) {
3427 _tmp = jsonObjectGetKeyConst( order_hash, "flesh" );
3429 int x = (int)jsonObjectGetNumber(_tmp);
3430 if (x == -1 || x > max_flesh_depth) x = max_flesh_depth;
3432 const jsonObject* temp_blob;
3433 if ((temp_blob = jsonObjectGetKeyConst( order_hash, "flesh_fields" )) && x > 0) {
3435 jsonObject* flesh_blob = jsonObjectClone( temp_blob );
3436 const jsonObject* flesh_fields = jsonObjectGetKeyConst( flesh_blob, core_class );
3438 osrfStringArray* link_fields = NULL;
3441 if (flesh_fields->size == 1) {
3442 char* _t = jsonObjectToSimpleString( jsonObjectGetIndex( flesh_fields, 0 ) );
3443 if (!strcmp(_t,"*")) link_fields = osrfHashKeys( links );
3449 link_fields = osrfNewStringArray(1);
3450 jsonIterator* _i = jsonNewIterator( flesh_fields );
3451 while ((_f = jsonIteratorNext( _i ))) {
3452 osrfStringArrayAdd( link_fields, jsonObjectToSimpleString( _f ) );
3454 jsonIteratorFree(_i);
3459 jsonIterator* itr = jsonNewIterator( res_list );
3460 while ((cur = jsonIteratorNext( itr ))) {
3465 while ( (link_field = osrfStringArrayGetString(link_fields, i++)) ) {
3467 osrfLogDebug(OSRF_LOG_MARK, "Starting to flesh %s", link_field);
3469 osrfHash* kid_link = osrfHashGet(links, link_field);
3470 if (!kid_link) continue;
3472 osrfHash* field = osrfHashGet(fields, link_field);
3473 if (!field) continue;
3475 osrfHash* value_field = field;
3477 osrfHash* kid_idl = osrfHashGet(oilsIDL(), osrfHashGet(kid_link, "class"));
3478 if (!kid_idl) continue;
3480 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3481 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3484 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) { // might_have
3485 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3488 osrfStringArray* link_map = osrfHashGet( kid_link, "map" );
3490 if (link_map->size > 0) {
3491 jsonObject* _kid_key = jsonNewObjectType(JSON_ARRAY);
3494 jsonNewObject( osrfStringArrayGetString( link_map, 0 ) )
3499 osrfHashGet(kid_link, "class"),
3506 "Link field: %s, remote class: %s, fkey: %s, reltype: %s",
3507 osrfHashGet(kid_link, "field"),
3508 osrfHashGet(kid_link, "class"),
3509 osrfHashGet(kid_link, "key"),
3510 osrfHashGet(kid_link, "reltype")
3513 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
3514 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // search hash
3515 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // order/flesh hash
3517 osrfLogDebug(OSRF_LOG_MARK, "Creating dummy params object...");
3520 jsonObjectToSimpleString(
3523 atoi( osrfHashGet(value_field, "array_position") )
3528 osrfLogDebug(OSRF_LOG_MARK, "Nothing to search for!");
3533 jsonObjectGetIndex(fake_params, 0),
3534 osrfHashGet(kid_link, "key"),
3535 jsonNewObject( search_key )
3542 jsonObjectGetIndex(fake_params, 1),
3544 jsonNewNumberObject( (double)(x - 1 + link_map->size) )
3548 jsonObjectSetKey( jsonObjectGetIndex(fake_params, 1), "flesh_fields", jsonObjectClone(flesh_blob) );
3550 if (jsonObjectGetKeyConst(order_hash, "order_by")) {
3552 jsonObjectGetIndex(fake_params, 1),
3554 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "order_by"))
3558 if (jsonObjectGetKeyConst(order_hash, "select")) {
3560 jsonObjectGetIndex(fake_params, 1),
3562 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "select"))
3566 jsonObject* kids = doFieldmapperSearch(ctx, kid_idl, fake_params, err);
3569 jsonObjectFree( fake_params );
3570 osrfStringArrayFree(link_fields);
3571 jsonIteratorFree(itr);
3572 jsonObjectFree(res_list);
3573 jsonObjectFree(flesh_blob);
3577 osrfLogDebug(OSRF_LOG_MARK, "Search for %s return %d linked objects", osrfHashGet(kid_link, "class"), kids->size);
3579 jsonObject* X = NULL;
3580 if ( link_map->size > 0 && kids->size > 0 ) {
3582 kids = jsonNewObjectType(JSON_ARRAY);
3584 jsonObject* _k_node;
3585 jsonIterator* _k = jsonNewIterator( X );
3586 while ((_k_node = jsonIteratorNext( _k ))) {
3592 (unsigned long)atoi(
3598 osrfHashGet(kid_link, "class")
3602 osrfStringArrayGetString( link_map, 0 )
3611 jsonIteratorFree(_k);
3614 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_a" )) || !(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) {
3615 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3618 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3619 jsonObjectClone( jsonObjectGetIndex(kids, 0) )
3623 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3624 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3627 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3628 jsonObjectClone( kids )
3633 jsonObjectFree(kids);
3637 jsonObjectFree( kids );
3638 jsonObjectFree( fake_params );
3640 osrfLogDebug(OSRF_LOG_MARK, "Fleshing of %s complete", osrfHashGet(kid_link, "field"));
3641 osrfLogDebug(OSRF_LOG_MARK, "%s", jsonObjectToJSON(cur));
3645 jsonObjectFree( flesh_blob );
3646 osrfStringArrayFree(link_fields);
3647 jsonIteratorFree(itr);
3656 static jsonObject* doUpdate(osrfMethodContext* ctx, int* err ) {
3658 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3660 jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
3662 jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
3665 if (!verifyObjectClass(ctx, target)) {
3670 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3671 osrfAppSessionStatus(
3673 OSRF_STATUS_BADREQUEST,
3674 "osrfMethodException",
3676 "No active transaction -- required for UPDATE"
3682 // The following test is harmless but redundant. If a class is
3683 // readonly, we don't register an update method for it.
3684 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
3685 osrfAppSessionStatus(
3687 OSRF_STATUS_BADREQUEST,
3688 "osrfMethodException",
3690 "Cannot UPDATE readonly class"
3696 dbhandle = writehandle;
3698 char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
3700 // Set the last_xact_id
3701 int index = oilsIDL_ntop( target->classname, "last_xact_id" );
3703 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
3704 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
3707 char* pkey = osrfHashGet(meta, "primarykey");
3708 osrfHash* fields = osrfHashGet(meta, "fields");
3710 char* id = oilsFMGetString( target, pkey );
3714 "%s updating %s object with %s = %s",
3716 osrfHashGet(meta, "fieldmapper"),
3721 growing_buffer* sql = buffer_init(128);
3722 buffer_fadd(sql,"UPDATE %s SET", osrfHashGet(meta, "tablename"));
3727 osrfStringArray* field_list = osrfHashKeys( fields );
3728 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
3730 osrfHash* field = osrfHashGet( fields, field_name );
3732 if(!( strcmp( field_name, pkey ) )) continue;
3733 if( str_is_true( osrfHashGet(osrfHashGet(fields,field_name), "virtual") ) )
3736 const jsonObject* field_object = oilsFMGetObject( target, field_name );
3739 if (field_object && field_object->classname) {
3740 value = oilsFMGetString(
3742 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
3745 value = jsonObjectToSimpleString( field_object );
3748 osrfLogDebug( OSRF_LOG_MARK, "Updating %s object with %s = %s", osrfHashGet(meta, "fieldmapper"), field_name, value);
3750 if (!field_object || field_object->type == JSON_NULL) {
3751 if ( !(!( strcmp( osrfHashGet(meta, "classname"), "au" ) ) && !( strcmp( field_name, "passwd" ) )) ) { // arg at the special case!
3752 if (first) first = 0;
3753 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3754 buffer_fadd( sql, " %s = NULL", field_name );
3757 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
3758 if (first) first = 0;
3759 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3761 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
3762 buffer_fadd( sql, " %s = %ld", field_name, atol(value) );
3763 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
3764 buffer_fadd( sql, " %s = %f", field_name, atof(value) );
3767 osrfLogDebug( OSRF_LOG_MARK, "%s is of type %s", field_name, osrfHashGet(field, "datatype"));
3770 if ( dbi_conn_quote_string(dbhandle, &value) ) {
3771 if (first) first = 0;
3772 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3773 buffer_fadd( sql, " %s = %s", field_name, value );
3776 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
3777 osrfAppSessionStatus(
3779 OSRF_STATUS_INTERNALSERVERERROR,
3780 "osrfMethodException",
3782 "Error quoting string -- please see the error log for more details"
3796 jsonObject* obj = jsonNewObject(id);
3798 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
3799 dbi_conn_quote_string(dbhandle, &id);
3801 buffer_fadd( sql, " WHERE %s = %s;", pkey, id );
3803 char* query = buffer_release(sql);
3804 osrfLogDebug(OSRF_LOG_MARK, "%s: Update SQL [%s]", MODULENAME, query);
3806 dbi_result result = dbi_conn_query(dbhandle, query);
3810 jsonObjectFree(obj);
3811 obj = jsonNewObject(NULL);
3814 "%s ERROR updating %s object with %s = %s",
3816 osrfHashGet(meta, "fieldmapper"),
3827 static jsonObject* doDelete(osrfMethodContext* ctx, int* err ) {
3829 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3831 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3832 osrfAppSessionStatus(
3834 OSRF_STATUS_BADREQUEST,
3835 "osrfMethodException",
3837 "No active transaction -- required for DELETE"
3843 // The following test is harmless but redundant. If a class is
3844 // readonly, we don't register a delete method for it.
3845 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
3846 osrfAppSessionStatus(
3848 OSRF_STATUS_BADREQUEST,
3849 "osrfMethodException",
3851 "Cannot DELETE readonly class"
3857 dbhandle = writehandle;
3861 char* pkey = osrfHashGet(meta, "primarykey");
3869 if (jsonObjectGetIndex(ctx->params, _obj_pos)->classname) {
3870 if (!verifyObjectClass(ctx, jsonObjectGetIndex( ctx->params, _obj_pos ))) {
3875 id = oilsFMGetString( jsonObjectGetIndex(ctx->params, _obj_pos), pkey );
3878 if (!verifyObjectPCRUD( ctx, NULL )) {
3883 id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, _obj_pos));
3888 "%s deleting %s object with %s = %s",
3890 osrfHashGet(meta, "fieldmapper"),
3895 obj = jsonNewObject(id);
3897 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
3898 dbi_conn_quote_string(writehandle, &id);
3900 dbi_result result = dbi_conn_queryf(writehandle, "DELETE FROM %s WHERE %s = %s;", osrfHashGet(meta, "tablename"), pkey, id);
3903 jsonObjectFree(obj);
3904 obj = jsonNewObject(NULL);
3907 "%s ERROR deleting %s object with %s = %s",
3909 osrfHashGet(meta, "fieldmapper"),
3922 static jsonObject* oilsMakeFieldmapperFromResult( dbi_result result, osrfHash* meta) {
3923 if(!(result && meta)) return jsonNULL;
3925 jsonObject* object = jsonNewObject(NULL);
3926 jsonObjectSetClass(object, osrfHashGet(meta, "classname"));
3928 osrfHash* fields = osrfHashGet(meta, "fields");
3930 osrfLogInternal(OSRF_LOG_MARK, "Setting object class to %s ", object->classname);
3934 char dt_string[256];
3938 int columnIndex = 1;
3940 unsigned short type;
3941 const char* columnName;
3943 /* cycle through the column list */
3944 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
3946 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
3948 fmIndex = -1; // reset the position
3950 /* determine the field type and storage attributes */
3951 type = dbi_result_get_field_type(result, columnName);
3952 attr = dbi_result_get_field_attribs(result, columnName);
3954 /* fetch the fieldmapper index */
3955 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
3957 if ( str_is_true( osrfHashGet(_f, "virtual") ) )
3960 const char* pos = (char*)osrfHashGet(_f, "array_position");
3961 if ( !pos ) continue;
3963 fmIndex = atoi( pos );
3964 osrfLogInternal(OSRF_LOG_MARK, "... Found column at position [%s]...", pos);
3969 if (dbi_result_field_is_null(result, columnName)) {
3970 jsonObjectSetIndex( object, fmIndex, jsonNewObject(NULL) );
3975 case DBI_TYPE_INTEGER :
3977 if( attr & DBI_INTEGER_SIZE8 )
3978 jsonObjectSetIndex( object, fmIndex,
3979 jsonNewNumberObject(dbi_result_get_longlong(result, columnName)));
3981 jsonObjectSetIndex( object, fmIndex,
3982 jsonNewNumberObject(dbi_result_get_int(result, columnName)));
3986 case DBI_TYPE_DECIMAL :
3987 jsonObjectSetIndex( object, fmIndex,
3988 jsonNewNumberObject(dbi_result_get_double(result, columnName)));
3991 case DBI_TYPE_STRING :
3997 jsonNewObject( dbi_result_get_string(result, columnName) )
4002 case DBI_TYPE_DATETIME :
4004 memset(dt_string, '\0', sizeof(dt_string));
4005 memset(&gmdt, '\0', sizeof(gmdt));
4007 _tmp_dt = dbi_result_get_datetime(result, columnName);
4010 if (!(attr & DBI_DATETIME_DATE)) {
4011 gmtime_r( &_tmp_dt, &gmdt );
4012 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
4013 } else if (!(attr & DBI_DATETIME_TIME)) {
4014 localtime_r( &_tmp_dt, &gmdt );
4015 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
4017 localtime_r( &_tmp_dt, &gmdt );
4018 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
4021 jsonObjectSetIndex( object, fmIndex, jsonNewObject(dt_string) );
4025 case DBI_TYPE_BINARY :
4026 osrfLogError( OSRF_LOG_MARK,
4027 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
4035 static jsonObject* oilsMakeJSONFromResult( dbi_result result ) {
4036 if(!result) return jsonNULL;
4038 jsonObject* object = jsonNewObject(NULL);
4041 char dt_string[256];
4045 int columnIndex = 1;
4047 unsigned short type;
4048 const char* columnName;
4050 /* cycle through the column list */
4051 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
4053 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
4055 fmIndex = -1; // reset the position
4057 /* determine the field type and storage attributes */
4058 type = dbi_result_get_field_type(result, columnName);
4059 attr = dbi_result_get_field_attribs(result, columnName);
4061 if (dbi_result_field_is_null(result, columnName)) {
4062 jsonObjectSetKey( object, columnName, jsonNewObject(NULL) );
4067 case DBI_TYPE_INTEGER :
4069 if( attr & DBI_INTEGER_SIZE8 )
4070 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_longlong(result, columnName)) );
4072 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_int(result, columnName)) );
4075 case DBI_TYPE_DECIMAL :
4076 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_double(result, columnName)) );
4079 case DBI_TYPE_STRING :
4080 jsonObjectSetKey( object, columnName, jsonNewObject(dbi_result_get_string(result, columnName)) );
4083 case DBI_TYPE_DATETIME :
4085 memset(dt_string, '\0', sizeof(dt_string));
4086 memset(&gmdt, '\0', sizeof(gmdt));
4088 _tmp_dt = dbi_result_get_datetime(result, columnName);
4091 if (!(attr & DBI_DATETIME_DATE)) {
4092 gmtime_r( &_tmp_dt, &gmdt );
4093 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
4094 } else if (!(attr & DBI_DATETIME_TIME)) {
4095 localtime_r( &_tmp_dt, &gmdt );
4096 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
4098 localtime_r( &_tmp_dt, &gmdt );
4099 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
4102 jsonObjectSetKey( object, columnName, jsonNewObject(dt_string) );
4105 case DBI_TYPE_BINARY :
4106 osrfLogError( OSRF_LOG_MARK,
4107 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
4115 // Interpret a string as true or false
4116 static int str_is_true( const char* str ) {
4117 if( NULL == str || strcasecmp( str, "true" ) )
4123 // Interpret a jsonObject as true or false
4124 static int obj_is_true( const jsonObject* obj ) {
4127 else switch( obj->type )
4135 if( strcasecmp( obj->value.s, "true" ) )
4139 case JSON_NUMBER : // Support 1/0 for perl's sake
4140 if( jsonObjectGetNumber( obj ) == 1.0 )