1 #include "opensrf/osrf_application.h"
2 #include "opensrf/osrf_settings.h"
3 #include "opensrf/osrf_message.h"
4 #include "opensrf/utils.h"
5 #include "opensrf/osrf_json.h"
6 #include "opensrf/log.h"
7 #include "openils/oils_utils.h"
16 # define MODULENAME "open-ils.reporter-store"
19 # define MODULENAME "open-ils.pcrud"
21 # define MODULENAME "open-ils.cstore"
26 #define DISABLE_I18N 2
27 #define SELECT_DISTINCT 1
31 int osrfAppChildInit();
32 int osrfAppInitialize();
33 void osrfAppChildExit();
35 static int verifyObjectClass ( osrfMethodContext*, const jsonObject* );
37 int beginTransaction ( osrfMethodContext* );
38 int commitTransaction ( osrfMethodContext* );
39 int rollbackTransaction ( osrfMethodContext* );
41 int setSavepoint ( osrfMethodContext* );
42 int releaseSavepoint ( osrfMethodContext* );
43 int rollbackSavepoint ( osrfMethodContext* );
45 int doJSONSearch ( osrfMethodContext* );
47 int dispatchCRUDMethod ( osrfMethodContext* );
48 static jsonObject* doCreate ( osrfMethodContext*, int* );
49 static jsonObject* doRetrieve ( osrfMethodContext*, int* );
50 static jsonObject* doUpdate ( osrfMethodContext*, int* );
51 static jsonObject* doDelete ( osrfMethodContext*, int* );
52 static jsonObject* doFieldmapperSearch ( osrfMethodContext*, osrfHash*,
53 const jsonObject*, int* );
54 static jsonObject* oilsMakeFieldmapperFromResult( dbi_result, osrfHash* );
55 static jsonObject* oilsMakeJSONFromResult( dbi_result );
57 static char* searchWriteSimplePredicate ( const char*, osrfHash*,
58 const char*, const char*, const char* );
59 static char* searchSimplePredicate ( const char*, const char*, osrfHash*, const jsonObject* );
60 static char* searchFunctionPredicate ( const char*, osrfHash*, const jsonObject*, const char* );
61 static char* searchFieldTransform ( const char*, osrfHash*, const jsonObject*);
62 static char* searchFieldTransformPredicate ( const char*, osrfHash*, jsonObject*, const char* );
63 static char* searchBETWEENPredicate ( const char*, osrfHash*, jsonObject* );
64 static char* searchINPredicate ( const char*, osrfHash*,
65 jsonObject*, const char*, osrfMethodContext* );
66 static char* searchPredicate ( const char*, osrfHash*, jsonObject*, osrfMethodContext* );
67 static char* searchJOIN ( const jsonObject*, osrfHash* );
68 static char* searchWHERE ( const jsonObject*, osrfHash*, int, osrfMethodContext* );
69 static char* buildSELECT ( jsonObject*, jsonObject*, osrfHash*, osrfMethodContext* );
71 char* SELECT ( osrfMethodContext*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, int );
73 void userDataFree( void* );
74 static void sessionDataFree( char*, void* );
75 static char* getSourceDefinition( osrfHash* );
76 static int str_is_true( const char* str );
77 static int obj_is_true( const jsonObject* obj );
80 static jsonObject* verifyUserPCRUD( osrfMethodContext* );
81 static int verifyObjectPCRUD( osrfMethodContext*, const jsonObject* );
84 static dbi_conn writehandle; /* our MASTER db connection */
85 static dbi_conn dbhandle; /* our CURRENT db connection */
86 //static osrfHash * readHandles;
87 static jsonObject* jsonNULL = NULL; //
88 static int max_flesh_depth = 100;
90 /* called when this process is about to exit */
91 void osrfAppChildExit() {
92 osrfLogDebug(OSRF_LOG_MARK, "Child is exiting, disconnecting from database...");
95 if (writehandle == dbhandle) same = 1;
97 dbi_conn_query(writehandle, "ROLLBACK;");
98 dbi_conn_close(writehandle);
101 if (dbhandle && !same)
102 dbi_conn_close(dbhandle);
104 // XXX add cleanup of readHandles whenever that gets used
109 int osrfAppInitialize() {
111 osrfLogInfo(OSRF_LOG_MARK, "Initializing the CStore Server...");
112 osrfLogInfo(OSRF_LOG_MARK, "Finding XML file...");
114 if (!oilsIDLInit( osrf_settings_host_value("/IDL") )) return 1; /* return non-zero to indicate error */
116 growing_buffer* method_name = buffer_init(64);
118 // Generic search thingy
119 buffer_add(method_name, MODULENAME);
120 buffer_add(method_name, ".json_query");
121 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
122 "doJSONSearch", "", 1, OSRF_METHOD_STREAMING );
125 // first we register all the transaction and savepoint methods
126 buffer_reset(method_name);
127 OSRF_BUFFER_ADD(method_name, MODULENAME);
128 OSRF_BUFFER_ADD(method_name, ".transaction.begin");
129 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
130 "beginTransaction", "", 0, 0 );
132 buffer_reset(method_name);
133 OSRF_BUFFER_ADD(method_name, MODULENAME);
134 OSRF_BUFFER_ADD(method_name, ".transaction.commit");
135 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
136 "commitTransaction", "", 0, 0 );
138 buffer_reset(method_name);
139 OSRF_BUFFER_ADD(method_name, MODULENAME);
140 OSRF_BUFFER_ADD(method_name, ".transaction.rollback");
141 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
142 "rollbackTransaction", "", 0, 0 );
144 buffer_reset(method_name);
145 OSRF_BUFFER_ADD(method_name, MODULENAME);
146 OSRF_BUFFER_ADD(method_name, ".savepoint.set");
147 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
148 "setSavepoint", "", 1, 0 );
150 buffer_reset(method_name);
151 OSRF_BUFFER_ADD(method_name, MODULENAME);
152 OSRF_BUFFER_ADD(method_name, ".savepoint.release");
153 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
154 "releaseSavepoint", "", 1, 0 );
156 buffer_reset(method_name);
157 OSRF_BUFFER_ADD(method_name, MODULENAME);
158 OSRF_BUFFER_ADD(method_name, ".savepoint.rollback");
159 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
160 "rollbackSavepoint", "", 1, 0 );
162 buffer_free(method_name);
164 static const char* global_method[] = {
172 const int global_method_count
173 = sizeof( global_method ) / sizeof ( global_method[0] );
177 osrfStringArray* classes = osrfHashKeys( oilsIDL() );
178 osrfLogDebug(OSRF_LOG_MARK, "%d classes loaded", classes->size );
179 osrfLogDebug(OSRF_LOG_MARK,
180 "At least %d methods will be generated", classes->size * global_method_count);
182 while ( (classname = osrfStringArrayGetString(classes, c_index++)) ) {
183 osrfLogInfo(OSRF_LOG_MARK, "Generating class methods for %s", classname);
185 osrfHash* idlClass = osrfHashGet(oilsIDL(), classname);
187 if (!osrfStringArrayContains( osrfHashGet(idlClass, "controller"), MODULENAME )) {
188 osrfLogInfo(OSRF_LOG_MARK, "%s is not listed as a controller for %s, moving on", MODULENAME, classname);
192 if ( str_is_true( osrfHashGet(idlClass, "virtual") ) ) {
193 osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
197 // Look up some other attributes of the current class
198 const char* idlClass_fieldmapper = osrfHashGet(idlClass, "fieldmapper");
199 const char* readonly = osrfHashGet(idlClass, "readonly");
201 osrfHash* idlClass_permacrud = osrfHashGet(idlClass, "permacrud");
205 for( i = 0; i < global_method_count; ++i ) {
206 const char* method_type = global_method[ i ];
207 osrfLogDebug(OSRF_LOG_MARK,
208 "Using files to build %s class methods for %s", method_type, classname);
210 if (!idlClass_fieldmapper) continue;
213 if (!idlClass_permacrud) continue;
215 const char* tmp_method = method_type;
216 if ( *tmp_method == 'i' || *tmp_method == 's') {
217 tmp_method = "retrieve";
219 if (!osrfHashGet( idlClass_permacrud, tmp_method )) continue;
222 if ( str_is_true( readonly ) &&
223 ( *method_type == 'c' || *method_type == 'u' || *method_type == 'd')
226 osrfHash* method_meta = osrfNewHash();
227 osrfHashSet(method_meta, idlClass, "class");
229 method_name = buffer_init(64);
231 buffer_fadd(method_name, "%s.%s.%s", MODULENAME, method_type, classname);
235 char* _fm = strdup( idlClass_fieldmapper );
236 part = strtok_r(_fm, ":", &st_tmp);
238 buffer_fadd(method_name, "%s.direct.%s", MODULENAME, part);
240 while ((part = strtok_r(NULL, ":", &st_tmp))) {
241 OSRF_BUFFER_ADD_CHAR(method_name, '.');
242 OSRF_BUFFER_ADD(method_name, part);
244 OSRF_BUFFER_ADD_CHAR(method_name, '.');
245 OSRF_BUFFER_ADD(method_name, method_type);
249 char* method = buffer_release(method_name);
251 osrfHashSet( method_meta, method, "methodname" );
252 osrfHashSet( method_meta, strdup(method_type), "methodtype" );
255 if (*method_type == 'i' || *method_type == 's') {
256 flags = flags | OSRF_METHOD_STREAMING;
259 osrfAppRegisterExtendedMethod(
262 "dispatchCRUDMethod",
276 static char* getSourceDefinition( osrfHash* class ) {
278 char* tabledef = osrfHashGet(class, "tablename");
281 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 if( join_hash->type != JSON_HASH ) {
2018 "%s: JOIN failed; expected JSON object type not found",
2023 working_hash = join_hash;
2026 growing_buffer* join_buf = buffer_init(128);
2027 const char* leftclass = osrfHashGet(leftmeta, "classname");
2029 jsonObject* snode = NULL;
2030 jsonIterator* search_itr = jsonNewIterator( working_hash );
2032 while ( (snode = jsonIteratorNext( search_itr )) ) {
2033 osrfHash* idlClass = osrfHashGet( oilsIDL(), search_itr->key );
2037 "%s: JOIN failed. No class \"%s\" defined in IDL",
2041 jsonIteratorFree( search_itr );
2042 buffer_free( join_buf );
2044 jsonObjectFree( freeable_hash );
2048 const char* class = osrfHashGet(idlClass, "classname");
2050 char* fkey = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "fkey" ) );
2051 char* field = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "field" ) );
2053 if (field && !fkey) {
2054 fkey = (char*)oilsIDLFindPath("/%s/links/%s/key", class, field);
2058 "%s: JOIN failed. No link defined from %s.%s to %s",
2064 buffer_free(join_buf);
2066 jsonObjectFree(freeable_hash);
2068 jsonIteratorFree(search_itr);
2071 fkey = strdup( fkey );
2073 } else if (!field && fkey) {
2074 field = (char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, fkey );
2078 "%s: JOIN failed. No link defined from %s.%s to %s",
2084 buffer_free(join_buf);
2086 jsonObjectFree(freeable_hash);
2088 jsonIteratorFree(search_itr);
2091 field = strdup( field );
2093 } else if (!field && !fkey) {
2094 osrfHash* _links = oilsIDLFindPath("/%s/links", leftclass);
2096 // For each link defined for the left class:
2097 // see if the link references the joined class
2098 osrfHashIterator* itr = osrfNewHashIterator( _links );
2099 osrfHash* curr_link = NULL;
2100 while( (curr_link = osrfHashIteratorNext( itr ) ) ) {
2101 const char* other_class = osrfHashGet( curr_link, "class" );
2102 if( other_class && !strcmp( other_class, class ) ) {
2104 // Found a link between the classes
2105 fkey = strdup( osrfHashIteratorKey( itr ) );
2106 const char* other_key = osrfHashGet( curr_link, "key" );
2107 field = other_key ? strdup( other_key ) : NULL;
2111 osrfHashIteratorFree( itr );
2113 if (!field || !fkey) {
2114 // Do another such search, with the classes reversed
2115 _links = oilsIDLFindPath("/%s/links", class);
2117 // For each link defined for the joined class:
2118 // see if the link references the left class
2119 osrfHashIterator* itr = osrfNewHashIterator( _links );
2120 osrfHash* curr_link = NULL;
2121 while( (curr_link = osrfHashIteratorNext( itr ) ) ) {
2122 const char* other_class = osrfHashGet( curr_link, "class" );
2123 if( other_class && !strcmp( other_class, leftclass ) ) {
2125 // Found a link between the classes
2126 fkey = strdup( osrfHashIteratorKey( itr ) );
2127 const char* other_key = osrfHashGet( curr_link, "key" );
2128 field = other_key ? strdup( other_key ) : NULL;
2132 osrfHashIteratorFree( itr );
2135 if (!field || !fkey) {
2138 "%s: JOIN failed. No link defined between %s and %s",
2143 buffer_free(join_buf);
2145 jsonObjectFree(freeable_hash);
2146 jsonIteratorFree(search_itr);
2152 char* type = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "type" ) );
2154 if ( !strcasecmp(type,"left") ) {
2155 buffer_add(join_buf, " LEFT JOIN");
2156 } else if ( !strcasecmp(type,"right") ) {
2157 buffer_add(join_buf, " RIGHT JOIN");
2158 } else if ( !strcasecmp(type,"full") ) {
2159 buffer_add(join_buf, " FULL JOIN");
2161 buffer_add(join_buf, " INNER JOIN");
2164 buffer_add(join_buf, " INNER JOIN");
2168 char* table = getSourceDefinition(idlClass);
2169 buffer_fadd(join_buf, " %s AS \"%s\" ON ( \"%s\".%s = \"%s\".%s",
2170 table, class, class, field, leftclass, fkey);
2173 const jsonObject* filter = jsonObjectGetKeyConst( snode, "filter" );
2175 char* filter_op = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "filter_op" ) );
2177 if (!strcasecmp("or",filter_op)) {
2178 buffer_add( join_buf, " OR " );
2180 buffer_add( join_buf, " AND " );
2183 buffer_add( join_buf, " AND " );
2186 char* jpred = searchWHERE( filter, idlClass, AND_OP_JOIN, NULL );
2187 OSRF_BUFFER_ADD_CHAR( join_buf, ' ' );
2188 OSRF_BUFFER_ADD( join_buf, jpred );
2193 buffer_add(join_buf, " ) ");
2195 const jsonObject* join_filter = jsonObjectGetKeyConst( snode, "join" );
2197 char* jpred = searchJOIN( join_filter, idlClass );
2198 OSRF_BUFFER_ADD_CHAR( join_buf, ' ' );
2199 OSRF_BUFFER_ADD( join_buf, jpred );
2208 jsonObjectFree(freeable_hash);
2209 jsonIteratorFree(search_itr);
2211 return buffer_release(join_buf);
2216 { +class : { -or|-and : { field : { op : value }, ... } ... }, ... }
2217 { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }
2218 [ { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }, ... ]
2222 static char* searchWHERE ( const jsonObject* search_hash, osrfHash* meta, int opjoin_type, osrfMethodContext* ctx ) {
2226 "%s: Entering searchWHERE; search_hash addr = %p, meta addr = %p, opjoin_type = %d, ctx addr = %p",
2234 growing_buffer* sql_buf = buffer_init(128);
2236 jsonObject* node = NULL;
2239 if ( search_hash->type == JSON_ARRAY ) {
2240 osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_ARRAY", MODULENAME);
2241 jsonIterator* search_itr = jsonNewIterator( search_hash );
2242 while ( (node = jsonIteratorNext( search_itr )) ) {
2246 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2247 else buffer_add(sql_buf, " AND ");
2250 char* subpred = searchWHERE( node, meta, opjoin_type, ctx );
2251 buffer_fadd(sql_buf, "( %s )", subpred);
2254 jsonIteratorFree(search_itr);
2256 } else if ( search_hash->type == JSON_HASH ) {
2257 osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_HASH", MODULENAME);
2258 jsonIterator* search_itr = jsonNewIterator( search_hash );
2259 while ( (node = jsonIteratorNext( search_itr )) ) {
2264 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2265 else buffer_add(sql_buf, " AND ");
2268 if ( !strncmp("+",search_itr->key,1) ) {
2269 if ( node->type == JSON_STRING ) {
2270 char* subpred = jsonObjectToSimpleString( node );
2271 buffer_fadd(sql_buf, " \"%s\".%s ", search_itr->key + 1, subpred);
2274 char* subpred = searchWHERE( node, osrfHashGet( oilsIDL(), search_itr->key + 1 ), AND_OP_JOIN, ctx );
2275 buffer_fadd(sql_buf, "( %s )", subpred);
2278 } else if ( !strcasecmp("-or",search_itr->key) ) {
2279 char* subpred = searchWHERE( node, meta, OR_OP_JOIN, ctx );
2280 buffer_fadd(sql_buf, "( %s )", subpred);
2282 } else if ( !strcasecmp("-and",search_itr->key) ) {
2283 char* subpred = searchWHERE( node, meta, AND_OP_JOIN, ctx );
2284 buffer_fadd(sql_buf, "( %s )", subpred);
2286 } else if ( !strcasecmp("-exists",search_itr->key) ) {
2287 char* subpred = SELECT(
2289 jsonObjectGetKey( node, "select" ),
2290 jsonObjectGetKey( node, "from" ),
2291 jsonObjectGetKey( node, "where" ),
2292 jsonObjectGetKey( node, "having" ),
2293 jsonObjectGetKey( node, "order_by" ),
2294 jsonObjectGetKey( node, "limit" ),
2295 jsonObjectGetKey( node, "offset" ),
2299 buffer_fadd(sql_buf, "EXISTS ( %s )", subpred);
2301 } else if ( !strcasecmp("-not-exists",search_itr->key) ) {
2302 char* subpred = SELECT(
2304 jsonObjectGetKey( node, "select" ),
2305 jsonObjectGetKey( node, "from" ),
2306 jsonObjectGetKey( node, "where" ),
2307 jsonObjectGetKey( node, "having" ),
2308 jsonObjectGetKey( node, "order_by" ),
2309 jsonObjectGetKey( node, "limit" ),
2310 jsonObjectGetKey( node, "offset" ),
2314 buffer_fadd(sql_buf, "NOT EXISTS ( %s )", subpred);
2318 char* class = osrfHashGet(meta, "classname");
2319 osrfHash* fields = osrfHashGet(meta, "fields");
2320 osrfHash* field = osrfHashGet( fields, search_itr->key );
2324 char* table = getSourceDefinition(meta);
2327 "%s: Attempt to reference non-existent column %s on %s (%s)",
2333 buffer_free(sql_buf);
2335 jsonIteratorFree(search_itr);
2339 char* subpred = searchPredicate( class, field, node, ctx );
2340 buffer_add( sql_buf, subpred );
2344 jsonIteratorFree(search_itr);
2347 // ERROR ... only hash and array allowed at this level
2348 char* predicate_string = jsonObjectToJSON( search_hash );
2351 "%s: Invalid predicate structure: %s",
2355 buffer_free(sql_buf);
2356 free(predicate_string);
2361 return buffer_release(sql_buf);
2365 /* method context */ osrfMethodContext* ctx,
2367 /* SELECT */ jsonObject* selhash,
2368 /* FROM */ jsonObject* join_hash,
2369 /* WHERE */ jsonObject* search_hash,
2370 /* HAVING */ jsonObject* having_hash,
2371 /* ORDER BY */ jsonObject* order_hash,
2372 /* LIMIT */ jsonObject* limit,
2373 /* OFFSET */ jsonObject* offset,
2374 /* flags */ int flags
2376 const char* locale = osrf_message_get_last_locale();
2378 // in case we don't get a select list
2379 jsonObject* defaultselhash = NULL;
2381 // general tmp objects
2382 const jsonObject* tmp_const;
2383 jsonObject* selclass = NULL;
2384 jsonObject* selfield = NULL;
2385 jsonObject* snode = NULL;
2386 jsonObject* onode = NULL;
2388 char* string = NULL;
2389 int from_function = 0;
2394 // the core search class
2395 char* core_class = NULL;
2397 // metadata about the core search class
2398 osrfHash* core_meta = NULL;
2400 // punt if there's no core class
2401 if (!join_hash || ( join_hash->type == JSON_HASH && !join_hash->size ))
2404 // get the core class -- the only key of the top level FROM clause, or a string
2405 if (join_hash->type == JSON_HASH) {
2406 jsonIterator* tmp_itr = jsonNewIterator( join_hash );
2407 snode = jsonIteratorNext( tmp_itr );
2409 core_class = strdup( tmp_itr->key );
2412 jsonObject* extra = jsonIteratorNext( tmp_itr );
2414 jsonIteratorFree( tmp_itr );
2417 // There shouldn't be more than one entry in join_hash
2419 return NULL; // Malformed join_hash; extra entry
2421 } else if (join_hash->type == JSON_ARRAY) {
2423 core_class = jsonObjectToSimpleString( jsonObjectGetIndex(join_hash, 0) );
2426 } else if (join_hash->type == JSON_STRING) {
2427 core_class = jsonObjectToSimpleString( join_hash );
2433 // punt if we don't know about the core class (and it's not a function)
2434 if (!from_function && !(core_meta = osrfHashGet( oilsIDL(), core_class ))) {
2439 // if the select list is empty, or the core class field list is '*',
2440 // build the default select list ...
2442 selhash = defaultselhash = jsonNewObjectType(JSON_HASH);
2443 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2444 } else if ( (tmp_const = jsonObjectGetKeyConst( selhash, core_class )) && tmp_const->type == JSON_STRING ) {
2445 char* _x = jsonObjectToSimpleString( tmp_const );
2446 if (!strncmp( "*", _x, 1 )) {
2447 jsonObjectRemoveKey( selhash, core_class );
2448 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2454 growing_buffer* sql_buf = buffer_init(128);
2456 // temp buffer for the SELECT list
2457 growing_buffer* select_buf = buffer_init(128);
2458 growing_buffer* order_buf = buffer_init(128);
2459 growing_buffer* group_buf = buffer_init(128);
2460 growing_buffer* having_buf = buffer_init(128);
2462 // Build a select list
2463 if(from_function) // From a function we select everything
2464 OSRF_BUFFER_ADD_CHAR( select_buf, '*' );
2467 // If we need to build a default list, do so
2468 jsonObject* _tmp = jsonObjectGetKey( selhash, core_class );
2469 if ( _tmp && !_tmp->size ) {
2473 osrfHash* core_fields = osrfHashGet( core_meta, "fields" );
2475 osrfStringArray* keys = osrfHashKeys( core_fields );
2476 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
2477 if( ! str_is_true( osrfHashGet( osrfHashGet( core_fields, field ), "virtual" ) ) )
2478 jsonObjectPush( _tmp, jsonNewObject( field ) ); // not virtual; use it
2480 osrfStringArrayFree(keys);
2483 // Now build the actual select list
2485 jsonObject* is_agg = jsonObjectFindPath(selhash, "//aggregate");
2488 jsonIterator* selclass_itr = jsonNewIterator( selhash );
2489 while ( (selclass = jsonIteratorNext( selclass_itr )) ) { // For each class
2491 // round trip through the idl, just to be safe
2492 const char* cname = selclass_itr->key;
2493 osrfHash* idlClass = osrfHashGet( oilsIDL(), cname );
2495 // No such class. Skip it.
2498 // Make sure the target relation is in the join tree.
2500 // At this point join_hash is a step down from the join_hash we
2501 // received as a parameter. If the original was a JSON_STRING,
2502 // then json_hash is now NULL. If the original was a JSON_HASH,
2503 // then json_hash is now the first (and only) entry in it,
2504 // denoting the core class. We've already excluded the
2505 // possibility that the original was a JSON_ARRAY, because in
2506 // that case from_function would be non-NULL, and we wouldn't
2509 if ( strcmp( core_class, cname )) {
2511 // There's only one class in the FROM clause,
2512 // and this isn't it. Skip it.
2515 if (join_hash->type == JSON_STRING) {
2516 string = jsonObjectToSimpleString(join_hash);
2517 int different = strcmp( string, cname );
2520 // There's only one class in the FROM clause,
2521 // and this isn't it. Skip it.
2524 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", cname);
2525 unsigned long size = found->size;
2526 jsonObjectFree( found );
2528 // No such class anywhere in the join tree. Skip it.
2533 // Look up some attributes of the current class, so that we
2534 // don't have to look them up again for each field
2535 osrfHash* class_field_set = osrfHashGet( idlClass, "fields" );
2536 char* class_pkey = osrfHashGet( idlClass, "primarykey" );
2537 char* class_tname = osrfHashGet( idlClass, "tablename" );
2539 // stitch together the column list ...
2540 jsonIterator* select_itr = jsonNewIterator( selclass );
2541 while ( (selfield = jsonIteratorNext( select_itr )) ) { // for each SELECT column
2543 // If we need a separator comma, add one
2547 OSRF_BUFFER_ADD_CHAR( select_buf, ',' );
2550 // ... if it's a string, just toss it on the pile
2551 if (selfield->type == JSON_STRING) {
2553 // again, just to be safe
2554 const char* _requested_col = selfield->value.s;
2555 osrfHash* field = osrfHashGet( class_field_set, _requested_col );
2556 if (!field) continue; // No such field in current class; skip it
2558 const char* col_name = osrfHashGet(field, "name");
2562 if (flags & DISABLE_I18N)
2565 i18n = osrfHashGet(field, "i18n");
2567 if( str_is_true( i18n ) ) {
2568 buffer_fadd( select_buf,
2569 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2570 class_tname, cname, col_name, class_pkey, cname, class_pkey, locale, col_name );
2572 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2575 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2578 // ... but it could be an object, in which case we check for a Field Transform
2581 char* _column = jsonObjectToSimpleString( jsonObjectGetKeyConst( selfield, "column" ) );
2583 // Get the field definition from the IDL
2584 osrfHash* field = osrfHashGet( class_field_set, _column );
2585 if (!field) continue; // No such field defined in IDL. Skip it.
2587 // Decide what to use as a column alias
2589 if ((tmp_const = jsonObjectGetKeyConst( selfield, "alias" ))) {
2590 _alias = jsonObjectToSimpleString( tmp_const );
2592 } else { // Use column name as its own alias
2595 _column = NULL; // To emphasize that we're through with _column
2597 if (jsonObjectGetKeyConst( selfield, "transform" )) {
2598 char* transform_str = searchFieldTransform(cname, field, selfield);
2599 buffer_fadd(select_buf, " %s AS \"%s\"", transform_str, _alias);
2600 free(transform_str);
2603 const char* fname = osrfHashGet(field, "name");
2607 if (flags & DISABLE_I18N)
2610 i18n = osrfHashGet(field, "i18n");
2612 if( str_is_true( i18n ) ) {
2613 buffer_fadd( select_buf,
2614 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2615 class_tname, cname, fname, class_pkey, cname, class_pkey, locale, _alias);
2617 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, fname, _alias);
2620 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, fname, _alias);
2627 if (is_agg->size || (flags & SELECT_DISTINCT)) {
2629 const jsonObject* aggregate_obj = jsonObjectGetKey( selfield, "aggregate" );
2630 if ( ! obj_is_true( aggregate_obj ) ) {
2634 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
2637 buffer_fadd(group_buf, " %d", sel_pos);
2639 } else if (is_agg = jsonObjectGetKey( selfield, "having" )) {
2643 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
2646 _column = searchFieldTransform(cname, field, selfield);
2647 OSRF_BUFFER_ADD_CHAR(group_buf, ' ');
2648 OSRF_BUFFER_ADD(group_buf, _column);
2649 _column = searchFieldTransform(cname, field, selfield);
2655 } // end while -- iterating across SELECT columns
2657 jsonIteratorFree(select_itr);
2658 } // end while -- iterating across classes
2660 jsonIteratorFree(selclass_itr);
2662 if (is_agg) jsonObjectFree(is_agg);
2666 char* col_list = buffer_release(select_buf);
2668 if (from_function) table = searchValueTransform(join_hash);
2669 else table = getSourceDefinition(core_meta);
2671 // Put it all together
2672 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\" ", col_list, table, core_class );
2676 if (!from_function) {
2677 // Now, walk the join tree and add that clause
2679 char* join_clause = searchJOIN( join_hash, core_meta );
2680 buffer_add(sql_buf, join_clause);
2684 // Build a WHERE clause, if there is one
2685 if ( search_hash ) {
2686 buffer_add(sql_buf, " WHERE ");
2688 // and it's on the WHERE clause
2689 char* pred = searchWHERE( search_hash, core_meta, AND_OP_JOIN, ctx );
2692 buffer_add(sql_buf, pred);
2696 osrfAppSessionStatus(
2698 OSRF_STATUS_INTERNALSERVERERROR,
2699 "osrfMethodException",
2701 "Severe query error in WHERE predicate -- see error log for more details"
2705 buffer_free(having_buf);
2706 buffer_free(group_buf);
2707 buffer_free(order_buf);
2708 buffer_free(sql_buf);
2709 if (defaultselhash) jsonObjectFree(defaultselhash);
2714 // Build a HAVING clause, if there is one
2715 if ( having_hash ) {
2716 buffer_add(sql_buf, " HAVING ");
2718 // and it's on the the WHERE clause
2719 char* pred = searchWHERE( having_hash, core_meta, AND_OP_JOIN, ctx );
2722 buffer_add(sql_buf, pred);
2726 osrfAppSessionStatus(
2728 OSRF_STATUS_INTERNALSERVERERROR,
2729 "osrfMethodException",
2731 "Severe query error in HAVING predicate -- see error log for more details"
2735 buffer_free(having_buf);
2736 buffer_free(group_buf);
2737 buffer_free(order_buf);
2738 buffer_free(sql_buf);
2739 if (defaultselhash) jsonObjectFree(defaultselhash);
2744 // Build an ORDER BY clause, if there is one
2746 jsonIterator* class_itr = jsonNewIterator( order_hash );
2747 while ( (snode = jsonIteratorNext( class_itr )) ) {
2749 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
2752 if ( snode->type == JSON_HASH ) {
2754 jsonIterator* order_itr = jsonNewIterator( snode );
2755 while ( (onode = jsonIteratorNext( order_itr )) ) {
2757 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
2760 char* direction = NULL;
2761 if ( onode->type == JSON_HASH ) {
2762 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
2763 string = searchFieldTransform(
2765 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
2769 growing_buffer* field_buf = buffer_init(16);
2770 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
2771 string = buffer_release(field_buf);
2774 if ( (tmp_const = jsonObjectGetKeyConst( onode, "direction" )) ) {
2775 direction = jsonObjectToSimpleString(tmp_const);
2776 if (!strncasecmp(direction, "d", 1)) {
2778 direction = " DESC";
2786 string = strdup(order_itr->key);
2787 direction = jsonObjectToSimpleString(onode);
2788 if (!strncasecmp(direction, "d", 1)) {
2790 direction = " DESC";
2800 buffer_add(order_buf, ", ");
2803 buffer_add(order_buf, string);
2807 buffer_add(order_buf, direction);
2811 // jsonIteratorFree(order_itr);
2813 } else if ( snode->type == JSON_ARRAY ) {
2815 jsonIterator* order_itr = jsonNewIterator( snode );
2816 while ( (onode = jsonIteratorNext( order_itr )) ) {
2818 char* _f = jsonObjectToSimpleString( onode );
2820 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, _f))
2826 buffer_add(order_buf, ", ");
2829 buffer_add(order_buf, _f);
2833 // jsonIteratorFree(order_itr);
2836 // IT'S THE OOOOOOOOOOOLD STYLE!
2838 osrfLogError(OSRF_LOG_MARK, "%s: Possible SQL injection attempt; direct order by is not allowed", MODULENAME);
2840 osrfAppSessionStatus(
2842 OSRF_STATUS_INTERNALSERVERERROR,
2843 "osrfMethodException",
2845 "Severe query error -- see error log for more details"
2850 buffer_free(having_buf);
2851 buffer_free(group_buf);
2852 buffer_free(order_buf);
2853 buffer_free(sql_buf);
2854 if (defaultselhash) jsonObjectFree(defaultselhash);
2855 jsonIteratorFree(class_itr);
2860 // jsonIteratorFree(class_itr);
2864 string = buffer_release(group_buf);
2866 if (strlen(string)) {
2867 OSRF_BUFFER_ADD( sql_buf, " GROUP BY " );
2868 OSRF_BUFFER_ADD( sql_buf, string );
2873 string = buffer_release(having_buf);
2875 if (strlen(string)) {
2876 OSRF_BUFFER_ADD( sql_buf, " HAVING " );
2877 OSRF_BUFFER_ADD( sql_buf, string );
2882 string = buffer_release(order_buf);
2884 if (strlen(string)) {
2885 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
2886 OSRF_BUFFER_ADD( sql_buf, string );
2892 string = jsonObjectToSimpleString(limit);
2893 buffer_fadd( sql_buf, " LIMIT %d", atoi(string) );
2898 string = jsonObjectToSimpleString(offset);
2899 buffer_fadd( sql_buf, " OFFSET %d", atoi(string) );
2903 if (!(flags & SUBSELECT)) OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
2906 if (defaultselhash) jsonObjectFree(defaultselhash);
2908 return buffer_release(sql_buf);
2912 static char* buildSELECT ( jsonObject* search_hash, jsonObject* order_hash, osrfHash* meta, osrfMethodContext* ctx ) {
2914 const char* locale = osrf_message_get_last_locale();
2916 osrfHash* fields = osrfHashGet(meta, "fields");
2917 char* core_class = osrfHashGet(meta, "classname");
2919 const jsonObject* join_hash = jsonObjectGetKeyConst( order_hash, "join" );
2921 jsonObject* node = NULL;
2922 jsonObject* snode = NULL;
2923 jsonObject* onode = NULL;
2924 const jsonObject* _tmp = NULL;
2925 jsonObject* selhash = NULL;
2926 jsonObject* defaultselhash = NULL;
2928 growing_buffer* sql_buf = buffer_init(128);
2929 growing_buffer* select_buf = buffer_init(128);
2931 if ( !(selhash = jsonObjectGetKey( order_hash, "select" )) ) {
2932 defaultselhash = jsonNewObjectType(JSON_HASH);
2933 selhash = defaultselhash;
2936 if ( !jsonObjectGetKeyConst(selhash,core_class) ) {
2937 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2938 jsonObject* flist = jsonObjectGetKey( selhash, core_class );
2943 osrfStringArray* keys = osrfHashKeys( fields );
2944 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
2945 if( ! str_is_true( osrfHashGet( osrfHashGet( fields, field ), "virtual" ) ) )
2946 jsonObjectPush( flist, jsonNewObject( field ) );
2948 osrfStringArrayFree(keys);
2952 jsonIterator* class_itr = jsonNewIterator( selhash );
2953 while ( (snode = jsonIteratorNext( class_itr )) ) {
2955 osrfHash* idlClass = osrfHashGet( oilsIDL(), class_itr->key );
2956 if (!idlClass) continue;
2957 char* cname = osrfHashGet(idlClass, "classname");
2959 if (strcmp(core_class,class_itr->key)) {
2960 if (!join_hash) continue;
2962 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", class_itr->key);
2964 jsonObjectFree(found);
2968 jsonObjectFree(found);
2971 jsonIterator* select_itr = jsonNewIterator( snode );
2972 while ( (node = jsonIteratorNext( select_itr )) ) {
2973 char* item_str = jsonObjectToSimpleString(node);
2974 osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), item_str );
2976 char* fname = osrfHashGet(field, "name");
2978 if (!field) continue;
2983 OSRF_BUFFER_ADD_CHAR(select_buf, ',');
2988 const jsonObject* no_i18n_obj = jsonObjectGetKey( order_hash, "no_i18n" );
2989 if ( obj_is_true( no_i18n_obj ) ) // Suppress internationalization?
2992 i18n = osrfHashGet(field, "i18n");
2994 if( str_is_true( i18n ) ) {
2995 char* pkey = osrfHashGet(idlClass, "primarykey");
2996 char* tname = osrfHashGet(idlClass, "tablename");
2998 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);
3000 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
3003 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
3007 jsonIteratorFree(select_itr);
3010 jsonIteratorFree(class_itr);
3012 char* col_list = buffer_release(select_buf);
3013 char* table = getSourceDefinition(meta);
3015 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\"", col_list, table, core_class );
3020 char* join_clause = searchJOIN( join_hash, meta );
3021 OSRF_BUFFER_ADD_CHAR(sql_buf, ' ');
3022 OSRF_BUFFER_ADD(sql_buf, join_clause);
3026 osrfLogDebug(OSRF_LOG_MARK, "%s pre-predicate SQL = %s",
3027 MODULENAME, OSRF_BUFFER_C_STR(sql_buf));
3029 buffer_add(sql_buf, " WHERE ");
3031 char* pred = searchWHERE( search_hash, meta, AND_OP_JOIN, ctx );
3033 osrfAppSessionStatus(
3035 OSRF_STATUS_INTERNALSERVERERROR,
3036 "osrfMethodException",
3038 "Severe query error -- see error log for more details"
3040 buffer_free(sql_buf);
3041 if(defaultselhash) jsonObjectFree(defaultselhash);
3044 buffer_add(sql_buf, pred);
3049 char* string = NULL;
3050 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "order_by" )) ){
3052 growing_buffer* order_buf = buffer_init(128);
3055 jsonIterator* class_itr = jsonNewIterator( _tmp );
3056 while ( (snode = jsonIteratorNext( class_itr )) ) {
3058 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
3061 if ( snode->type == JSON_HASH ) {
3063 jsonIterator* order_itr = jsonNewIterator( snode );
3064 while ( (onode = jsonIteratorNext( order_itr )) ) {
3066 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
3069 char* direction = NULL;
3070 if ( onode->type == JSON_HASH ) {
3071 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
3072 string = searchFieldTransform(
3074 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
3078 growing_buffer* field_buf = buffer_init(16);
3079 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
3080 string = buffer_release(field_buf);
3083 if ( (_tmp = jsonObjectGetKeyConst( onode, "direction" )) ) {
3084 direction = jsonObjectToSimpleString(_tmp);
3085 if (!strncasecmp(direction, "d", 1)) {
3087 direction = " DESC";
3095 string = strdup(order_itr->key);
3096 direction = jsonObjectToSimpleString(onode);
3097 if (!strncasecmp(direction, "d", 1)) {
3099 direction = " DESC";
3109 buffer_add(order_buf, ", ");
3112 buffer_add(order_buf, string);
3116 buffer_add(order_buf, direction);
3121 jsonIteratorFree(order_itr);
3124 string = jsonObjectToSimpleString(snode);
3125 buffer_add(order_buf, string);
3132 jsonIteratorFree(class_itr);
3134 string = buffer_release(order_buf);
3136 if (strlen(string)) {
3137 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
3138 OSRF_BUFFER_ADD( sql_buf, string );
3144 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "limit" )) ){
3145 string = jsonObjectToSimpleString(_tmp);
3154 _tmp = jsonObjectGetKeyConst( order_hash, "offset" );
3156 string = jsonObjectToSimpleString(_tmp);
3166 if (defaultselhash) jsonObjectFree(defaultselhash);
3168 OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
3169 return buffer_release(sql_buf);
3172 int doJSONSearch ( osrfMethodContext* ctx ) {
3173 if(osrfMethodVerifyContext( ctx )) {
3174 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
3178 osrfLogDebug(OSRF_LOG_MARK, "Recieved query request");
3183 dbhandle = writehandle;
3185 jsonObject* hash = jsonObjectGetIndex(ctx->params, 0);
3189 if ( obj_is_true( jsonObjectGetKey( hash, "distinct" ) ) )
3190 flags |= SELECT_DISTINCT;
3192 if ( obj_is_true( jsonObjectGetKey( hash, "no_i18n" ) ) )
3193 flags |= DISABLE_I18N;
3195 osrfLogDebug(OSRF_LOG_MARK, "Building SQL ...");
3198 jsonObjectGetKey( hash, "select" ),
3199 jsonObjectGetKey( hash, "from" ),
3200 jsonObjectGetKey( hash, "where" ),
3201 jsonObjectGetKey( hash, "having" ),
3202 jsonObjectGetKey( hash, "order_by" ),
3203 jsonObjectGetKey( hash, "limit" ),
3204 jsonObjectGetKey( hash, "offset" ),
3213 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3214 dbi_result result = dbi_conn_query(dbhandle, sql);
3217 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3219 if (dbi_result_first_row(result)) {
3220 /* JSONify the result */
3221 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3224 jsonObject* return_val = oilsMakeJSONFromResult( result );
3225 osrfAppRespond( ctx, return_val );
3226 jsonObjectFree( return_val );
3227 } while (dbi_result_next_row(result));
3230 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
3233 osrfAppRespondComplete( ctx, NULL );
3235 /* clean up the query */
3236 dbi_result_free(result);
3240 osrfLogError(OSRF_LOG_MARK, "%s: Error with query [%s]", MODULENAME, sql);
3241 osrfAppSessionStatus(
3243 OSRF_STATUS_INTERNALSERVERERROR,
3244 "osrfMethodException",
3246 "Severe query error -- see error log for more details"
3254 static jsonObject* doFieldmapperSearch ( osrfMethodContext* ctx, osrfHash* meta,
3255 const jsonObject* params, int* err ) {
3258 dbhandle = writehandle;
3260 osrfHash* links = osrfHashGet(meta, "links");
3261 osrfHash* fields = osrfHashGet(meta, "fields");
3262 char* core_class = osrfHashGet(meta, "classname");
3263 char* pkey = osrfHashGet(meta, "primarykey");
3265 const jsonObject* _tmp;
3267 jsonObject* search_hash = jsonObjectGetIndex(params, 0);
3268 jsonObject* order_hash = jsonObjectGetIndex(params, 1);
3270 char* sql = buildSELECT( search_hash, order_hash, meta, ctx );
3272 osrfLogDebug(OSRF_LOG_MARK, "Problem building query, returning NULL");
3277 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3279 dbi_result result = dbi_conn_query(dbhandle, sql);
3280 if( NULL == result ) {
3281 osrfLogError(OSRF_LOG_MARK, "%s: Error retrieving %s with query [%s]",
3282 MODULENAME, osrfHashGet(meta, "fieldmapper"), sql);
3283 osrfAppSessionStatus(
3285 OSRF_STATUS_INTERNALSERVERERROR,
3286 "osrfMethodException",
3288 "Severe query error -- see error log for more details"
3295 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3298 jsonObject* res_list = jsonNewObjectType(JSON_ARRAY);
3299 osrfHash* dedup = osrfNewHash();
3301 if (dbi_result_first_row(result)) {
3302 /* JSONify the result */
3303 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3305 obj = oilsMakeFieldmapperFromResult( result, meta );
3306 char* pkey_val = oilsFMGetString( obj, pkey );
3307 if ( osrfHashGet( dedup, pkey_val ) ) {
3308 jsonObjectFree(obj);
3311 osrfHashSet( dedup, pkey_val, pkey_val );
3312 jsonObjectPush(res_list, obj);
3314 } while (dbi_result_next_row(result));
3316 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s",
3320 osrfHashFree(dedup);
3321 /* clean up the query */
3322 dbi_result_free(result);
3325 if (res_list->size && order_hash) {
3326 _tmp = jsonObjectGetKeyConst( order_hash, "flesh" );
3328 int x = (int)jsonObjectGetNumber(_tmp);
3329 if (x == -1 || x > max_flesh_depth) x = max_flesh_depth;
3331 const jsonObject* temp_blob;
3332 if ((temp_blob = jsonObjectGetKeyConst( order_hash, "flesh_fields" )) && x > 0) {
3334 jsonObject* flesh_blob = jsonObjectClone( temp_blob );
3335 const jsonObject* flesh_fields = jsonObjectGetKeyConst( flesh_blob, core_class );
3337 osrfStringArray* link_fields = NULL;
3340 if (flesh_fields->size == 1) {
3341 char* _t = jsonObjectToSimpleString( jsonObjectGetIndex( flesh_fields, 0 ) );
3342 if (!strcmp(_t,"*")) link_fields = osrfHashKeys( links );
3348 link_fields = osrfNewStringArray(1);
3349 jsonIterator* _i = jsonNewIterator( flesh_fields );
3350 while ((_f = jsonIteratorNext( _i ))) {
3351 osrfStringArrayAdd( link_fields, jsonObjectToSimpleString( _f ) );
3353 jsonIteratorFree(_i);
3358 jsonIterator* itr = jsonNewIterator( res_list );
3359 while ((cur = jsonIteratorNext( itr ))) {
3364 while ( (link_field = osrfStringArrayGetString(link_fields, i++)) ) {
3366 osrfLogDebug(OSRF_LOG_MARK, "Starting to flesh %s", link_field);
3368 osrfHash* kid_link = osrfHashGet(links, link_field);
3369 if (!kid_link) continue;
3371 osrfHash* field = osrfHashGet(fields, link_field);
3372 if (!field) continue;
3374 osrfHash* value_field = field;
3376 osrfHash* kid_idl = osrfHashGet(oilsIDL(), osrfHashGet(kid_link, "class"));
3377 if (!kid_idl) continue;
3379 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3380 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3383 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) { // might_have
3384 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3387 osrfStringArray* link_map = osrfHashGet( kid_link, "map" );
3389 if (link_map->size > 0) {
3390 jsonObject* _kid_key = jsonNewObjectType(JSON_ARRAY);
3393 jsonNewObject( osrfStringArrayGetString( link_map, 0 ) )
3398 osrfHashGet(kid_link, "class"),
3405 "Link field: %s, remote class: %s, fkey: %s, reltype: %s",
3406 osrfHashGet(kid_link, "field"),
3407 osrfHashGet(kid_link, "class"),
3408 osrfHashGet(kid_link, "key"),
3409 osrfHashGet(kid_link, "reltype")
3412 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
3413 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // search hash
3414 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // order/flesh hash
3416 osrfLogDebug(OSRF_LOG_MARK, "Creating dummy params object...");
3419 jsonObjectToSimpleString(
3422 atoi( osrfHashGet(value_field, "array_position") )
3427 osrfLogDebug(OSRF_LOG_MARK, "Nothing to search for!");
3432 jsonObjectGetIndex(fake_params, 0),
3433 osrfHashGet(kid_link, "key"),
3434 jsonNewObject( search_key )
3441 jsonObjectGetIndex(fake_params, 1),
3443 jsonNewNumberObject( (double)(x - 1 + link_map->size) )
3447 jsonObjectSetKey( jsonObjectGetIndex(fake_params, 1), "flesh_fields", jsonObjectClone(flesh_blob) );
3449 if (jsonObjectGetKeyConst(order_hash, "order_by")) {
3451 jsonObjectGetIndex(fake_params, 1),
3453 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "order_by"))
3457 if (jsonObjectGetKeyConst(order_hash, "select")) {
3459 jsonObjectGetIndex(fake_params, 1),
3461 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "select"))
3465 jsonObject* kids = doFieldmapperSearch(ctx, kid_idl, fake_params, err);
3468 jsonObjectFree( fake_params );
3469 osrfStringArrayFree(link_fields);
3470 jsonIteratorFree(itr);
3471 jsonObjectFree(res_list);
3472 jsonObjectFree(flesh_blob);
3476 osrfLogDebug(OSRF_LOG_MARK, "Search for %s return %d linked objects", osrfHashGet(kid_link, "class"), kids->size);
3478 jsonObject* X = NULL;
3479 if ( link_map->size > 0 && kids->size > 0 ) {
3481 kids = jsonNewObjectType(JSON_ARRAY);
3483 jsonObject* _k_node;
3484 jsonIterator* _k = jsonNewIterator( X );
3485 while ((_k_node = jsonIteratorNext( _k ))) {
3491 (unsigned long)atoi(
3497 osrfHashGet(kid_link, "class")
3501 osrfStringArrayGetString( link_map, 0 )
3510 jsonIteratorFree(_k);
3513 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_a" )) || !(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) {
3514 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3517 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3518 jsonObjectClone( jsonObjectGetIndex(kids, 0) )
3522 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3523 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3526 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3527 jsonObjectClone( kids )
3532 jsonObjectFree(kids);
3536 jsonObjectFree( kids );
3537 jsonObjectFree( fake_params );
3539 osrfLogDebug(OSRF_LOG_MARK, "Fleshing of %s complete", osrfHashGet(kid_link, "field"));
3540 osrfLogDebug(OSRF_LOG_MARK, "%s", jsonObjectToJSON(cur));
3544 jsonObjectFree( flesh_blob );
3545 osrfStringArrayFree(link_fields);
3546 jsonIteratorFree(itr);
3555 static jsonObject* doUpdate(osrfMethodContext* ctx, int* err ) {
3557 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3559 jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
3561 jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
3564 if (!verifyObjectClass(ctx, target)) {
3569 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3570 osrfAppSessionStatus(
3572 OSRF_STATUS_BADREQUEST,
3573 "osrfMethodException",
3575 "No active transaction -- required for UPDATE"
3581 // The following test is harmless but redundant. If a class is
3582 // readonly, we don't register an update method for it.
3583 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
3584 osrfAppSessionStatus(
3586 OSRF_STATUS_BADREQUEST,
3587 "osrfMethodException",
3589 "Cannot UPDATE readonly class"
3595 dbhandle = writehandle;
3597 char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
3599 // Set the last_xact_id
3600 int index = oilsIDL_ntop( target->classname, "last_xact_id" );
3602 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
3603 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
3606 char* pkey = osrfHashGet(meta, "primarykey");
3607 osrfHash* fields = osrfHashGet(meta, "fields");
3609 char* id = oilsFMGetString( target, pkey );
3613 "%s updating %s object with %s = %s",
3615 osrfHashGet(meta, "fieldmapper"),
3620 growing_buffer* sql = buffer_init(128);
3621 buffer_fadd(sql,"UPDATE %s SET", osrfHashGet(meta, "tablename"));
3626 osrfStringArray* field_list = osrfHashKeys( fields );
3627 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
3629 osrfHash* field = osrfHashGet( fields, field_name );
3631 if(!( strcmp( field_name, pkey ) )) continue;
3632 if( str_is_true( osrfHashGet(osrfHashGet(fields,field_name), "virtual") ) )
3635 const jsonObject* field_object = oilsFMGetObject( target, field_name );
3638 if (field_object && field_object->classname) {
3639 value = oilsFMGetString(
3641 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
3644 value = jsonObjectToSimpleString( field_object );
3647 osrfLogDebug( OSRF_LOG_MARK, "Updating %s object with %s = %s", osrfHashGet(meta, "fieldmapper"), field_name, value);
3649 if (!field_object || field_object->type == JSON_NULL) {
3650 if ( !(!( strcmp( osrfHashGet(meta, "classname"), "au" ) ) && !( strcmp( field_name, "passwd" ) )) ) { // arg at the special case!
3651 if (first) first = 0;
3652 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3653 buffer_fadd( sql, " %s = NULL", field_name );
3656 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
3657 if (first) first = 0;
3658 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3660 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
3661 buffer_fadd( sql, " %s = %ld", field_name, atol(value) );
3662 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
3663 buffer_fadd( sql, " %s = %f", field_name, atof(value) );
3666 osrfLogDebug( OSRF_LOG_MARK, "%s is of type %s", field_name, osrfHashGet(field, "datatype"));
3669 if ( dbi_conn_quote_string(dbhandle, &value) ) {
3670 if (first) first = 0;
3671 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3672 buffer_fadd( sql, " %s = %s", field_name, value );
3675 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
3676 osrfAppSessionStatus(
3678 OSRF_STATUS_INTERNALSERVERERROR,
3679 "osrfMethodException",
3681 "Error quoting string -- please see the error log for more details"
3695 jsonObject* obj = jsonNewObject(id);
3697 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
3698 dbi_conn_quote_string(dbhandle, &id);
3700 buffer_fadd( sql, " WHERE %s = %s;", pkey, id );
3702 char* query = buffer_release(sql);
3703 osrfLogDebug(OSRF_LOG_MARK, "%s: Update SQL [%s]", MODULENAME, query);
3705 dbi_result result = dbi_conn_query(dbhandle, query);
3709 jsonObjectFree(obj);
3710 obj = jsonNewObject(NULL);
3713 "%s ERROR updating %s object with %s = %s",
3715 osrfHashGet(meta, "fieldmapper"),
3726 static jsonObject* doDelete(osrfMethodContext* ctx, int* err ) {
3728 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3730 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3731 osrfAppSessionStatus(
3733 OSRF_STATUS_BADREQUEST,
3734 "osrfMethodException",
3736 "No active transaction -- required for DELETE"
3742 // The following test is harmless but redundant. If a class is
3743 // readonly, we don't register a delete method for it.
3744 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
3745 osrfAppSessionStatus(
3747 OSRF_STATUS_BADREQUEST,
3748 "osrfMethodException",
3750 "Cannot DELETE readonly class"
3756 dbhandle = writehandle;
3760 char* pkey = osrfHashGet(meta, "primarykey");
3768 if (jsonObjectGetIndex(ctx->params, _obj_pos)->classname) {
3769 if (!verifyObjectClass(ctx, jsonObjectGetIndex( ctx->params, _obj_pos ))) {
3774 id = oilsFMGetString( jsonObjectGetIndex(ctx->params, _obj_pos), pkey );
3777 if (!verifyObjectPCRUD( ctx, NULL )) {
3782 id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, _obj_pos));
3787 "%s deleting %s object with %s = %s",
3789 osrfHashGet(meta, "fieldmapper"),
3794 obj = jsonNewObject(id);
3796 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
3797 dbi_conn_quote_string(writehandle, &id);
3799 dbi_result result = dbi_conn_queryf(writehandle, "DELETE FROM %s WHERE %s = %s;", osrfHashGet(meta, "tablename"), pkey, id);
3802 jsonObjectFree(obj);
3803 obj = jsonNewObject(NULL);
3806 "%s ERROR deleting %s object with %s = %s",
3808 osrfHashGet(meta, "fieldmapper"),
3821 static jsonObject* oilsMakeFieldmapperFromResult( dbi_result result, osrfHash* meta) {
3822 if(!(result && meta)) return jsonNULL;
3824 jsonObject* object = jsonNewObject(NULL);
3825 jsonObjectSetClass(object, osrfHashGet(meta, "classname"));
3827 osrfHash* fields = osrfHashGet(meta, "fields");
3829 osrfLogInternal(OSRF_LOG_MARK, "Setting object class to %s ", object->classname);
3833 char dt_string[256];
3837 int columnIndex = 1;
3839 unsigned short type;
3840 const char* columnName;
3842 /* cycle through the column list */
3843 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
3845 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
3847 fmIndex = -1; // reset the position
3849 /* determine the field type and storage attributes */
3850 type = dbi_result_get_field_type(result, columnName);
3851 attr = dbi_result_get_field_attribs(result, columnName);
3853 /* fetch the fieldmapper index */
3854 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
3856 if ( str_is_true( osrfHashGet(_f, "virtual") ) )
3859 const char* pos = (char*)osrfHashGet(_f, "array_position");
3860 if ( !pos ) continue;
3862 fmIndex = atoi( pos );
3863 osrfLogInternal(OSRF_LOG_MARK, "... Found column at position [%s]...", pos);
3868 if (dbi_result_field_is_null(result, columnName)) {
3869 jsonObjectSetIndex( object, fmIndex, jsonNewObject(NULL) );
3874 case DBI_TYPE_INTEGER :
3876 if( attr & DBI_INTEGER_SIZE8 )
3877 jsonObjectSetIndex( object, fmIndex,
3878 jsonNewNumberObject(dbi_result_get_longlong(result, columnName)));
3880 jsonObjectSetIndex( object, fmIndex,
3881 jsonNewNumberObject(dbi_result_get_int(result, columnName)));
3885 case DBI_TYPE_DECIMAL :
3886 jsonObjectSetIndex( object, fmIndex,
3887 jsonNewNumberObject(dbi_result_get_double(result, columnName)));
3890 case DBI_TYPE_STRING :
3896 jsonNewObject( dbi_result_get_string(result, columnName) )
3901 case DBI_TYPE_DATETIME :
3903 memset(dt_string, '\0', sizeof(dt_string));
3904 memset(&gmdt, '\0', sizeof(gmdt));
3906 _tmp_dt = dbi_result_get_datetime(result, columnName);
3909 if (!(attr & DBI_DATETIME_DATE)) {
3910 gmtime_r( &_tmp_dt, &gmdt );
3911 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
3912 } else if (!(attr & DBI_DATETIME_TIME)) {
3913 localtime_r( &_tmp_dt, &gmdt );
3914 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
3916 localtime_r( &_tmp_dt, &gmdt );
3917 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
3920 jsonObjectSetIndex( object, fmIndex, jsonNewObject(dt_string) );
3924 case DBI_TYPE_BINARY :
3925 osrfLogError( OSRF_LOG_MARK,
3926 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
3934 static jsonObject* oilsMakeJSONFromResult( dbi_result result ) {
3935 if(!result) return jsonNULL;
3937 jsonObject* object = jsonNewObject(NULL);
3940 char dt_string[256];
3944 int columnIndex = 1;
3946 unsigned short type;
3947 const char* columnName;
3949 /* cycle through the column list */
3950 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
3952 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
3954 fmIndex = -1; // reset the position
3956 /* determine the field type and storage attributes */
3957 type = dbi_result_get_field_type(result, columnName);
3958 attr = dbi_result_get_field_attribs(result, columnName);
3960 if (dbi_result_field_is_null(result, columnName)) {
3961 jsonObjectSetKey( object, columnName, jsonNewObject(NULL) );
3966 case DBI_TYPE_INTEGER :
3968 if( attr & DBI_INTEGER_SIZE8 )
3969 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_longlong(result, columnName)) );
3971 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_int(result, columnName)) );
3974 case DBI_TYPE_DECIMAL :
3975 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_double(result, columnName)) );
3978 case DBI_TYPE_STRING :
3979 jsonObjectSetKey( object, columnName, jsonNewObject(dbi_result_get_string(result, columnName)) );
3982 case DBI_TYPE_DATETIME :
3984 memset(dt_string, '\0', sizeof(dt_string));
3985 memset(&gmdt, '\0', sizeof(gmdt));
3987 _tmp_dt = dbi_result_get_datetime(result, columnName);
3990 if (!(attr & DBI_DATETIME_DATE)) {
3991 gmtime_r( &_tmp_dt, &gmdt );
3992 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
3993 } else if (!(attr & DBI_DATETIME_TIME)) {
3994 localtime_r( &_tmp_dt, &gmdt );
3995 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
3997 localtime_r( &_tmp_dt, &gmdt );
3998 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
4001 jsonObjectSetKey( object, columnName, jsonNewObject(dt_string) );
4004 case DBI_TYPE_BINARY :
4005 osrfLogError( OSRF_LOG_MARK,
4006 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
4014 // Interpret a string as true or false
4015 static int str_is_true( const char* str ) {
4016 if( NULL == str || strcasecmp( str, "true" ) )
4022 // Interpret a jsonObject as true or false
4023 static int obj_is_true( const jsonObject* obj ) {
4026 else switch( obj->type )
4034 if( strcasecmp( obj->value.s, "true" ) )
4038 case JSON_NUMBER : // Support 1/0 for perl's sake
4039 if( jsonObjectGetNumber( obj ) == 1.0 )