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 static 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 growing_buffer* tablebuf = buffer_init(128);
282 tabledef = osrfHashGet(class, "source_definition");
285 buffer_fadd( tablebuf, "(%s)", tabledef );
286 tabledef = buffer_release(tablebuf);
288 tabledef = strdup(tabledef);
295 * Connects to the database
297 int osrfAppChildInit() {
299 osrfLogDebug(OSRF_LOG_MARK, "Attempting to initialize libdbi...");
300 dbi_initialize(NULL);
301 osrfLogDebug(OSRF_LOG_MARK, "... libdbi initialized.");
303 char* driver = osrf_settings_host_value("/apps/%s/app_settings/driver", MODULENAME);
304 char* user = osrf_settings_host_value("/apps/%s/app_settings/database/user", MODULENAME);
305 char* host = osrf_settings_host_value("/apps/%s/app_settings/database/host", MODULENAME);
306 char* port = osrf_settings_host_value("/apps/%s/app_settings/database/port", MODULENAME);
307 char* db = osrf_settings_host_value("/apps/%s/app_settings/database/db", MODULENAME);
308 char* pw = osrf_settings_host_value("/apps/%s/app_settings/database/pw", MODULENAME);
309 char* md = osrf_settings_host_value("/apps/%s/app_settings/max_query_recursion", MODULENAME);
311 osrfLogDebug(OSRF_LOG_MARK, "Attempting to load the database driver [%s]...", driver);
312 writehandle = dbi_conn_new(driver);
315 osrfLogError(OSRF_LOG_MARK, "Error loading database driver [%s]", driver);
318 osrfLogDebug(OSRF_LOG_MARK, "Database driver [%s] seems OK", driver);
320 osrfLogInfo(OSRF_LOG_MARK, "%s connecting to database. host=%s, "
321 "port=%s, user=%s, pw=%s, db=%s", MODULENAME, host, port, user, pw, db );
323 if(host) dbi_conn_set_option(writehandle, "host", host );
324 if(port) dbi_conn_set_option_numeric( writehandle, "port", atoi(port) );
325 if(user) dbi_conn_set_option(writehandle, "username", user);
326 if(pw) dbi_conn_set_option(writehandle, "password", pw );
327 if(db) dbi_conn_set_option(writehandle, "dbname", db );
329 if(md) max_flesh_depth = atoi(md);
330 if(max_flesh_depth < 0) max_flesh_depth = 1;
331 if(max_flesh_depth > 1000) max_flesh_depth = 1000;
340 if (dbi_conn_connect(writehandle) < 0) {
342 if (dbi_conn_connect(writehandle) < 0) {
343 dbi_conn_error(writehandle, &err);
344 osrfLogError( OSRF_LOG_MARK, "Error connecting to database: %s", err);
349 osrfLogInfo(OSRF_LOG_MARK, "%s successfully connected to the database", MODULENAME);
355 osrfStringArray* classes = osrfHashKeys( oilsIDL() );
357 while ( (classname = osrfStringArrayGetString(classes, i++)) ) {
358 osrfHash* class = osrfHashGet( oilsIDL(), classname );
359 osrfHash* fields = osrfHashGet( class, "fields" );
361 if( str_is_true( osrfHashGet(class, "virtual") ) ) {
362 osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
366 char* tabledef = getSourceDefinition(class);
368 growing_buffer* sql_buf = buffer_init(32);
369 buffer_fadd( sql_buf, "SELECT * FROM %s AS x WHERE 1=0;", tabledef );
373 char* sql = buffer_release(sql_buf);
374 osrfLogDebug(OSRF_LOG_MARK, "%s Investigatory SQL = %s", MODULENAME, sql);
376 dbi_result result = dbi_conn_query(writehandle, sql);
382 const char* columnName;
384 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
386 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
388 /* fetch the fieldmapper index */
389 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
391 osrfLogDebug(OSRF_LOG_MARK, "Found [%s] in IDL hash...", (char*)columnName);
393 /* determine the field type and storage attributes */
394 type = dbi_result_get_field_type(result, columnName);
395 attr = dbi_result_get_field_attribs(result, columnName);
399 case DBI_TYPE_INTEGER :
401 if ( !osrfHashGet(_f, "primitive") )
402 osrfHashSet(_f,"number", "primitive");
404 if( attr & DBI_INTEGER_SIZE8 )
405 osrfHashSet(_f,"INT8", "datatype");
407 osrfHashSet(_f,"INT", "datatype");
410 case DBI_TYPE_DECIMAL :
411 if ( !osrfHashGet(_f, "primitive") )
412 osrfHashSet(_f,"number", "primitive");
414 osrfHashSet(_f,"NUMERIC", "datatype");
417 case DBI_TYPE_STRING :
418 if ( !osrfHashGet(_f, "primitive") )
419 osrfHashSet(_f,"string", "primitive");
420 osrfHashSet(_f,"TEXT", "datatype");
423 case DBI_TYPE_DATETIME :
424 if ( !osrfHashGet(_f, "primitive") )
425 osrfHashSet(_f,"string", "primitive");
427 osrfHashSet(_f,"TIMESTAMP", "datatype");
430 case DBI_TYPE_BINARY :
431 if ( !osrfHashGet(_f, "primitive") )
432 osrfHashSet(_f,"string", "primitive");
434 osrfHashSet(_f,"BYTEA", "datatype");
439 "Setting [%s] to primitive [%s] and datatype [%s]...",
441 osrfHashGet(_f, "primitive"),
442 osrfHashGet(_f, "datatype")
446 dbi_result_free(result);
448 osrfLogDebug(OSRF_LOG_MARK, "No data found for class [%s]...", (char*)classname);
452 osrfStringArrayFree(classes);
457 void userDataFree( void* blob ) {
458 osrfHashFree( (osrfHash*)blob );
462 static void sessionDataFree( char* key, void* item ) {
463 if (!(strcmp(key,"xact_id"))) {
465 dbi_conn_query(writehandle, "ROLLBACK;");
472 int beginTransaction ( osrfMethodContext* ctx ) {
473 if(osrfMethodVerifyContext( ctx )) {
474 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
479 jsonObject* user = verifyUserPCRUD( ctx );
480 if (!user) return -1;
481 jsonObjectFree(user);
484 dbi_result result = dbi_conn_query(writehandle, "START TRANSACTION;");
486 osrfLogError(OSRF_LOG_MARK, "%s: Error starting transaction", MODULENAME );
487 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error starting transaction" );
490 jsonObject* ret = jsonNewObject(ctx->session->session_id);
491 osrfAppRespondComplete( ctx, ret );
494 if (!ctx->session->userData) {
495 ctx->session->userData = osrfNewHash();
496 osrfHashSetCallback((osrfHash*)ctx->session->userData, &sessionDataFree);
499 osrfHashSet( (osrfHash*)ctx->session->userData, strdup( ctx->session->session_id ), "xact_id" );
500 ctx->session->userDataFree = &userDataFree;
506 int setSavepoint ( osrfMethodContext* ctx ) {
507 if(osrfMethodVerifyContext( ctx )) {
508 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
515 jsonObject* user = verifyUserPCRUD( ctx );
516 if (!user) return -1;
517 jsonObjectFree(user);
520 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
521 osrfAppSessionStatus(
523 OSRF_STATUS_INTERNALSERVERERROR,
524 "osrfMethodException",
526 "No active transaction -- required for savepoints"
531 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
533 dbi_result result = dbi_conn_queryf(writehandle, "SAVEPOINT \"%s\";", spName);
537 "%s: Error creating savepoint %s in transaction %s",
540 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
542 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error creating savepoint" );
546 jsonObject* ret = jsonNewObject(spName);
547 osrfAppRespondComplete( ctx, ret );
554 int releaseSavepoint ( osrfMethodContext* ctx ) {
555 if(osrfMethodVerifyContext( ctx )) {
556 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
563 jsonObject* user = verifyUserPCRUD( ctx );
564 if (!user) return -1;
565 jsonObjectFree(user);
568 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
569 osrfAppSessionStatus(
571 OSRF_STATUS_INTERNALSERVERERROR,
572 "osrfMethodException",
574 "No active transaction -- required for savepoints"
579 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
581 dbi_result result = dbi_conn_queryf(writehandle, "RELEASE SAVEPOINT \"%s\";", spName);
585 "%s: Error releasing savepoint %s in transaction %s",
588 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
590 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error releasing savepoint" );
594 jsonObject* ret = jsonNewObject(spName);
595 osrfAppRespondComplete( ctx, ret );
602 int rollbackSavepoint ( osrfMethodContext* ctx ) {
603 if(osrfMethodVerifyContext( ctx )) {
604 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
611 jsonObject* user = verifyUserPCRUD( ctx );
612 if (!user) return -1;
613 jsonObjectFree(user);
616 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
617 osrfAppSessionStatus(
619 OSRF_STATUS_INTERNALSERVERERROR,
620 "osrfMethodException",
622 "No active transaction -- required for savepoints"
627 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
629 dbi_result result = dbi_conn_queryf(writehandle, "ROLLBACK TO SAVEPOINT \"%s\";", spName);
633 "%s: Error rolling back savepoint %s in transaction %s",
636 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
638 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back savepoint" );
642 jsonObject* ret = jsonNewObject(spName);
643 osrfAppRespondComplete( ctx, ret );
650 int commitTransaction ( osrfMethodContext* ctx ) {
651 if(osrfMethodVerifyContext( ctx )) {
652 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
657 jsonObject* user = verifyUserPCRUD( ctx );
658 if (!user) return -1;
659 jsonObjectFree(user);
662 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
663 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to commit" );
667 dbi_result result = dbi_conn_query(writehandle, "COMMIT;");
669 osrfLogError(OSRF_LOG_MARK, "%s: Error committing transaction", MODULENAME );
670 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error committing transaction" );
673 osrfHashRemove(ctx->session->userData, "xact_id");
674 jsonObject* ret = jsonNewObject(ctx->session->session_id);
675 osrfAppRespondComplete( ctx, ret );
681 int rollbackTransaction ( osrfMethodContext* ctx ) {
682 if(osrfMethodVerifyContext( ctx )) {
683 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
688 jsonObject* user = verifyUserPCRUD( ctx );
689 if (!user) return -1;
690 jsonObjectFree(user);
693 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
694 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to roll back" );
698 dbi_result result = dbi_conn_query(writehandle, "ROLLBACK;");
700 osrfLogError(OSRF_LOG_MARK, "%s: Error rolling back transaction", MODULENAME );
701 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back transaction" );
704 osrfHashRemove(ctx->session->userData, "xact_id");
705 jsonObject* ret = jsonNewObject(ctx->session->session_id);
706 osrfAppRespondComplete( ctx, ret );
712 int dispatchCRUDMethod ( osrfMethodContext* ctx ) {
713 if(osrfMethodVerifyContext( ctx )) {
714 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
718 osrfHash* meta = (osrfHash*) ctx->method->userData;
719 osrfHash* class_obj = osrfHashGet( meta, "class" );
723 const char* methodtype = osrfHashGet(meta, "methodtype");
724 jsonObject * obj = NULL;
726 if (!strcmp(methodtype, "create")) {
727 obj = doCreate(ctx, &err);
728 osrfAppRespondComplete( ctx, obj );
730 else if (!strcmp(methodtype, "retrieve")) {
731 obj = doRetrieve(ctx, &err);
732 osrfAppRespondComplete( ctx, obj );
734 else if (!strcmp(methodtype, "update")) {
735 obj = doUpdate(ctx, &err);
736 osrfAppRespondComplete( ctx, obj );
738 else if (!strcmp(methodtype, "delete")) {
739 obj = doDelete(ctx, &err);
740 osrfAppRespondComplete( ctx, obj );
742 else if (!strcmp(methodtype, "search")) {
744 jsonObject* _p = jsonObjectClone( ctx->params );
747 _p = jsonParseString("[]");
748 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 1)));
749 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 2)));
752 obj = doFieldmapperSearch(ctx, class_obj, _p, &err);
758 jsonIterator* itr = jsonNewIterator( obj );
759 while ((cur = jsonIteratorNext( itr ))) {
761 if(!verifyObjectPCRUD(ctx, cur)) continue;
763 osrfAppRespond( ctx, cur );
765 jsonIteratorFree(itr);
766 osrfAppRespondComplete( ctx, NULL );
768 } else if (!strcmp(methodtype, "id_list")) {
770 jsonObject* _p = jsonObjectClone( ctx->params );
773 _p = jsonParseString("[]");
774 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 1)));
775 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 2)));
778 if (jsonObjectGetIndex( _p, 1 )) {
779 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "select" );
780 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "no_i18n" );
781 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh" );
782 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh_columns" );
784 jsonObjectSetIndex( _p, 1, jsonNewObjectType(JSON_HASH) );
787 jsonObjectSetKey( jsonObjectGetIndex( _p, 1 ), "no_i18n", jsonNewBoolObject( 1 ) );
790 jsonObjectGetIndex( _p, 1 ),
793 "{ \"%s\":[\"%s\"] }",
794 osrfHashGet( class_obj, "classname" ),
795 osrfHashGet( class_obj, "primarykey" )
799 obj = doFieldmapperSearch(ctx, class_obj, _p, &err);
805 jsonIterator* itr = jsonNewIterator( obj );
806 while ((cur = jsonIteratorNext( itr ))) {
808 if(!verifyObjectPCRUD(ctx, cur)) continue;
812 oilsFMGetObject( cur, osrfHashGet( class_obj, "primarykey" ) )
815 jsonIteratorFree(itr);
816 osrfAppRespondComplete( ctx, NULL );
819 osrfAppRespondComplete( ctx, obj );
827 static int verifyObjectClass ( osrfMethodContext* ctx, const jsonObject* param ) {
830 osrfHash* meta = (osrfHash*) ctx->method->userData;
831 osrfHash* class = osrfHashGet( meta, "class" );
833 if (!param->classname || (strcmp( osrfHashGet(class, "classname"), param->classname ))) {
835 growing_buffer* msg = buffer_init(128);
838 "%s: %s method for type %s was passed a %s",
840 osrfHashGet(meta, "methodtype"),
841 osrfHashGet(class, "classname"),
845 char* m = buffer_release(msg);
846 osrfAppSessionStatus( ctx->session, OSRF_STATUS_BADREQUEST, "osrfMethodException", ctx->request, m );
854 ret = verifyObjectPCRUD( ctx, param );
862 static jsonObject* verifyUserPCRUD( osrfMethodContext* ctx ) {
863 char* auth = jsonObjectToSimpleString( jsonObjectGetIndex( ctx->params, 0 ) );
864 jsonObject* auth_object = jsonNewObject(auth);
865 jsonObject* user = oilsUtilsQuickReq("open-ils.auth","open-ils.auth.session.retrieve", auth_object);
866 jsonObjectFree(auth_object);
868 if (!user->classname || strcmp(user->classname, "au")) {
870 growing_buffer* msg = buffer_init(128);
873 "%s: permacrud received a bad auth token: %s",
878 char* m = buffer_release(msg);
879 osrfAppSessionStatus( ctx->session, OSRF_STATUS_UNAUTHORIZED, "osrfMethodException", ctx->request, m );
882 jsonObjectFree(user);
891 static int verifyObjectPCRUD ( osrfMethodContext* ctx, const jsonObject* obj ) {
893 dbhandle = writehandle;
895 osrfHash* meta = (osrfHash*) ctx->method->userData;
896 osrfHash* class = osrfHashGet( meta, "class" );
897 char* method_type = strdup( osrfHashGet(meta, "methodtype") );
900 if ( ( *method_type == 's' || *method_type == 'i' ) ) {
902 method_type = strdup("retrieve"); // search and id_list are equivelant to retrieve for this
903 } else if ( *method_type == 'u' || *method_type == 'd' ) {
904 fetch = 1; // MUST go to the db for the object for update and delete
907 osrfHash* pcrud = osrfHashGet( osrfHashGet(class, "permacrud"), method_type );
911 // No permacrud for this method type on this class
913 growing_buffer* msg = buffer_init(128);
916 "%s: %s on class %s has no permacrud IDL entry",
918 osrfHashGet(meta, "methodtype"),
919 osrfHashGet(class, "classname")
922 char* m = buffer_release(msg);
923 osrfAppSessionStatus( ctx->session, OSRF_STATUS_FORBIDDEN, "osrfMethodException", ctx->request, m );
930 jsonObject* user = verifyUserPCRUD( ctx );
933 int userid = atoi( oilsFMGetString( user, "id" ) );
934 jsonObjectFree(user);
936 osrfStringArray* permission = osrfHashGet(pcrud, "permission");
937 osrfStringArray* local_context = osrfHashGet(pcrud, "local_context");
938 osrfHash* foreign_context = osrfHashGet(pcrud, "foreign_context");
940 osrfStringArray* context_org_array = osrfNewStringArray(1);
943 char* pkey_value = NULL;
944 if ( str_is_true( osrfHashGet(pcrud, "global_required") ) ) {
945 osrfLogDebug( OSRF_LOG_MARK, "global-level permissions required, fetching top of the org tree" );
947 // check for perm at top of org tree
948 jsonObject* _tmp_params = jsonParseString("[{\"parent_ou\":null}]");
949 jsonObject* _list = doFieldmapperSearch(ctx, osrfHashGet( oilsIDL(), "aou" ), _tmp_params, &err);
951 jsonObject* _tree_top = jsonObjectGetIndex(_list, 0);
954 jsonObjectFree(_tmp_params);
955 jsonObjectFree(_list);
957 growing_buffer* msg = buffer_init(128);
958 OSRF_BUFFER_ADD( msg, MODULENAME );
959 OSRF_BUFFER_ADD( msg,
960 ": Internal error, could not find the top of the org tree (parent_ou = NULL)" );
962 char* m = buffer_release(msg);
963 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, m );
969 osrfStringArrayAdd( context_org_array, oilsFMGetString( _tree_top, "id" ) );
970 osrfLogDebug( OSRF_LOG_MARK, "top of the org tree is %s", osrfStringArrayGetString(context_org_array, 0) );
972 jsonObjectFree(_tmp_params);
973 jsonObjectFree(_list);
976 osrfLogDebug( OSRF_LOG_MARK, "global-level permissions not required, fetching context org ids" );
977 char* pkey = osrfHashGet(class, "primarykey");
978 jsonObject *param = NULL;
980 if (obj->classname) {
981 pkey_value = oilsFMGetString( obj, pkey );
982 if (!fetch) param = jsonObjectClone(obj);
983 osrfLogDebug( OSRF_LOG_MARK, "Object supplied, using primary key value of %s", pkey_value );
985 pkey_value = jsonObjectToSimpleString( obj );
987 osrfLogDebug( OSRF_LOG_MARK, "Object not supplied, using primary key value of %s and retrieving from the database", pkey_value );
991 jsonObject* _tmp_params = jsonParseStringFmt("[{\"%s\":\"%s\"}]", pkey, pkey_value);
992 jsonObject* _list = doFieldmapperSearch(
999 param = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1001 jsonObjectFree(_tmp_params);
1002 jsonObjectFree(_list);
1006 osrfLogDebug( OSRF_LOG_MARK, "Object not found in the database with primary key %s of %s", pkey, pkey_value );
1008 growing_buffer* msg = buffer_init(128);
1011 "%s: no object found with primary key %s of %s",
1017 char* m = buffer_release(msg);
1018 osrfAppSessionStatus(
1020 OSRF_STATUS_INTERNALSERVERERROR,
1021 "osrfMethodException",
1027 if (pkey_value) free(pkey_value);
1032 if (local_context->size > 0) {
1033 osrfLogDebug( OSRF_LOG_MARK, "%d class-local context field(s) specified", local_context->size);
1035 char* lcontext = NULL;
1036 while ( (lcontext = osrfStringArrayGetString(local_context, i++)) ) {
1037 osrfStringArrayAdd( context_org_array, oilsFMGetString( param, lcontext ) );
1040 "adding class-local field %s (value: %s) to the context org list",
1042 osrfStringArrayGetString(context_org_array, context_org_array->size - 1)
1047 osrfStringArray* class_list;
1049 if (foreign_context) {
1050 class_list = osrfHashKeys( foreign_context );
1051 osrfLogDebug( OSRF_LOG_MARK, "%d foreign context classes(s) specified", class_list->size);
1053 if (class_list->size > 0) {
1056 char* class_name = NULL;
1057 while ( (class_name = osrfStringArrayGetString(class_list, i++)) ) {
1058 osrfHash* fcontext = osrfHashGet(foreign_context, class_name);
1062 "%d foreign context fields(s) specified for class %s",
1063 ((osrfStringArray*)osrfHashGet(fcontext,"context"))->size,
1067 char* foreign_pkey = osrfHashGet(fcontext, "field");
1068 char* foreign_pkey_value = oilsFMGetString(param, osrfHashGet(fcontext, "fkey"));
1070 jsonObject* _tmp_params = jsonParseStringFmt(
1071 "[{\"%s\":\"%s\"}]",
1076 jsonObject* _list = doFieldmapperSearch(
1078 osrfHashGet( oilsIDL(), class_name ),
1083 jsonObject* _fparam = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1084 jsonObjectFree(_tmp_params);
1085 jsonObjectFree(_list);
1087 osrfStringArray* jump_list = osrfHashGet(fcontext, "jump");
1089 if (_fparam && jump_list) {
1092 while ( (flink = osrfStringArrayGetString(jump_list, k++)) && _fparam ) {
1093 free(foreign_pkey_value);
1095 osrfHash* foreign_link_hash = oilsIDLFindPath( "/%s/links/%s", _fparam->classname, flink );
1097 foreign_pkey_value = oilsFMGetString(_fparam, flink);
1098 foreign_pkey = osrfHashGet( foreign_link_hash, "key" );
1100 _tmp_params = jsonParseStringFmt(
1101 "[{\"%s\":\"%s\"}]",
1106 _list = doFieldmapperSearch(
1108 osrfHashGet( oilsIDL(), osrfHashGet( foreign_link_hash, "class" ) ),
1113 _fparam = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1114 jsonObjectFree(_tmp_params);
1115 jsonObjectFree(_list);
1122 growing_buffer* msg = buffer_init(128);
1125 "%s: no object found with primary key %s of %s",
1131 char* m = buffer_release(msg);
1132 osrfAppSessionStatus(
1134 OSRF_STATUS_INTERNALSERVERERROR,
1135 "osrfMethodException",
1141 osrfStringArrayFree(class_list);
1142 free(foreign_pkey_value);
1143 jsonObjectFree(param);
1148 free(foreign_pkey_value);
1151 char* foreign_field = NULL;
1152 while ( (foreign_field = osrfStringArrayGetString(osrfHashGet(fcontext,"context"), j++)) ) {
1153 osrfStringArrayAdd( context_org_array, oilsFMGetString( _fparam, foreign_field ) );
1156 "adding foreign class %s field %s (value: %s) to the context org list",
1159 osrfStringArrayGetString(context_org_array, context_org_array->size - 1)
1163 jsonObjectFree(_fparam);
1166 osrfStringArrayFree(class_list);
1170 jsonObjectFree(param);
1173 char* context_org = NULL;
1177 if (permission->size == 0) {
1178 osrfLogDebug( OSRF_LOG_MARK, "No permission specified for this action, passing through" );
1183 while ( (perm = osrfStringArrayGetString(permission, i++)) ) {
1185 while ( (context_org = osrfStringArrayGetString(context_org_array, j++)) ) {
1191 "Checking object permission [%s] for user %d on object %s (class %s) at org %d",
1195 osrfHashGet(class, "classname"),
1199 result = dbi_conn_queryf(
1201 "SELECT permission.usr_has_object_perm(%d, '%s', '%s', '%s', %d) AS has_perm;",
1204 osrfHashGet(class, "classname"),
1212 "Recieved a result for object permission [%s] for user %d on object %s (class %s) at org %d",
1216 osrfHashGet(class, "classname"),
1220 if (dbi_result_first_row(result)) {
1221 jsonObject* return_val = oilsMakeJSONFromResult( result );
1222 char* has_perm = jsonObjectToSimpleString( jsonObjectGetKeyConst(return_val, "has_perm") );
1226 "Status of object permission [%s] for user %d on object %s (class %s) at org %d is %s",
1230 osrfHashGet(class, "classname"),
1235 if ( *has_perm == 't' ) OK = 1;
1237 jsonObjectFree(return_val);
1240 dbi_result_free(result);
1245 osrfLogDebug( OSRF_LOG_MARK, "Checking non-object permission [%s] for user %d at org %d", perm, userid, atoi(context_org) );
1246 result = dbi_conn_queryf(
1248 "SELECT permission.usr_has_perm(%d, '%s', %d) AS has_perm;",
1255 osrfLogDebug( OSRF_LOG_MARK, "Recieved a result for permission [%s] for user %d at org %d", perm, userid, atoi(context_org) );
1256 if (dbi_result_first_row(result)) {
1257 jsonObject* return_val = oilsMakeJSONFromResult( result );
1258 char* has_perm = jsonObjectToSimpleString( jsonObjectGetKeyConst(return_val, "has_perm") );
1259 osrfLogDebug( OSRF_LOG_MARK, "Status of permission [%s] for user %d at org %d is [%s]", perm, userid, atoi(context_org), has_perm );
1260 if ( *has_perm == 't' ) OK = 1;
1262 jsonObjectFree(return_val);
1265 dbi_result_free(result);
1273 if (pkey_value) free(pkey_value);
1274 osrfStringArrayFree(context_org_array);
1281 static jsonObject* doCreate(osrfMethodContext* ctx, int* err ) {
1283 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1285 jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
1286 jsonObject* options = jsonObjectGetIndex( ctx->params, 2 );
1288 jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
1289 jsonObject* options = jsonObjectGetIndex( ctx->params, 1 );
1292 if (!verifyObjectClass(ctx, target)) {
1297 osrfLogDebug( OSRF_LOG_MARK, "Object seems to be of the correct type" );
1299 if (!ctx->session || !ctx->session->userData || !osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
1300 osrfLogError( OSRF_LOG_MARK, "No active transaction -- required for CREATE" );
1302 osrfAppSessionStatus(
1304 OSRF_STATUS_BADREQUEST,
1305 "osrfMethodException",
1307 "No active transaction -- required for CREATE"
1313 // The following test is harmless but redundant. If a class is
1314 // readonly, we don't register a create method for it.
1315 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
1316 osrfAppSessionStatus(
1318 OSRF_STATUS_BADREQUEST,
1319 "osrfMethodException",
1321 "Cannot INSERT readonly class"
1328 char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
1330 // Set the last_xact_id
1331 int index = oilsIDL_ntop( target->classname, "last_xact_id" );
1333 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
1334 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
1337 osrfLogDebug( OSRF_LOG_MARK, "There is a transaction running..." );
1339 dbhandle = writehandle;
1341 osrfHash* fields = osrfHashGet(meta, "fields");
1342 char* pkey = osrfHashGet(meta, "primarykey");
1343 char* seq = osrfHashGet(meta, "sequence");
1345 growing_buffer* table_buf = buffer_init(128);
1346 growing_buffer* col_buf = buffer_init(128);
1347 growing_buffer* val_buf = buffer_init(128);
1349 OSRF_BUFFER_ADD(table_buf, "INSERT INTO ");
1350 OSRF_BUFFER_ADD(table_buf, osrfHashGet(meta, "tablename"));
1351 OSRF_BUFFER_ADD_CHAR( col_buf, '(' );
1352 buffer_add(val_buf,"VALUES (");
1358 osrfStringArray* field_list = osrfHashKeys( fields );
1359 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
1361 osrfHash* field = osrfHashGet( fields, field_name );
1363 if( str_is_true( osrfHashGet( field, "virtual" ) ) )
1366 const jsonObject* field_object = oilsFMGetObject( target, field_name );
1369 if (field_object && field_object->classname) {
1370 value = oilsFMGetString(
1372 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
1375 value = jsonObjectToSimpleString( field_object );
1382 OSRF_BUFFER_ADD_CHAR( col_buf, ',' );
1383 OSRF_BUFFER_ADD_CHAR( val_buf, ',' );
1386 buffer_add(col_buf, field_name);
1388 if (!field_object || field_object->type == JSON_NULL) {
1389 buffer_add( val_buf, "DEFAULT" );
1391 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1392 if ( !strcmp(osrfHashGet(field, "datatype"), "INT8") ) {
1393 buffer_fadd( val_buf, "%lld", atoll(value) );
1395 } else if ( !strcmp(osrfHashGet(field, "datatype"), "INT") ) {
1396 buffer_fadd( val_buf, "%d", atoi(value) );
1398 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
1399 buffer_fadd( val_buf, "%f", atof(value) );
1402 if ( dbi_conn_quote_string(writehandle, &value) ) {
1403 OSRF_BUFFER_ADD( val_buf, value );
1406 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
1407 osrfAppSessionStatus(
1409 OSRF_STATUS_INTERNALSERVERERROR,
1410 "osrfMethodException",
1412 "Error quoting string -- please see the error log for more details"
1415 buffer_free(table_buf);
1416 buffer_free(col_buf);
1417 buffer_free(val_buf);
1428 OSRF_BUFFER_ADD_CHAR( col_buf, ')' );
1429 OSRF_BUFFER_ADD_CHAR( val_buf, ')' );
1431 char* table_str = buffer_release(table_buf);
1432 char* col_str = buffer_release(col_buf);
1433 char* val_str = buffer_release(val_buf);
1434 growing_buffer* sql = buffer_init(128);
1435 buffer_fadd( sql, "%s %s %s;", table_str, col_str, val_str );
1440 char* query = buffer_release(sql);
1442 osrfLogDebug(OSRF_LOG_MARK, "%s: Insert SQL [%s]", MODULENAME, query);
1445 dbi_result result = dbi_conn_query(writehandle, query);
1447 jsonObject* obj = NULL;
1450 obj = jsonNewObject(NULL);
1453 "%s ERROR inserting %s object using query [%s]",
1455 osrfHashGet(meta, "fieldmapper"),
1458 osrfAppSessionStatus(
1460 OSRF_STATUS_INTERNALSERVERERROR,
1461 "osrfMethodException",
1463 "INSERT error -- please see the error log for more details"
1468 char* id = oilsFMGetString(target, pkey);
1470 unsigned long long new_id = dbi_conn_sequence_last(writehandle, seq);
1471 growing_buffer* _id = buffer_init(10);
1472 buffer_fadd(_id, "%lld", new_id);
1473 id = buffer_release(_id);
1476 // Find quietness specification, if present
1477 char* quiet_str = NULL;
1479 const jsonObject* quiet_obj = jsonObjectGetKeyConst( options, "quiet" );
1481 quiet_str = jsonObjectToSimpleString( quiet_obj );
1484 if( str_is_true( quiet_str ) ) { // if quietness is specified
1485 obj = jsonNewObject(id);
1489 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
1490 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH));
1493 jsonObjectGetIndex(fake_params, 0),
1498 jsonObject* list = doFieldmapperSearch( ctx,meta, fake_params, err);
1501 jsonObjectFree( fake_params );
1504 obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
1507 jsonObjectFree( list );
1508 jsonObjectFree( fake_params );
1511 if(quiet_str) free(quiet_str);
1522 static jsonObject* doRetrieve(osrfMethodContext* ctx, int* err ) {
1532 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1534 char* id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, id_pos));
1535 jsonObject* order_hash = jsonObjectGetIndex(ctx->params, order_pos);
1539 "%s retrieving %s object with primary key value of %s",
1541 osrfHashGet(meta, "fieldmapper"),
1546 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
1547 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH));
1550 jsonObjectGetIndex(fake_params, 0),
1551 osrfHashGet(meta, "primarykey"),
1552 jsonObjectClone(jsonObjectGetIndex(ctx->params, id_pos))
1556 if (order_hash) jsonObjectPush(fake_params, jsonObjectClone(order_hash) );
1558 jsonObject* list = doFieldmapperSearch( ctx,meta, fake_params, err);
1561 jsonObjectFree( fake_params );
1565 jsonObject* obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
1567 jsonObjectFree( list );
1568 jsonObjectFree( fake_params );
1571 if(!verifyObjectPCRUD(ctx, obj)) {
1572 jsonObjectFree(obj);
1575 growing_buffer* msg = buffer_init(128);
1576 OSRF_BUFFER_ADD( msg, MODULENAME );
1577 OSRF_BUFFER_ADD( msg, ": Insufficient permissions to retrieve object" );
1579 char* m = buffer_release(msg);
1580 osrfAppSessionStatus( ctx->session, OSRF_STATUS_NOTALLOWED, "osrfMethodException", ctx->request, m );
1591 static char* jsonNumberToDBString ( osrfHash* field, const jsonObject* value ) {
1592 growing_buffer* val_buf = buffer_init(32);
1594 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
1595 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%ld", (long)jsonObjectGetNumber(value) );
1597 char* val_str = jsonObjectToSimpleString(value);
1598 buffer_fadd( val_buf, "%ld", atol(val_str) );
1602 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
1603 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%f", jsonObjectGetNumber(value) );
1605 char* val_str = jsonObjectToSimpleString(value);
1606 buffer_fadd( val_buf, "%f", atof(val_str) );
1611 return buffer_release(val_buf);
1614 static char* searchINPredicate (const char* class, osrfHash* field,
1615 jsonObject* node, const char* op, osrfMethodContext* ctx ) {
1616 growing_buffer* sql_buf = buffer_init(32);
1622 osrfHashGet(field, "name")
1626 buffer_add(sql_buf, "IN (");
1627 } else if (!(strcasecmp(op,"not in"))) {
1628 buffer_add(sql_buf, "NOT IN (");
1630 buffer_add(sql_buf, "IN (");
1633 if (node->type == JSON_HASH) {
1634 // subquery predicate
1635 char* subpred = SELECT(
1637 jsonObjectGetKey( node, "select" ),
1638 jsonObjectGetKey( node, "from" ),
1639 jsonObjectGetKey( node, "where" ),
1640 jsonObjectGetKey( node, "having" ),
1641 jsonObjectGetKey( node, "order_by" ),
1642 jsonObjectGetKey( node, "limit" ),
1643 jsonObjectGetKey( node, "offset" ),
1647 buffer_add(sql_buf, subpred);
1650 } else if (node->type == JSON_ARRAY) {
1651 // litteral value list
1652 int in_item_index = 0;
1653 int in_item_first = 1;
1654 jsonObject* in_item;
1655 while ( (in_item = jsonObjectGetIndex(node, in_item_index++)) ) {
1660 buffer_add(sql_buf, ", ");
1662 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1663 char* val = jsonNumberToDBString( field, in_item );
1664 OSRF_BUFFER_ADD( sql_buf, val );
1668 char* key_string = jsonObjectToSimpleString(in_item);
1669 if ( dbi_conn_quote_string(dbhandle, &key_string) ) {
1670 OSRF_BUFFER_ADD( sql_buf, key_string );
1673 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, key_string);
1675 buffer_free(sql_buf);
1682 OSRF_BUFFER_ADD_CHAR( sql_buf, ')' );
1684 return buffer_release(sql_buf);
1687 // Receive a JSON_ARRAY representing a function call. The first
1688 // entry in the array is the function name. The rest are parameters.
1689 static char* searchValueTransform( const jsonObject* array ) {
1690 growing_buffer* sql_buf = buffer_init(32);
1693 jsonObject* func_item;
1695 // Get the function name
1696 if( array->size > 0 ) {
1697 func_item = jsonObjectGetIndex( array, 0 );
1698 val = jsonObjectToSimpleString( func_item );
1699 OSRF_BUFFER_ADD( sql_buf, val );
1700 OSRF_BUFFER_ADD( sql_buf, "( " );
1704 // Get the parameters
1705 int func_item_index = 1; // We already grabbed the zeroth entry
1706 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1708 // Add a separator comma, if we need one
1709 if( func_item_index > 2 )
1710 buffer_add( sql_buf, ", " );
1712 // Add the current parameter
1713 if (func_item->type == JSON_NULL) {
1714 buffer_add( sql_buf, "NULL" );
1716 val = jsonObjectToSimpleString(func_item);
1717 if ( dbi_conn_quote_string(dbhandle, &val) ) {
1718 OSRF_BUFFER_ADD( sql_buf, val );
1721 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1722 buffer_free(sql_buf);
1729 buffer_add( sql_buf, " )" );
1731 return buffer_release(sql_buf);
1734 static char* searchFunctionPredicate (const char* class, osrfHash* field,
1735 const jsonObject* node, const char* node_key) {
1736 growing_buffer* sql_buf = buffer_init(32);
1738 char* val = searchValueTransform(node);
1744 osrfHashGet(field, "name"),
1751 return buffer_release(sql_buf);
1754 // class is a class name
1755 // field is a field definition as stored in the IDL
1756 // node comes from the method parameter, and represents an entry in the SELECT list
1757 static char* searchFieldTransform (const char* class, osrfHash* field, const jsonObject* node) {
1758 growing_buffer* sql_buf = buffer_init(32);
1760 char* field_transform = jsonObjectToSimpleString( jsonObjectGetKeyConst( node, "transform" ) );
1761 char* transform_subcolumn = jsonObjectToSimpleString( jsonObjectGetKeyConst( node, "result_field" ) );
1763 if(transform_subcolumn)
1764 OSRF_BUFFER_ADD_CHAR( sql_buf, '(' ); // enclose transform in parentheses
1766 if (field_transform) {
1767 buffer_fadd( sql_buf, "%s(\"%s\".%s", field_transform, class, osrfHashGet(field, "name"));
1768 const jsonObject* array = jsonObjectGetKeyConst( node, "params" );
1771 int func_item_index = 0;
1772 jsonObject* func_item;
1773 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1775 char* val = jsonObjectToSimpleString(func_item);
1778 buffer_add( sql_buf, ",NULL" );
1779 } else if ( dbi_conn_quote_string(dbhandle, &val) ) {
1780 OSRF_BUFFER_ADD_CHAR( sql_buf, ',' );
1781 OSRF_BUFFER_ADD( sql_buf, val );
1783 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1784 free(transform_subcolumn);
1785 free(field_transform);
1787 buffer_free(sql_buf);
1794 buffer_add( sql_buf, " )" );
1797 buffer_fadd( sql_buf, "\"%s\".%s", class, osrfHashGet(field, "name"));
1800 if (transform_subcolumn)
1801 buffer_fadd( sql_buf, ").\"%s\"", transform_subcolumn );
1803 if (field_transform) free(field_transform);
1804 if (transform_subcolumn) free(transform_subcolumn);
1806 return buffer_release(sql_buf);
1809 static char* searchFieldTransformPredicate (const char* class, osrfHash* field, jsonObject* node, const char* node_key) {
1810 char* field_transform = searchFieldTransform( class, field, node );
1813 if (!jsonObjectGetKeyConst( node, "value" )) {
1814 value = searchWHERE( node, osrfHashGet( oilsIDL(), class ), AND_OP_JOIN, NULL );
1815 } else if (jsonObjectGetKeyConst( node, "value" )->type == JSON_ARRAY) {
1816 value = searchValueTransform(jsonObjectGetKeyConst( node, "value" ));
1817 } else if (jsonObjectGetKeyConst( node, "value" )->type == JSON_HASH) {
1818 value = searchWHERE( jsonObjectGetKeyConst( node, "value" ), osrfHashGet( oilsIDL(), class ), AND_OP_JOIN, NULL );
1819 } else if (jsonObjectGetKeyConst( node, "value" )->type != JSON_NULL) {
1820 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1821 value = jsonNumberToDBString( field, jsonObjectGetKeyConst( node, "value" ) );
1823 value = jsonObjectToSimpleString(jsonObjectGetKeyConst( node, "value" ));
1824 if ( !dbi_conn_quote_string(dbhandle, &value) ) {
1825 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, value);
1827 free(field_transform);
1833 growing_buffer* sql_buf = buffer_init(32);
1844 free(field_transform);
1846 return buffer_release(sql_buf);
1849 static char* searchSimplePredicate (const char* orig_op, const char* class,
1850 osrfHash* field, const jsonObject* node) {
1854 if (node->type != JSON_NULL) {
1855 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1856 val = jsonNumberToDBString( field, node );
1858 val = jsonObjectToSimpleString(node);
1862 char* pred = searchWriteSimplePredicate( class, field, osrfHashGet(field, "name"), orig_op, val );
1869 static char* searchWriteSimplePredicate ( const char* class, osrfHash* field,
1870 const char* left, const char* orig_op, const char* right ) {
1874 if (right == NULL) {
1875 val = strdup("NULL");
1877 if (strcmp( orig_op, "=" ))
1878 op = strdup("IS NOT");
1882 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1883 val = strdup(right);
1884 op = strdup(orig_op);
1887 val = strdup(right);
1888 if ( !dbi_conn_quote_string(dbhandle, &val) ) {
1889 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1893 op = strdup(orig_op);
1896 growing_buffer* sql_buf = buffer_init(16);
1897 buffer_fadd( sql_buf, "\"%s\".%s %s %s", class, left, op, val );
1901 return buffer_release(sql_buf);
1904 static char* searchBETWEENPredicate (const char* class, osrfHash* field, jsonObject* node) {
1909 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1910 x_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,0));
1911 y_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,1));
1914 x_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,0));
1915 y_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,1));
1916 if ( !(dbi_conn_quote_string(dbhandle, &x_string) && dbi_conn_quote_string(dbhandle, &y_string)) ) {
1917 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key strings [%s] and [%s]", MODULENAME, x_string, y_string);
1924 growing_buffer* sql_buf = buffer_init(32);
1925 buffer_fadd( sql_buf, "%s BETWEEN %s AND %s", osrfHashGet(field, "name"), x_string, y_string );
1929 return buffer_release(sql_buf);
1932 static char* searchPredicate ( const char* class, osrfHash* field,
1933 jsonObject* node, osrfMethodContext* ctx ) {
1936 if (node->type == JSON_ARRAY) { // equality IN search
1937 pred = searchINPredicate( class, field, node, NULL, ctx );
1938 } else if (node->type == JSON_HASH) { // non-equality search
1939 jsonObject* pred_node;
1940 jsonIterator* pred_itr = jsonNewIterator( node );
1941 while ( (pred_node = jsonIteratorNext( pred_itr )) ) {
1942 if ( !(strcasecmp( pred_itr->key,"between" )) )
1943 pred = searchBETWEENPredicate( class, field, pred_node );
1944 else if ( !(strcasecmp( pred_itr->key,"in" )) || !(strcasecmp( pred_itr->key,"not in" )) )
1945 pred = searchINPredicate( class, field, pred_node, pred_itr->key, ctx );
1946 else if ( pred_node->type == JSON_ARRAY )
1947 pred = searchFunctionPredicate( class, field, pred_node, pred_itr->key );
1948 else if ( pred_node->type == JSON_HASH )
1949 pred = searchFieldTransformPredicate( class, field, pred_node, pred_itr->key );
1951 pred = searchSimplePredicate( pred_itr->key, class, field, pred_node );
1955 jsonIteratorFree(pred_itr);
1956 } else if (node->type == JSON_NULL) { // IS NULL search
1957 growing_buffer* _p = buffer_init(64);
1960 "\"%s\".%s IS NULL",
1962 osrfHashGet(field, "name")
1964 pred = buffer_release(_p);
1965 } else { // equality search
1966 pred = searchSimplePredicate( "=", class, field, node );
1985 field : call_number,
2001 static char* searchJOIN ( const jsonObject* join_hash, osrfHash* leftmeta ) {
2003 const jsonObject* working_hash;
2004 jsonObject* freeable_hash = NULL;
2006 if (join_hash->type == JSON_STRING) {
2007 // create a wrapper around a copy of the original
2008 char* _tmp = jsonObjectToSimpleString( join_hash );
2009 freeable_hash = jsonNewObjectType(JSON_HASH);
2010 jsonObjectSetKey(freeable_hash, _tmp, NULL);
2012 working_hash = freeable_hash;
2015 working_hash = join_hash;
2017 growing_buffer* join_buf = buffer_init(128);
2018 char* leftclass = osrfHashGet(leftmeta, "classname");
2020 jsonObject* snode = NULL;
2021 jsonIterator* search_itr = jsonNewIterator( working_hash );
2023 jsonObjectFree(freeable_hash);
2025 while ( (snode = jsonIteratorNext( search_itr )) ) {
2026 osrfHash* idlClass = osrfHashGet( oilsIDL(), search_itr->key );
2028 char* class = osrfHashGet(idlClass, "classname");
2030 char* fkey = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "fkey" ) );
2031 char* field = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "field" ) );
2033 if (field && !fkey) {
2034 fkey = (char*)oilsIDLFindPath("/%s/links/%s/key", class, field);
2038 "%s: JOIN failed. No link defined from %s.%s to %s",
2044 buffer_free(join_buf);
2046 jsonIteratorFree(search_itr);
2049 fkey = strdup( fkey );
2051 } else if (!field && fkey) {
2052 field = (char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, fkey );
2056 "%s: JOIN failed. No link defined from %s.%s to %s",
2062 buffer_free(join_buf);
2064 jsonIteratorFree(search_itr);
2067 field = strdup( field );
2069 } else if (!field && !fkey) {
2070 osrfHash* _links = oilsIDLFindPath("/%s/links", leftclass);
2073 osrfStringArray* keys = osrfHashKeys( _links );
2074 while ( (fkey = osrfStringArrayGetString(keys, i++)) ) {
2075 fkey = strdup(osrfStringArrayGetString(keys, i++));
2076 if ( !strcmp( (char*)oilsIDLFindPath("/%s/links/%s/class", leftclass, fkey), class) ) {
2077 field = strdup( (char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, fkey) );
2083 osrfStringArrayFree(keys);
2085 if (!field && !fkey) {
2086 _links = oilsIDLFindPath("/%s/links", class);
2089 keys = osrfHashKeys( _links );
2090 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
2091 field = strdup(osrfStringArrayGetString(keys, i++));
2092 if ( !strcmp( (char*)oilsIDLFindPath("/%s/links/%s/class", class, field), class) ) {
2093 fkey = strdup( (char*)oilsIDLFindPath("/%s/links/%s/key", class, field) );
2099 osrfStringArrayFree(keys);
2102 if (!field && !fkey) {
2105 "%s: JOIN failed. No link defined between %s and %s",
2110 buffer_free(join_buf);
2111 jsonIteratorFree(search_itr);
2117 char* type = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "type" ) );
2119 if ( !strcasecmp(type,"left") ) {
2120 buffer_add(join_buf, " LEFT JOIN");
2121 } else if ( !strcasecmp(type,"right") ) {
2122 buffer_add(join_buf, " RIGHT JOIN");
2123 } else if ( !strcasecmp(type,"full") ) {
2124 buffer_add(join_buf, " FULL JOIN");
2126 buffer_add(join_buf, " INNER JOIN");
2129 buffer_add(join_buf, " INNER JOIN");
2133 char* table = getSourceDefinition(idlClass);
2134 buffer_fadd(join_buf, " %s AS \"%s\" ON ( \"%s\".%s = \"%s\".%s", table, class, class, field, leftclass, fkey);
2137 const jsonObject* filter = jsonObjectGetKeyConst( snode, "filter" );
2139 char* filter_op = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "filter_op" ) );
2141 if (!strcasecmp("or",filter_op)) {
2142 buffer_add( join_buf, " OR " );
2144 buffer_add( join_buf, " AND " );
2147 buffer_add( join_buf, " AND " );
2150 char* jpred = searchWHERE( filter, idlClass, AND_OP_JOIN, NULL );
2151 OSRF_BUFFER_ADD_CHAR( join_buf, ' ' );
2152 OSRF_BUFFER_ADD( join_buf, jpred );
2157 buffer_add(join_buf, " ) ");
2159 const jsonObject* join_filter = jsonObjectGetKeyConst( snode, "join" );
2161 char* jpred = searchJOIN( join_filter, idlClass );
2162 OSRF_BUFFER_ADD_CHAR( join_buf, ' ' );
2163 OSRF_BUFFER_ADD( join_buf, jpred );
2171 jsonIteratorFree(search_itr);
2173 return buffer_release(join_buf);
2178 { +class : { -or|-and : { field : { op : value }, ... } ... }, ... }
2179 { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }
2180 [ { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }, ... ]
2184 static char* searchWHERE ( const jsonObject* search_hash, osrfHash* meta, int opjoin_type, osrfMethodContext* ctx ) {
2188 "%s: Entering searchWHERE; search_hash addr = %p, meta addr = %p, opjoin_type = %d, ctx addr = %p",
2196 growing_buffer* sql_buf = buffer_init(128);
2198 jsonObject* node = NULL;
2201 if ( search_hash->type == JSON_ARRAY ) {
2202 osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_ARRAY", MODULENAME);
2203 jsonIterator* search_itr = jsonNewIterator( search_hash );
2204 while ( (node = jsonIteratorNext( search_itr )) ) {
2208 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2209 else buffer_add(sql_buf, " AND ");
2212 char* subpred = searchWHERE( node, meta, opjoin_type, ctx );
2213 buffer_fadd(sql_buf, "( %s )", subpred);
2216 jsonIteratorFree(search_itr);
2218 } else if ( search_hash->type == JSON_HASH ) {
2219 osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_HASH", MODULENAME);
2220 jsonIterator* search_itr = jsonNewIterator( search_hash );
2221 while ( (node = jsonIteratorNext( search_itr )) ) {
2226 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2227 else buffer_add(sql_buf, " AND ");
2230 if ( !strncmp("+",search_itr->key,1) ) {
2231 if ( node->type == JSON_STRING ) {
2232 char* subpred = jsonObjectToSimpleString( node );
2233 buffer_fadd(sql_buf, " \"%s\".%s ", search_itr->key + 1, subpred);
2236 char* subpred = searchWHERE( node, osrfHashGet( oilsIDL(), search_itr->key + 1 ), AND_OP_JOIN, ctx );
2237 buffer_fadd(sql_buf, "( %s )", subpred);
2240 } else if ( !strcasecmp("-or",search_itr->key) ) {
2241 char* subpred = searchWHERE( node, meta, OR_OP_JOIN, ctx );
2242 buffer_fadd(sql_buf, "( %s )", subpred);
2244 } else if ( !strcasecmp("-and",search_itr->key) ) {
2245 char* subpred = searchWHERE( node, meta, AND_OP_JOIN, ctx );
2246 buffer_fadd(sql_buf, "( %s )", subpred);
2248 } else if ( !strcasecmp("-exists",search_itr->key) ) {
2249 char* subpred = SELECT(
2251 jsonObjectGetKey( node, "select" ),
2252 jsonObjectGetKey( node, "from" ),
2253 jsonObjectGetKey( node, "where" ),
2254 jsonObjectGetKey( node, "having" ),
2255 jsonObjectGetKey( node, "order_by" ),
2256 jsonObjectGetKey( node, "limit" ),
2257 jsonObjectGetKey( node, "offset" ),
2261 buffer_fadd(sql_buf, "EXISTS ( %s )", subpred);
2263 } else if ( !strcasecmp("-not-exists",search_itr->key) ) {
2264 char* subpred = SELECT(
2266 jsonObjectGetKey( node, "select" ),
2267 jsonObjectGetKey( node, "from" ),
2268 jsonObjectGetKey( node, "where" ),
2269 jsonObjectGetKey( node, "having" ),
2270 jsonObjectGetKey( node, "order_by" ),
2271 jsonObjectGetKey( node, "limit" ),
2272 jsonObjectGetKey( node, "offset" ),
2276 buffer_fadd(sql_buf, "NOT EXISTS ( %s )", subpred);
2280 char* class = osrfHashGet(meta, "classname");
2281 osrfHash* fields = osrfHashGet(meta, "fields");
2282 osrfHash* field = osrfHashGet( fields, search_itr->key );
2286 char* table = getSourceDefinition(meta);
2289 "%s: Attempt to reference non-existent column %s on %s (%s)",
2295 buffer_free(sql_buf);
2297 jsonIteratorFree(search_itr);
2301 char* subpred = searchPredicate( class, field, node, ctx );
2302 buffer_add( sql_buf, subpred );
2306 jsonIteratorFree(search_itr);
2309 // ERROR ... only hash and array allowed at this level
2310 char* predicate_string = jsonObjectToJSON( search_hash );
2313 "%s: Invalid predicate structure: %s",
2317 buffer_free(sql_buf);
2318 free(predicate_string);
2323 return buffer_release(sql_buf);
2326 static char* SELECT (
2327 /* method context */ osrfMethodContext* ctx,
2329 /* SELECT */ jsonObject* selhash,
2330 /* FROM */ jsonObject* join_hash,
2331 /* WHERE */ jsonObject* search_hash,
2332 /* HAVING */ jsonObject* having_hash,
2333 /* ORDER BY */ jsonObject* order_hash,
2334 /* LIMIT */ jsonObject* limit,
2335 /* OFFSET */ jsonObject* offset,
2336 /* flags */ int flags
2338 const char* locale = osrf_message_get_last_locale();
2340 // in case we don't get a select list
2341 jsonObject* defaultselhash = NULL;
2343 // general tmp objects
2344 const jsonObject* tmp_const;
2345 jsonObject* selclass = NULL;
2346 jsonObject* selfield = NULL;
2347 jsonObject* snode = NULL;
2348 jsonObject* onode = NULL;
2350 char* string = NULL;
2351 int from_function = 0;
2356 // the core search class
2357 char* core_class = NULL;
2359 // metadata about the core search class
2360 osrfHash* core_meta = NULL;
2362 // punt if there's no core class
2363 if (!join_hash || ( join_hash->type == JSON_HASH && !join_hash->size ))
2366 // get the core class -- the only key of the top level FROM clause, or a string
2367 if (join_hash->type == JSON_HASH) {
2368 jsonIterator* tmp_itr = jsonNewIterator( join_hash );
2369 snode = jsonIteratorNext( tmp_itr );
2371 core_class = strdup( tmp_itr->key );
2374 jsonObject* extra = jsonIteratorNext( tmp_itr );
2376 jsonIteratorFree( tmp_itr );
2379 // There shouldn't be more than one entry in join_hash
2381 return NULL; // Malformed join_hash; extra entry
2383 } else if (join_hash->type == JSON_ARRAY) {
2385 core_class = jsonObjectToSimpleString( jsonObjectGetIndex(join_hash, 0) );
2388 } else if (join_hash->type == JSON_STRING) {
2389 core_class = jsonObjectToSimpleString( join_hash );
2395 // punt if we don't know about the core class (and it's not a function)
2396 if (!from_function && !(core_meta = osrfHashGet( oilsIDL(), core_class ))) {
2401 // if the select list is empty, or the core class field list is '*',
2402 // build the default select list ...
2404 selhash = defaultselhash = jsonNewObjectType(JSON_HASH);
2405 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2406 } else if ( (tmp_const = jsonObjectGetKeyConst( selhash, core_class )) && tmp_const->type == JSON_STRING ) {
2407 char* _x = jsonObjectToSimpleString( tmp_const );
2408 if (!strncmp( "*", _x, 1 )) {
2409 jsonObjectRemoveKey( selhash, core_class );
2410 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2416 growing_buffer* sql_buf = buffer_init(128);
2418 // temp buffer for the SELECT list
2419 growing_buffer* select_buf = buffer_init(128);
2420 growing_buffer* order_buf = buffer_init(128);
2421 growing_buffer* group_buf = buffer_init(128);
2422 growing_buffer* having_buf = buffer_init(128);
2424 // Build a select list
2425 if(from_function) // From a function we select everything
2426 OSRF_BUFFER_ADD_CHAR( select_buf, '*' );
2429 // If we need to build a default list, do so
2430 jsonObject* _tmp = jsonObjectGetKey( selhash, core_class );
2431 if ( _tmp && !_tmp->size ) {
2435 osrfHash* core_fields = osrfHashGet( core_meta, "fields" );
2437 osrfStringArray* keys = osrfHashKeys( core_fields );
2438 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
2439 if( ! str_is_true( osrfHashGet( osrfHashGet( core_fields, field ), "virtual" ) ) )
2440 jsonObjectPush( _tmp, jsonNewObject( field ) ); // not virtual; use it
2442 osrfStringArrayFree(keys);
2445 // Now build the actual select list
2447 jsonObject* is_agg = jsonObjectFindPath(selhash, "//aggregate");
2450 jsonIterator* selclass_itr = jsonNewIterator( selhash );
2451 while ( (selclass = jsonIteratorNext( selclass_itr )) ) { // For each class
2453 // round trip through the idl, just to be safe
2454 const char* cname = selclass_itr->key;
2455 osrfHash* idlClass = osrfHashGet( oilsIDL(), cname );
2457 // No such class. Skip it.
2460 // Make sure the target relation is in the join tree.
2462 // At this point join_hash is a step down from the join_hash we
2463 // received as a parameter. If the original was a JSON_STRING,
2464 // then json_hash is now NULL. If the original was a JSON_HASH,
2465 // then json_hash is now the first (and only) entry in it,
2466 // denoting the core class. We've already excluded the
2467 // possibility that the original was a JSON_ARRAY, because in
2468 // that case from_function would be non-NULL, and we wouldn't
2471 if ( strcmp( core_class, cname )) {
2473 // There's only one class in the FROM clause,
2474 // and this isn't it. Skip it.
2477 if (join_hash->type == JSON_STRING) {
2478 string = jsonObjectToSimpleString(join_hash);
2479 int different = strcmp( string, cname );
2482 // There's only one class in the FROM clause,
2483 // and this isn't it. Skip it.
2486 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", cname);
2487 unsigned long size = found->size;
2488 jsonObjectFree( found );
2490 // No such class anywhere in the join tree. Skip it.
2495 // Look up some attributes of the current class, so that we
2496 // don't have to look them up again for each field
2497 osrfHash* class_field_set = osrfHashGet( idlClass, "fields" );
2498 char* class_pkey = osrfHashGet( idlClass, "primarykey" );
2499 char* class_tname = osrfHashGet( idlClass, "tablename" );
2501 // stitch together the column list ...
2502 jsonIterator* select_itr = jsonNewIterator( selclass );
2503 while ( (selfield = jsonIteratorNext( select_itr )) ) { // for each SELECT column
2505 // If we need a separator comma, add one
2509 OSRF_BUFFER_ADD_CHAR( select_buf, ',' );
2512 // ... if it's a string, just toss it on the pile
2513 if (selfield->type == JSON_STRING) {
2515 // again, just to be safe
2516 const char* _requested_col = selfield->value.s;
2517 osrfHash* field = osrfHashGet( class_field_set, _requested_col );
2518 if (!field) continue; // No such field in current class; skip it
2520 const char* col_name = osrfHashGet(field, "name");
2524 if (flags & DISABLE_I18N)
2527 i18n = osrfHashGet(field, "i18n");
2529 if( str_is_true( i18n ) ) {
2530 buffer_fadd( select_buf,
2531 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2532 class_tname, cname, col_name, class_pkey, cname, class_pkey, locale, col_name );
2534 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2537 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2540 // ... but it could be an object, in which case we check for a Field Transform
2543 char* _column = jsonObjectToSimpleString( jsonObjectGetKeyConst( selfield, "column" ) );
2545 // Get the field definition from the IDL
2546 osrfHash* field = osrfHashGet( class_field_set, _column );
2547 if (!field) continue; // No such field defined in IDL. Skip it.
2549 // Decide what to use as a column alias
2551 if ((tmp_const = jsonObjectGetKeyConst( selfield, "alias" ))) {
2552 _alias = jsonObjectToSimpleString( tmp_const );
2554 } else { // Use column name as its own alias
2557 _column = NULL; // To emphasize that we're through with _column
2559 if (jsonObjectGetKeyConst( selfield, "transform" )) {
2560 char* transform_str = searchFieldTransform(cname, field, selfield);
2561 buffer_fadd(select_buf, " %s AS \"%s\"", transform_str, _alias);
2562 free(transform_str);
2565 const char* fname = osrfHashGet(field, "name");
2569 if (flags & DISABLE_I18N)
2572 i18n = osrfHashGet(field, "i18n");
2574 if( str_is_true( i18n ) ) {
2575 buffer_fadd( select_buf,
2576 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2577 class_tname, cname, fname, class_pkey, cname, class_pkey, locale, _alias);
2579 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, fname, _alias);
2582 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, fname, _alias);
2589 if (is_agg->size || (flags & SELECT_DISTINCT)) {
2591 const jsonObject* aggregate_obj = jsonObjectGetKey( selfield, "aggregate" );
2592 if ( ! obj_is_true( aggregate_obj ) ) {
2596 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
2599 buffer_fadd(group_buf, " %d", sel_pos);
2601 } else if (is_agg = jsonObjectGetKey( selfield, "having" )) {
2605 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
2608 _column = searchFieldTransform(cname, field, selfield);
2609 OSRF_BUFFER_ADD_CHAR(group_buf, ' ');
2610 OSRF_BUFFER_ADD(group_buf, _column);
2611 _column = searchFieldTransform(cname, field, selfield);
2617 } // end while -- iterating across SELECT columns
2619 jsonIteratorFree(select_itr);
2620 } // end while -- iterating across classes
2622 jsonIteratorFree(selclass_itr);
2624 if (is_agg) jsonObjectFree(is_agg);
2628 char* col_list = buffer_release(select_buf);
2630 if (from_function) table = searchValueTransform(join_hash);
2631 else table = getSourceDefinition(core_meta);
2633 // Put it all together
2634 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\" ", col_list, table, core_class );
2638 if (!from_function) {
2639 // Now, walk the join tree and add that clause
2641 char* join_clause = searchJOIN( join_hash, core_meta );
2642 buffer_add(sql_buf, join_clause);
2646 // Build a WHERE clause, if there is one
2647 if ( search_hash ) {
2648 buffer_add(sql_buf, " WHERE ");
2650 // and it's on the WHERE clause
2651 char* pred = searchWHERE( search_hash, core_meta, AND_OP_JOIN, ctx );
2654 buffer_add(sql_buf, pred);
2658 osrfAppSessionStatus(
2660 OSRF_STATUS_INTERNALSERVERERROR,
2661 "osrfMethodException",
2663 "Severe query error in WHERE predicate -- see error log for more details"
2667 buffer_free(having_buf);
2668 buffer_free(group_buf);
2669 buffer_free(order_buf);
2670 buffer_free(sql_buf);
2671 if (defaultselhash) jsonObjectFree(defaultselhash);
2676 // Build a HAVING clause, if there is one
2677 if ( having_hash ) {
2678 buffer_add(sql_buf, " HAVING ");
2680 // and it's on the the WHERE clause
2681 char* pred = searchWHERE( having_hash, core_meta, AND_OP_JOIN, ctx );
2684 buffer_add(sql_buf, pred);
2688 osrfAppSessionStatus(
2690 OSRF_STATUS_INTERNALSERVERERROR,
2691 "osrfMethodException",
2693 "Severe query error in HAVING predicate -- see error log for more details"
2697 buffer_free(having_buf);
2698 buffer_free(group_buf);
2699 buffer_free(order_buf);
2700 buffer_free(sql_buf);
2701 if (defaultselhash) jsonObjectFree(defaultselhash);
2706 // Build an ORDER BY clause, if there is one
2708 jsonIterator* class_itr = jsonNewIterator( order_hash );
2709 while ( (snode = jsonIteratorNext( class_itr )) ) {
2711 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
2714 if ( snode->type == JSON_HASH ) {
2716 jsonIterator* order_itr = jsonNewIterator( snode );
2717 while ( (onode = jsonIteratorNext( order_itr )) ) {
2719 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
2722 char* direction = NULL;
2723 if ( onode->type == JSON_HASH ) {
2724 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
2725 string = searchFieldTransform(
2727 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
2731 growing_buffer* field_buf = buffer_init(16);
2732 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
2733 string = buffer_release(field_buf);
2736 if ( (tmp_const = jsonObjectGetKeyConst( onode, "direction" )) ) {
2737 direction = jsonObjectToSimpleString(tmp_const);
2738 if (!strncasecmp(direction, "d", 1)) {
2740 direction = " DESC";
2748 string = strdup(order_itr->key);
2749 direction = jsonObjectToSimpleString(onode);
2750 if (!strncasecmp(direction, "d", 1)) {
2752 direction = " DESC";
2762 buffer_add(order_buf, ", ");
2765 buffer_add(order_buf, string);
2769 buffer_add(order_buf, direction);
2773 // jsonIteratorFree(order_itr);
2775 } else if ( snode->type == JSON_ARRAY ) {
2777 jsonIterator* order_itr = jsonNewIterator( snode );
2778 while ( (onode = jsonIteratorNext( order_itr )) ) {
2780 char* _f = jsonObjectToSimpleString( onode );
2782 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, _f))
2788 buffer_add(order_buf, ", ");
2791 buffer_add(order_buf, _f);
2795 // jsonIteratorFree(order_itr);
2798 // IT'S THE OOOOOOOOOOOLD STYLE!
2800 osrfLogError(OSRF_LOG_MARK, "%s: Possible SQL injection attempt; direct order by is not allowed", MODULENAME);
2802 osrfAppSessionStatus(
2804 OSRF_STATUS_INTERNALSERVERERROR,
2805 "osrfMethodException",
2807 "Severe query error -- see error log for more details"
2812 buffer_free(having_buf);
2813 buffer_free(group_buf);
2814 buffer_free(order_buf);
2815 buffer_free(sql_buf);
2816 if (defaultselhash) jsonObjectFree(defaultselhash);
2817 jsonIteratorFree(class_itr);
2822 // jsonIteratorFree(class_itr);
2826 string = buffer_release(group_buf);
2828 if (strlen(string)) {
2829 OSRF_BUFFER_ADD( sql_buf, " GROUP BY " );
2830 OSRF_BUFFER_ADD( sql_buf, string );
2835 string = buffer_release(having_buf);
2837 if (strlen(string)) {
2838 OSRF_BUFFER_ADD( sql_buf, " HAVING " );
2839 OSRF_BUFFER_ADD( sql_buf, string );
2844 string = buffer_release(order_buf);
2846 if (strlen(string)) {
2847 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
2848 OSRF_BUFFER_ADD( sql_buf, string );
2854 string = jsonObjectToSimpleString(limit);
2855 buffer_fadd( sql_buf, " LIMIT %d", atoi(string) );
2860 string = jsonObjectToSimpleString(offset);
2861 buffer_fadd( sql_buf, " OFFSET %d", atoi(string) );
2865 if (!(flags & SUBSELECT)) OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
2868 if (defaultselhash) jsonObjectFree(defaultselhash);
2870 return buffer_release(sql_buf);
2874 static char* buildSELECT ( jsonObject* search_hash, jsonObject* order_hash, osrfHash* meta, osrfMethodContext* ctx ) {
2876 const char* locale = osrf_message_get_last_locale();
2878 osrfHash* fields = osrfHashGet(meta, "fields");
2879 char* core_class = osrfHashGet(meta, "classname");
2881 const jsonObject* join_hash = jsonObjectGetKeyConst( order_hash, "join" );
2883 jsonObject* node = NULL;
2884 jsonObject* snode = NULL;
2885 jsonObject* onode = NULL;
2886 const jsonObject* _tmp = NULL;
2887 jsonObject* selhash = NULL;
2888 jsonObject* defaultselhash = NULL;
2890 growing_buffer* sql_buf = buffer_init(128);
2891 growing_buffer* select_buf = buffer_init(128);
2893 if ( !(selhash = jsonObjectGetKey( order_hash, "select" )) ) {
2894 defaultselhash = jsonNewObjectType(JSON_HASH);
2895 selhash = defaultselhash;
2898 if ( !jsonObjectGetKeyConst(selhash,core_class) ) {
2899 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2900 jsonObject* flist = jsonObjectGetKey( selhash, core_class );
2905 osrfStringArray* keys = osrfHashKeys( fields );
2906 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
2907 if( ! str_is_true( osrfHashGet( osrfHashGet( fields, field ), "virtual" ) ) )
2908 jsonObjectPush( flist, jsonNewObject( field ) );
2910 osrfStringArrayFree(keys);
2914 jsonIterator* class_itr = jsonNewIterator( selhash );
2915 while ( (snode = jsonIteratorNext( class_itr )) ) {
2917 osrfHash* idlClass = osrfHashGet( oilsIDL(), class_itr->key );
2918 if (!idlClass) continue;
2919 char* cname = osrfHashGet(idlClass, "classname");
2921 if (strcmp(core_class,class_itr->key)) {
2922 if (!join_hash) continue;
2924 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", class_itr->key);
2926 jsonObjectFree(found);
2930 jsonObjectFree(found);
2933 jsonIterator* select_itr = jsonNewIterator( snode );
2934 while ( (node = jsonIteratorNext( select_itr )) ) {
2935 char* item_str = jsonObjectToSimpleString(node);
2936 osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), item_str );
2938 char* fname = osrfHashGet(field, "name");
2940 if (!field) continue;
2945 OSRF_BUFFER_ADD_CHAR(select_buf, ',');
2950 const jsonObject* no_i18n_obj = jsonObjectGetKey( order_hash, "no_i18n" );
2951 if ( obj_is_true( no_i18n_obj ) ) // Suppress internationalization?
2954 i18n = osrfHashGet(field, "i18n");
2956 if( str_is_true( i18n ) ) {
2957 char* pkey = osrfHashGet(idlClass, "primarykey");
2958 char* tname = osrfHashGet(idlClass, "tablename");
2960 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);
2962 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
2965 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
2969 jsonIteratorFree(select_itr);
2972 jsonIteratorFree(class_itr);
2974 char* col_list = buffer_release(select_buf);
2975 char* table = getSourceDefinition(meta);
2977 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\"", col_list, table, core_class );
2982 char* join_clause = searchJOIN( join_hash, meta );
2983 OSRF_BUFFER_ADD_CHAR(sql_buf, ' ');
2984 OSRF_BUFFER_ADD(sql_buf, join_clause);
2988 osrfLogDebug(OSRF_LOG_MARK, "%s pre-predicate SQL = %s",
2989 MODULENAME, OSRF_BUFFER_C_STR(sql_buf));
2991 buffer_add(sql_buf, " WHERE ");
2993 char* pred = searchWHERE( search_hash, meta, AND_OP_JOIN, ctx );
2995 osrfAppSessionStatus(
2997 OSRF_STATUS_INTERNALSERVERERROR,
2998 "osrfMethodException",
3000 "Severe query error -- see error log for more details"
3002 buffer_free(sql_buf);
3003 if(defaultselhash) jsonObjectFree(defaultselhash);
3006 buffer_add(sql_buf, pred);
3011 char* string = NULL;
3012 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "order_by" )) ){
3014 growing_buffer* order_buf = buffer_init(128);
3017 jsonIterator* class_itr = jsonNewIterator( _tmp );
3018 while ( (snode = jsonIteratorNext( class_itr )) ) {
3020 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
3023 if ( snode->type == JSON_HASH ) {
3025 jsonIterator* order_itr = jsonNewIterator( snode );
3026 while ( (onode = jsonIteratorNext( order_itr )) ) {
3028 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
3031 char* direction = NULL;
3032 if ( onode->type == JSON_HASH ) {
3033 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
3034 string = searchFieldTransform(
3036 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
3040 growing_buffer* field_buf = buffer_init(16);
3041 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
3042 string = buffer_release(field_buf);
3045 if ( (_tmp = jsonObjectGetKeyConst( onode, "direction" )) ) {
3046 direction = jsonObjectToSimpleString(_tmp);
3047 if (!strncasecmp(direction, "d", 1)) {
3049 direction = " DESC";
3057 string = strdup(order_itr->key);
3058 direction = jsonObjectToSimpleString(onode);
3059 if (!strncasecmp(direction, "d", 1)) {
3061 direction = " DESC";
3071 buffer_add(order_buf, ", ");
3074 buffer_add(order_buf, string);
3078 buffer_add(order_buf, direction);
3083 jsonIteratorFree(order_itr);
3086 string = jsonObjectToSimpleString(snode);
3087 buffer_add(order_buf, string);
3094 jsonIteratorFree(class_itr);
3096 string = buffer_release(order_buf);
3098 if (strlen(string)) {
3099 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
3100 OSRF_BUFFER_ADD( sql_buf, string );
3106 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "limit" )) ){
3107 string = jsonObjectToSimpleString(_tmp);
3116 _tmp = jsonObjectGetKeyConst( order_hash, "offset" );
3118 string = jsonObjectToSimpleString(_tmp);
3128 if (defaultselhash) jsonObjectFree(defaultselhash);
3130 OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
3131 return buffer_release(sql_buf);
3134 int doJSONSearch ( osrfMethodContext* ctx ) {
3135 if(osrfMethodVerifyContext( ctx )) {
3136 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
3140 osrfLogDebug(OSRF_LOG_MARK, "Recieved query request");
3145 dbhandle = writehandle;
3147 jsonObject* hash = jsonObjectGetIndex(ctx->params, 0);
3151 if ( obj_is_true( jsonObjectGetKey( hash, "distinct" ) ) )
3152 flags |= SELECT_DISTINCT;
3154 if ( obj_is_true( jsonObjectGetKey( hash, "no_i18n" ) ) )
3155 flags |= DISABLE_I18N;
3157 osrfLogDebug(OSRF_LOG_MARK, "Building SQL ...");
3160 jsonObjectGetKey( hash, "select" ),
3161 jsonObjectGetKey( hash, "from" ),
3162 jsonObjectGetKey( hash, "where" ),
3163 jsonObjectGetKey( hash, "having" ),
3164 jsonObjectGetKey( hash, "order_by" ),
3165 jsonObjectGetKey( hash, "limit" ),
3166 jsonObjectGetKey( hash, "offset" ),
3175 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3176 dbi_result result = dbi_conn_query(dbhandle, sql);
3179 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3181 if (dbi_result_first_row(result)) {
3182 /* JSONify the result */
3183 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3186 jsonObject* return_val = oilsMakeJSONFromResult( result );
3187 osrfAppRespond( ctx, return_val );
3188 jsonObjectFree( return_val );
3189 } while (dbi_result_next_row(result));
3192 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
3195 osrfAppRespondComplete( ctx, NULL );
3197 /* clean up the query */
3198 dbi_result_free(result);
3202 osrfLogError(OSRF_LOG_MARK, "%s: Error with query [%s]", MODULENAME, sql);
3203 osrfAppSessionStatus(
3205 OSRF_STATUS_INTERNALSERVERERROR,
3206 "osrfMethodException",
3208 "Severe query error -- see error log for more details"
3216 static jsonObject* doFieldmapperSearch ( osrfMethodContext* ctx, osrfHash* meta,
3217 const jsonObject* params, int* err ) {
3220 dbhandle = writehandle;
3222 osrfHash* links = osrfHashGet(meta, "links");
3223 osrfHash* fields = osrfHashGet(meta, "fields");
3224 char* core_class = osrfHashGet(meta, "classname");
3225 char* pkey = osrfHashGet(meta, "primarykey");
3227 const jsonObject* _tmp;
3229 jsonObject* search_hash = jsonObjectGetIndex(params, 0);
3230 jsonObject* order_hash = jsonObjectGetIndex(params, 1);
3232 char* sql = buildSELECT( search_hash, order_hash, meta, ctx );
3234 osrfLogDebug(OSRF_LOG_MARK, "Problem building query, returning NULL");
3239 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3241 dbi_result result = dbi_conn_query(dbhandle, sql);
3242 if( NULL == result ) {
3243 osrfLogError(OSRF_LOG_MARK, "%s: Error retrieving %s with query [%s]",
3244 MODULENAME, osrfHashGet(meta, "fieldmapper"), sql);
3245 osrfAppSessionStatus(
3247 OSRF_STATUS_INTERNALSERVERERROR,
3248 "osrfMethodException",
3250 "Severe query error -- see error log for more details"
3257 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3260 jsonObject* res_list = jsonNewObjectType(JSON_ARRAY);
3261 osrfHash* dedup = osrfNewHash();
3263 if (dbi_result_first_row(result)) {
3264 /* JSONify the result */
3265 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3267 obj = oilsMakeFieldmapperFromResult( result, meta );
3268 char* pkey_val = oilsFMGetString( obj, pkey );
3269 if ( osrfHashGet( dedup, pkey_val ) ) {
3270 jsonObjectFree(obj);
3273 osrfHashSet( dedup, pkey_val, pkey_val );
3274 jsonObjectPush(res_list, obj);
3276 } while (dbi_result_next_row(result));
3278 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s",
3282 osrfHashFree(dedup);
3283 /* clean up the query */
3284 dbi_result_free(result);
3287 if (res_list->size && order_hash) {
3288 _tmp = jsonObjectGetKeyConst( order_hash, "flesh" );
3290 int x = (int)jsonObjectGetNumber(_tmp);
3291 if (x == -1 || x > max_flesh_depth) x = max_flesh_depth;
3293 const jsonObject* temp_blob;
3294 if ((temp_blob = jsonObjectGetKeyConst( order_hash, "flesh_fields" )) && x > 0) {
3296 jsonObject* flesh_blob = jsonObjectClone( temp_blob );
3297 const jsonObject* flesh_fields = jsonObjectGetKeyConst( flesh_blob, core_class );
3299 osrfStringArray* link_fields = NULL;
3302 if (flesh_fields->size == 1) {
3303 char* _t = jsonObjectToSimpleString( jsonObjectGetIndex( flesh_fields, 0 ) );
3304 if (!strcmp(_t,"*")) link_fields = osrfHashKeys( links );
3310 link_fields = osrfNewStringArray(1);
3311 jsonIterator* _i = jsonNewIterator( flesh_fields );
3312 while ((_f = jsonIteratorNext( _i ))) {
3313 osrfStringArrayAdd( link_fields, jsonObjectToSimpleString( _f ) );
3315 jsonIteratorFree(_i);
3320 jsonIterator* itr = jsonNewIterator( res_list );
3321 while ((cur = jsonIteratorNext( itr ))) {
3326 while ( (link_field = osrfStringArrayGetString(link_fields, i++)) ) {
3328 osrfLogDebug(OSRF_LOG_MARK, "Starting to flesh %s", link_field);
3330 osrfHash* kid_link = osrfHashGet(links, link_field);
3331 if (!kid_link) continue;
3333 osrfHash* field = osrfHashGet(fields, link_field);
3334 if (!field) continue;
3336 osrfHash* value_field = field;
3338 osrfHash* kid_idl = osrfHashGet(oilsIDL(), osrfHashGet(kid_link, "class"));
3339 if (!kid_idl) continue;
3341 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3342 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3345 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) { // might_have
3346 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3349 osrfStringArray* link_map = osrfHashGet( kid_link, "map" );
3351 if (link_map->size > 0) {
3352 jsonObject* _kid_key = jsonNewObjectType(JSON_ARRAY);
3355 jsonNewObject( osrfStringArrayGetString( link_map, 0 ) )
3360 osrfHashGet(kid_link, "class"),
3367 "Link field: %s, remote class: %s, fkey: %s, reltype: %s",
3368 osrfHashGet(kid_link, "field"),
3369 osrfHashGet(kid_link, "class"),
3370 osrfHashGet(kid_link, "key"),
3371 osrfHashGet(kid_link, "reltype")
3374 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
3375 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // search hash
3376 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // order/flesh hash
3378 osrfLogDebug(OSRF_LOG_MARK, "Creating dummy params object...");
3381 jsonObjectToSimpleString(
3384 atoi( osrfHashGet(value_field, "array_position") )
3389 osrfLogDebug(OSRF_LOG_MARK, "Nothing to search for!");
3394 jsonObjectGetIndex(fake_params, 0),
3395 osrfHashGet(kid_link, "key"),
3396 jsonNewObject( search_key )
3403 jsonObjectGetIndex(fake_params, 1),
3405 jsonNewNumberObject( (double)(x - 1 + link_map->size) )
3409 jsonObjectSetKey( jsonObjectGetIndex(fake_params, 1), "flesh_fields", jsonObjectClone(flesh_blob) );
3411 if (jsonObjectGetKeyConst(order_hash, "order_by")) {
3413 jsonObjectGetIndex(fake_params, 1),
3415 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "order_by"))
3419 if (jsonObjectGetKeyConst(order_hash, "select")) {
3421 jsonObjectGetIndex(fake_params, 1),
3423 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "select"))
3427 jsonObject* kids = doFieldmapperSearch(ctx, kid_idl, fake_params, err);
3430 jsonObjectFree( fake_params );
3431 osrfStringArrayFree(link_fields);
3432 jsonIteratorFree(itr);
3433 jsonObjectFree(res_list);
3434 jsonObjectFree(flesh_blob);
3438 osrfLogDebug(OSRF_LOG_MARK, "Search for %s return %d linked objects", osrfHashGet(kid_link, "class"), kids->size);
3440 jsonObject* X = NULL;
3441 if ( link_map->size > 0 && kids->size > 0 ) {
3443 kids = jsonNewObjectType(JSON_ARRAY);
3445 jsonObject* _k_node;
3446 jsonIterator* _k = jsonNewIterator( X );
3447 while ((_k_node = jsonIteratorNext( _k ))) {
3453 (unsigned long)atoi(
3459 osrfHashGet(kid_link, "class")
3463 osrfStringArrayGetString( link_map, 0 )
3472 jsonIteratorFree(_k);
3475 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_a" )) || !(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) {
3476 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3479 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3480 jsonObjectClone( jsonObjectGetIndex(kids, 0) )
3484 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3485 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3488 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3489 jsonObjectClone( kids )
3494 jsonObjectFree(kids);
3498 jsonObjectFree( kids );
3499 jsonObjectFree( fake_params );
3501 osrfLogDebug(OSRF_LOG_MARK, "Fleshing of %s complete", osrfHashGet(kid_link, "field"));
3502 osrfLogDebug(OSRF_LOG_MARK, "%s", jsonObjectToJSON(cur));
3506 jsonObjectFree( flesh_blob );
3507 osrfStringArrayFree(link_fields);
3508 jsonIteratorFree(itr);
3517 static jsonObject* doUpdate(osrfMethodContext* ctx, int* err ) {
3519 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3521 jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
3523 jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
3526 if (!verifyObjectClass(ctx, target)) {
3531 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3532 osrfAppSessionStatus(
3534 OSRF_STATUS_BADREQUEST,
3535 "osrfMethodException",
3537 "No active transaction -- required for UPDATE"
3543 // The following test is harmless but redundant. If a class is
3544 // readonly, we don't register an update method for it.
3545 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
3546 osrfAppSessionStatus(
3548 OSRF_STATUS_BADREQUEST,
3549 "osrfMethodException",
3551 "Cannot UPDATE readonly class"
3557 dbhandle = writehandle;
3559 char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
3561 // Set the last_xact_id
3562 int index = oilsIDL_ntop( target->classname, "last_xact_id" );
3564 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
3565 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
3568 char* pkey = osrfHashGet(meta, "primarykey");
3569 osrfHash* fields = osrfHashGet(meta, "fields");
3571 char* id = oilsFMGetString( target, pkey );
3575 "%s updating %s object with %s = %s",
3577 osrfHashGet(meta, "fieldmapper"),
3582 growing_buffer* sql = buffer_init(128);
3583 buffer_fadd(sql,"UPDATE %s SET", osrfHashGet(meta, "tablename"));
3588 osrfStringArray* field_list = osrfHashKeys( fields );
3589 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
3591 osrfHash* field = osrfHashGet( fields, field_name );
3593 if(!( strcmp( field_name, pkey ) )) continue;
3594 if( str_is_true( osrfHashGet(osrfHashGet(fields,field_name), "virtual") ) )
3597 const jsonObject* field_object = oilsFMGetObject( target, field_name );
3600 if (field_object && field_object->classname) {
3601 value = oilsFMGetString(
3603 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
3606 value = jsonObjectToSimpleString( field_object );
3609 osrfLogDebug( OSRF_LOG_MARK, "Updating %s object with %s = %s", osrfHashGet(meta, "fieldmapper"), field_name, value);
3611 if (!field_object || field_object->type == JSON_NULL) {
3612 if ( !(!( strcmp( osrfHashGet(meta, "classname"), "au" ) ) && !( strcmp( field_name, "passwd" ) )) ) { // arg at the special case!
3613 if (first) first = 0;
3614 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3615 buffer_fadd( sql, " %s = NULL", field_name );
3618 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
3619 if (first) first = 0;
3620 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3622 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
3623 buffer_fadd( sql, " %s = %ld", field_name, atol(value) );
3624 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
3625 buffer_fadd( sql, " %s = %f", field_name, atof(value) );
3628 osrfLogDebug( OSRF_LOG_MARK, "%s is of type %s", field_name, osrfHashGet(field, "datatype"));
3631 if ( dbi_conn_quote_string(dbhandle, &value) ) {
3632 if (first) first = 0;
3633 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3634 buffer_fadd( sql, " %s = %s", field_name, value );
3637 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
3638 osrfAppSessionStatus(
3640 OSRF_STATUS_INTERNALSERVERERROR,
3641 "osrfMethodException",
3643 "Error quoting string -- please see the error log for more details"
3657 jsonObject* obj = jsonNewObject(id);
3659 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
3660 dbi_conn_quote_string(dbhandle, &id);
3662 buffer_fadd( sql, " WHERE %s = %s;", pkey, id );
3664 char* query = buffer_release(sql);
3665 osrfLogDebug(OSRF_LOG_MARK, "%s: Update SQL [%s]", MODULENAME, query);
3667 dbi_result result = dbi_conn_query(dbhandle, query);
3671 jsonObjectFree(obj);
3672 obj = jsonNewObject(NULL);
3675 "%s ERROR updating %s object with %s = %s",
3677 osrfHashGet(meta, "fieldmapper"),
3688 static jsonObject* doDelete(osrfMethodContext* ctx, int* err ) {
3690 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3692 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3693 osrfAppSessionStatus(
3695 OSRF_STATUS_BADREQUEST,
3696 "osrfMethodException",
3698 "No active transaction -- required for DELETE"
3704 // The following test is harmless but redundant. If a class is
3705 // readonly, we don't register a delete method for it.
3706 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
3707 osrfAppSessionStatus(
3709 OSRF_STATUS_BADREQUEST,
3710 "osrfMethodException",
3712 "Cannot DELETE readonly class"
3718 dbhandle = writehandle;
3722 char* pkey = osrfHashGet(meta, "primarykey");
3730 if (jsonObjectGetIndex(ctx->params, _obj_pos)->classname) {
3731 if (!verifyObjectClass(ctx, jsonObjectGetIndex( ctx->params, _obj_pos ))) {
3736 id = oilsFMGetString( jsonObjectGetIndex(ctx->params, _obj_pos), pkey );
3739 if (!verifyObjectPCRUD( ctx, NULL )) {
3744 id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, _obj_pos));
3749 "%s deleting %s object with %s = %s",
3751 osrfHashGet(meta, "fieldmapper"),
3756 obj = jsonNewObject(id);
3758 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
3759 dbi_conn_quote_string(writehandle, &id);
3761 dbi_result result = dbi_conn_queryf(writehandle, "DELETE FROM %s WHERE %s = %s;", osrfHashGet(meta, "tablename"), pkey, id);
3764 jsonObjectFree(obj);
3765 obj = jsonNewObject(NULL);
3768 "%s ERROR deleting %s object with %s = %s",
3770 osrfHashGet(meta, "fieldmapper"),
3783 static jsonObject* oilsMakeFieldmapperFromResult( dbi_result result, osrfHash* meta) {
3784 if(!(result && meta)) return jsonNULL;
3786 jsonObject* object = jsonNewObject(NULL);
3787 jsonObjectSetClass(object, osrfHashGet(meta, "classname"));
3789 osrfHash* fields = osrfHashGet(meta, "fields");
3791 osrfLogInternal(OSRF_LOG_MARK, "Setting object class to %s ", object->classname);
3795 char dt_string[256];
3799 int columnIndex = 1;
3801 unsigned short type;
3802 const char* columnName;
3804 /* cycle through the column list */
3805 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
3807 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
3809 fmIndex = -1; // reset the position
3811 /* determine the field type and storage attributes */
3812 type = dbi_result_get_field_type(result, columnName);
3813 attr = dbi_result_get_field_attribs(result, columnName);
3815 /* fetch the fieldmapper index */
3816 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
3818 if ( str_is_true( osrfHashGet(_f, "virtual") ) )
3821 const char* pos = (char*)osrfHashGet(_f, "array_position");
3822 if ( !pos ) continue;
3824 fmIndex = atoi( pos );
3825 osrfLogInternal(OSRF_LOG_MARK, "... Found column at position [%s]...", pos);
3830 if (dbi_result_field_is_null(result, columnName)) {
3831 jsonObjectSetIndex( object, fmIndex, jsonNewObject(NULL) );
3836 case DBI_TYPE_INTEGER :
3838 if( attr & DBI_INTEGER_SIZE8 )
3839 jsonObjectSetIndex( object, fmIndex,
3840 jsonNewNumberObject(dbi_result_get_longlong(result, columnName)));
3842 jsonObjectSetIndex( object, fmIndex,
3843 jsonNewNumberObject(dbi_result_get_int(result, columnName)));
3847 case DBI_TYPE_DECIMAL :
3848 jsonObjectSetIndex( object, fmIndex,
3849 jsonNewNumberObject(dbi_result_get_double(result, columnName)));
3852 case DBI_TYPE_STRING :
3858 jsonNewObject( dbi_result_get_string(result, columnName) )
3863 case DBI_TYPE_DATETIME :
3865 memset(dt_string, '\0', sizeof(dt_string));
3866 memset(&gmdt, '\0', sizeof(gmdt));
3868 _tmp_dt = dbi_result_get_datetime(result, columnName);
3871 if (!(attr & DBI_DATETIME_DATE)) {
3872 gmtime_r( &_tmp_dt, &gmdt );
3873 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
3874 } else if (!(attr & DBI_DATETIME_TIME)) {
3875 localtime_r( &_tmp_dt, &gmdt );
3876 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
3878 localtime_r( &_tmp_dt, &gmdt );
3879 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
3882 jsonObjectSetIndex( object, fmIndex, jsonNewObject(dt_string) );
3886 case DBI_TYPE_BINARY :
3887 osrfLogError( OSRF_LOG_MARK,
3888 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
3896 static jsonObject* oilsMakeJSONFromResult( dbi_result result ) {
3897 if(!result) return jsonNULL;
3899 jsonObject* object = jsonNewObject(NULL);
3902 char dt_string[256];
3906 int columnIndex = 1;
3908 unsigned short type;
3909 const char* columnName;
3911 /* cycle through the column list */
3912 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
3914 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
3916 fmIndex = -1; // reset the position
3918 /* determine the field type and storage attributes */
3919 type = dbi_result_get_field_type(result, columnName);
3920 attr = dbi_result_get_field_attribs(result, columnName);
3922 if (dbi_result_field_is_null(result, columnName)) {
3923 jsonObjectSetKey( object, columnName, jsonNewObject(NULL) );
3928 case DBI_TYPE_INTEGER :
3930 if( attr & DBI_INTEGER_SIZE8 )
3931 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_longlong(result, columnName)) );
3933 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_int(result, columnName)) );
3936 case DBI_TYPE_DECIMAL :
3937 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_double(result, columnName)) );
3940 case DBI_TYPE_STRING :
3941 jsonObjectSetKey( object, columnName, jsonNewObject(dbi_result_get_string(result, columnName)) );
3944 case DBI_TYPE_DATETIME :
3946 memset(dt_string, '\0', sizeof(dt_string));
3947 memset(&gmdt, '\0', sizeof(gmdt));
3949 _tmp_dt = dbi_result_get_datetime(result, columnName);
3952 if (!(attr & DBI_DATETIME_DATE)) {
3953 gmtime_r( &_tmp_dt, &gmdt );
3954 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
3955 } else if (!(attr & DBI_DATETIME_TIME)) {
3956 localtime_r( &_tmp_dt, &gmdt );
3957 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
3959 localtime_r( &_tmp_dt, &gmdt );
3960 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
3963 jsonObjectSetKey( object, columnName, jsonNewObject(dt_string) );
3966 case DBI_TYPE_BINARY :
3967 osrfLogError( OSRF_LOG_MARK,
3968 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
3976 // Interpret a string as true or false
3977 static int str_is_true( const char* str ) {
3978 if( NULL == str || strcasecmp( str, "true" ) )
3984 // Interpret a jsonObject as true or false
3985 static int obj_is_true( const jsonObject* obj ) {
3988 else switch( obj->type )
3996 if( strcasecmp( obj->value.s, "true" ) )
4000 case JSON_NUMBER : // Support 1/0 for perl's sake
4001 if( jsonObjectGetNumber( obj ) == 1.0 )