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, "Received 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 const char* class = search_itr->key;
2034 osrfHash* idlClass = osrfHashGet( oilsIDL(), class );
2038 "%s: JOIN failed. No class \"%s\" defined in IDL",
2042 jsonIteratorFree( search_itr );
2043 buffer_free( join_buf );
2045 jsonObjectFree( freeable_hash );
2049 char* fkey = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "fkey" ) );
2050 char* field = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "field" ) );
2052 if (field && !fkey) {
2053 fkey = (char*)oilsIDLFindPath("/%s/links/%s/key", class, field);
2057 "%s: JOIN failed. No link defined from %s.%s to %s",
2063 buffer_free(join_buf);
2065 jsonObjectFree(freeable_hash);
2067 jsonIteratorFree(search_itr);
2070 fkey = strdup( fkey );
2072 } else if (!field && fkey) {
2073 field = (char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, fkey );
2077 "%s: JOIN failed. No link defined from %s.%s to %s",
2083 buffer_free(join_buf);
2085 jsonObjectFree(freeable_hash);
2087 jsonIteratorFree(search_itr);
2090 field = strdup( field );
2092 } else if (!field && !fkey) {
2093 osrfHash* _links = oilsIDL_links( leftclass );
2095 // For each link defined for the left class:
2096 // see if the link references the joined class
2097 osrfHashIterator* itr = osrfNewHashIterator( _links );
2098 osrfHash* curr_link = NULL;
2099 while( (curr_link = osrfHashIteratorNext( itr ) ) ) {
2100 const char* other_class = osrfHashGet( curr_link, "class" );
2101 if( other_class && !strcmp( other_class, class ) ) {
2103 // Found a link between the classes
2104 fkey = strdup( osrfHashIteratorKey( itr ) );
2105 const char* other_key = osrfHashGet( curr_link, "key" );
2106 field = other_key ? strdup( other_key ) : NULL;
2110 osrfHashIteratorFree( itr );
2112 if (!field || !fkey) {
2113 // Do another such search, with the classes reversed
2114 _links = oilsIDL_links( class );
2116 // For each link defined for the joined class:
2117 // see if the link references the left class
2118 osrfHashIterator* itr = osrfNewHashIterator( _links );
2119 osrfHash* curr_link = NULL;
2120 while( (curr_link = osrfHashIteratorNext( itr ) ) ) {
2121 const char* other_class = osrfHashGet( curr_link, "class" );
2122 if( other_class && !strcmp( other_class, leftclass ) ) {
2124 // Found a link between the classes
2125 fkey = strdup( osrfHashIteratorKey( itr ) );
2126 const char* other_key = osrfHashGet( curr_link, "key" );
2127 field = other_key ? strdup( other_key ) : NULL;
2131 osrfHashIteratorFree( itr );
2134 if (!field || !fkey) {
2137 "%s: JOIN failed. No link defined between %s and %s",
2142 buffer_free(join_buf);
2144 jsonObjectFree(freeable_hash);
2145 jsonIteratorFree(search_itr);
2151 char* type = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "type" ) );
2153 if ( !strcasecmp(type,"left") ) {
2154 buffer_add(join_buf, " LEFT JOIN");
2155 } else if ( !strcasecmp(type,"right") ) {
2156 buffer_add(join_buf, " RIGHT JOIN");
2157 } else if ( !strcasecmp(type,"full") ) {
2158 buffer_add(join_buf, " FULL JOIN");
2160 buffer_add(join_buf, " INNER JOIN");
2163 buffer_add(join_buf, " INNER JOIN");
2167 char* table = getSourceDefinition(idlClass);
2168 buffer_fadd(join_buf, " %s AS \"%s\" ON ( \"%s\".%s = \"%s\".%s",
2169 table, class, class, field, leftclass, fkey);
2172 const jsonObject* filter = jsonObjectGetKeyConst( snode, "filter" );
2174 char* filter_op = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "filter_op" ) );
2176 if (!strcasecmp("or",filter_op)) {
2177 buffer_add( join_buf, " OR " );
2179 buffer_add( join_buf, " AND " );
2182 buffer_add( join_buf, " AND " );
2185 char* jpred = searchWHERE( filter, idlClass, AND_OP_JOIN, NULL );
2186 OSRF_BUFFER_ADD_CHAR( join_buf, ' ' );
2187 OSRF_BUFFER_ADD( join_buf, jpred );
2192 buffer_add(join_buf, " ) ");
2194 const jsonObject* join_filter = jsonObjectGetKeyConst( snode, "join" );
2196 char* jpred = searchJOIN( join_filter, idlClass );
2197 OSRF_BUFFER_ADD_CHAR( join_buf, ' ' );
2198 OSRF_BUFFER_ADD( join_buf, jpred );
2207 jsonObjectFree(freeable_hash);
2208 jsonIteratorFree(search_itr);
2210 return buffer_release(join_buf);
2215 { +class : { -or|-and : { field : { op : value }, ... } ... }, ... }
2216 { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }
2217 [ { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }, ... ]
2221 static char* searchWHERE ( const jsonObject* search_hash, osrfHash* meta, int opjoin_type, osrfMethodContext* ctx ) {
2225 "%s: Entering searchWHERE; search_hash addr = %p, meta addr = %p, opjoin_type = %d, ctx addr = %p",
2233 growing_buffer* sql_buf = buffer_init(128);
2235 jsonObject* node = NULL;
2238 if ( search_hash->type == JSON_ARRAY ) {
2239 osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_ARRAY", MODULENAME);
2240 jsonIterator* search_itr = jsonNewIterator( search_hash );
2241 while ( (node = jsonIteratorNext( search_itr )) ) {
2245 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2246 else buffer_add(sql_buf, " AND ");
2249 char* subpred = searchWHERE( node, meta, opjoin_type, ctx );
2250 buffer_fadd(sql_buf, "( %s )", subpred);
2253 jsonIteratorFree(search_itr);
2255 } else if ( search_hash->type == JSON_HASH ) {
2256 osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_HASH", MODULENAME);
2257 jsonIterator* search_itr = jsonNewIterator( search_hash );
2258 while ( (node = jsonIteratorNext( search_itr )) ) {
2263 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2264 else buffer_add(sql_buf, " AND ");
2267 if ( !strncmp("+",search_itr->key,1) ) {
2268 if ( node->type == JSON_STRING ) {
2269 char* subpred = jsonObjectToSimpleString( node );
2270 buffer_fadd(sql_buf, " \"%s\".%s ", search_itr->key + 1, subpred);
2273 char* subpred = searchWHERE( node, osrfHashGet( oilsIDL(), search_itr->key + 1 ), AND_OP_JOIN, ctx );
2274 buffer_fadd(sql_buf, "( %s )", subpred);
2277 } else if ( !strcasecmp("-or",search_itr->key) ) {
2278 char* subpred = searchWHERE( node, meta, OR_OP_JOIN, ctx );
2279 buffer_fadd(sql_buf, "( %s )", subpred);
2281 } else if ( !strcasecmp("-and",search_itr->key) ) {
2282 char* subpred = searchWHERE( node, meta, AND_OP_JOIN, ctx );
2283 buffer_fadd(sql_buf, "( %s )", subpred);
2285 } else if ( !strcasecmp("-exists",search_itr->key) ) {
2286 char* subpred = SELECT(
2288 jsonObjectGetKey( node, "select" ),
2289 jsonObjectGetKey( node, "from" ),
2290 jsonObjectGetKey( node, "where" ),
2291 jsonObjectGetKey( node, "having" ),
2292 jsonObjectGetKey( node, "order_by" ),
2293 jsonObjectGetKey( node, "limit" ),
2294 jsonObjectGetKey( node, "offset" ),
2298 buffer_fadd(sql_buf, "EXISTS ( %s )", subpred);
2300 } else if ( !strcasecmp("-not-exists",search_itr->key) ) {
2301 char* subpred = SELECT(
2303 jsonObjectGetKey( node, "select" ),
2304 jsonObjectGetKey( node, "from" ),
2305 jsonObjectGetKey( node, "where" ),
2306 jsonObjectGetKey( node, "having" ),
2307 jsonObjectGetKey( node, "order_by" ),
2308 jsonObjectGetKey( node, "limit" ),
2309 jsonObjectGetKey( node, "offset" ),
2313 buffer_fadd(sql_buf, "NOT EXISTS ( %s )", subpred);
2317 char* class = osrfHashGet(meta, "classname");
2318 osrfHash* fields = osrfHashGet(meta, "fields");
2319 osrfHash* field = osrfHashGet( fields, search_itr->key );
2323 char* table = getSourceDefinition(meta);
2326 "%s: Attempt to reference non-existent column %s on %s (%s)",
2332 buffer_free(sql_buf);
2334 jsonIteratorFree(search_itr);
2338 char* subpred = searchPredicate( class, field, node, ctx );
2339 buffer_add( sql_buf, subpred );
2343 jsonIteratorFree(search_itr);
2346 // ERROR ... only hash and array allowed at this level
2347 char* predicate_string = jsonObjectToJSON( search_hash );
2350 "%s: Invalid predicate structure: %s",
2354 buffer_free(sql_buf);
2355 free(predicate_string);
2360 return buffer_release(sql_buf);
2364 /* method context */ osrfMethodContext* ctx,
2366 /* SELECT */ jsonObject* selhash,
2367 /* FROM */ jsonObject* join_hash,
2368 /* WHERE */ jsonObject* search_hash,
2369 /* HAVING */ jsonObject* having_hash,
2370 /* ORDER BY */ jsonObject* order_hash,
2371 /* LIMIT */ jsonObject* limit,
2372 /* OFFSET */ jsonObject* offset,
2373 /* flags */ int flags
2375 const char* locale = osrf_message_get_last_locale();
2377 // in case we don't get a select list
2378 jsonObject* defaultselhash = NULL;
2380 // general tmp objects
2381 const jsonObject* tmp_const;
2382 jsonObject* selclass = NULL;
2383 jsonObject* selfield = NULL;
2384 jsonObject* snode = NULL;
2385 jsonObject* onode = NULL;
2387 char* string = NULL;
2388 int from_function = 0;
2393 // the core search class
2394 char* core_class = NULL;
2396 // metadata about the core search class
2397 osrfHash* core_meta = NULL;
2399 // punt if there's no core class
2400 if (!join_hash || ( join_hash->type == JSON_HASH && !join_hash->size ))
2403 // get the core class -- the only key of the top level FROM clause, or a string
2404 if (join_hash->type == JSON_HASH) {
2405 jsonIterator* tmp_itr = jsonNewIterator( join_hash );
2406 snode = jsonIteratorNext( tmp_itr );
2408 core_class = strdup( tmp_itr->key );
2411 jsonObject* extra = jsonIteratorNext( tmp_itr );
2413 jsonIteratorFree( tmp_itr );
2416 // There shouldn't be more than one entry in join_hash
2418 return NULL; // Malformed join_hash; extra entry
2420 } else if (join_hash->type == JSON_ARRAY) {
2422 core_class = jsonObjectToSimpleString( jsonObjectGetIndex(join_hash, 0) );
2425 } else if (join_hash->type == JSON_STRING) {
2426 core_class = jsonObjectToSimpleString( join_hash );
2432 // punt if we don't know about the core class (and it's not a function)
2433 if (!from_function && !(core_meta = osrfHashGet( oilsIDL(), core_class ))) {
2438 // if the select list is empty, or the core class field list is '*',
2439 // build the default select list ...
2441 selhash = defaultselhash = jsonNewObjectType(JSON_HASH);
2442 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2443 } else if ( (tmp_const = jsonObjectGetKeyConst( selhash, core_class )) && tmp_const->type == JSON_STRING ) {
2444 char* _x = jsonObjectToSimpleString( tmp_const );
2445 if (!strncmp( "*", _x, 1 )) {
2446 jsonObjectRemoveKey( selhash, core_class );
2447 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2453 growing_buffer* sql_buf = buffer_init(128);
2455 // temp buffer for the SELECT list
2456 growing_buffer* select_buf = buffer_init(128);
2457 growing_buffer* order_buf = buffer_init(128);
2458 growing_buffer* group_buf = buffer_init(128);
2459 growing_buffer* having_buf = buffer_init(128);
2461 // Build a select list
2462 if(from_function) // From a function we select everything
2463 OSRF_BUFFER_ADD_CHAR( select_buf, '*' );
2466 // If we need to build a default list, do so
2467 jsonObject* _tmp = jsonObjectGetKey( selhash, core_class );
2468 if ( _tmp && !_tmp->size ) {
2472 osrfHash* core_fields = osrfHashGet( core_meta, "fields" );
2474 osrfStringArray* keys = osrfHashKeys( core_fields );
2475 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
2476 if( ! str_is_true( osrfHashGet( osrfHashGet( core_fields, field ), "virtual" ) ) )
2477 jsonObjectPush( _tmp, jsonNewObject( field ) ); // not virtual; use it
2479 osrfStringArrayFree(keys);
2482 // Now build the actual select list
2484 jsonObject* is_agg = jsonObjectFindPath(selhash, "//aggregate");
2487 jsonIterator* selclass_itr = jsonNewIterator( selhash );
2488 while ( (selclass = jsonIteratorNext( selclass_itr )) ) { // For each class
2490 // round trip through the idl, just to be safe
2491 const char* cname = selclass_itr->key;
2492 osrfHash* idlClass = osrfHashGet( oilsIDL(), cname );
2494 // No such class. Skip it.
2497 // Make sure the target relation is in the join tree.
2499 // At this point join_hash is a step down from the join_hash we
2500 // received as a parameter. If the original was a JSON_STRING,
2501 // then json_hash is now NULL. If the original was a JSON_HASH,
2502 // then json_hash is now the first (and only) entry in it,
2503 // denoting the core class. We've already excluded the
2504 // possibility that the original was a JSON_ARRAY, because in
2505 // that case from_function would be non-NULL, and we wouldn't
2508 if ( strcmp( core_class, cname )) {
2510 // There's only one class in the FROM clause,
2511 // and this isn't it. Skip it.
2514 if (join_hash->type == JSON_STRING) {
2515 string = jsonObjectToSimpleString(join_hash);
2516 int different = strcmp( string, cname );
2519 // There's only one class in the FROM clause,
2520 // and this isn't it. Skip it.
2523 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", cname);
2524 unsigned long size = found->size;
2525 jsonObjectFree( found );
2527 // No such class anywhere in the join tree. Skip it.
2532 // Look up some attributes of the current class, so that we
2533 // don't have to look them up again for each field
2534 osrfHash* class_field_set = osrfHashGet( idlClass, "fields" );
2535 char* class_pkey = osrfHashGet( idlClass, "primarykey" );
2536 char* class_tname = osrfHashGet( idlClass, "tablename" );
2538 // stitch together the column list ...
2539 jsonIterator* select_itr = jsonNewIterator( selclass );
2540 while ( (selfield = jsonIteratorNext( select_itr )) ) { // for each SELECT column
2542 // If we need a separator comma, add one
2546 OSRF_BUFFER_ADD_CHAR( select_buf, ',' );
2549 // ... if it's a string, just toss it on the pile
2550 if (selfield->type == JSON_STRING) {
2552 // again, just to be safe
2553 const char* _requested_col = selfield->value.s;
2554 osrfHash* field = osrfHashGet( class_field_set, _requested_col );
2555 if (!field) continue; // No such field in current class; skip it
2557 const char* col_name = osrfHashGet(field, "name");
2561 if (flags & DISABLE_I18N)
2564 i18n = osrfHashGet(field, "i18n");
2566 if( str_is_true( i18n ) ) {
2567 buffer_fadd( select_buf,
2568 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2569 class_tname, cname, col_name, class_pkey, cname, class_pkey, locale, col_name );
2571 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2574 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2577 // ... but it could be an object, in which case we check for a Field Transform
2580 char* _column = jsonObjectToSimpleString( jsonObjectGetKeyConst( selfield, "column" ) );
2582 // Get the field definition from the IDL
2583 osrfHash* field = osrfHashGet( class_field_set, _column );
2584 if (!field) continue; // No such field defined in IDL. Skip it.
2586 // Decide what to use as a column alias
2588 if ((tmp_const = jsonObjectGetKeyConst( selfield, "alias" ))) {
2589 _alias = jsonObjectToSimpleString( tmp_const );
2591 } else { // Use column name as its own alias
2594 _column = NULL; // To emphasize that we're through with _column
2596 if (jsonObjectGetKeyConst( selfield, "transform" )) {
2597 char* transform_str = searchFieldTransform(cname, field, selfield);
2598 buffer_fadd(select_buf, " %s AS \"%s\"", transform_str, _alias);
2599 free(transform_str);
2602 const char* fname = osrfHashGet(field, "name");
2606 if (flags & DISABLE_I18N)
2609 i18n = osrfHashGet(field, "i18n");
2611 if( str_is_true( i18n ) ) {
2612 buffer_fadd( select_buf,
2613 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2614 class_tname, cname, fname, class_pkey, cname, class_pkey, locale, _alias);
2616 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, fname, _alias);
2619 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, fname, _alias);
2626 if (is_agg->size || (flags & SELECT_DISTINCT)) {
2628 const jsonObject* aggregate_obj = jsonObjectGetKey( selfield, "aggregate" );
2629 if ( ! obj_is_true( aggregate_obj ) ) {
2633 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
2636 buffer_fadd(group_buf, " %d", sel_pos);
2638 } else if (is_agg = jsonObjectGetKey( selfield, "having" )) {
2642 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
2645 _column = searchFieldTransform(cname, field, selfield);
2646 OSRF_BUFFER_ADD_CHAR(group_buf, ' ');
2647 OSRF_BUFFER_ADD(group_buf, _column);
2648 _column = searchFieldTransform(cname, field, selfield);
2654 } // end while -- iterating across SELECT columns
2656 jsonIteratorFree(select_itr);
2657 } // end while -- iterating across classes
2659 jsonIteratorFree(selclass_itr);
2661 if (is_agg) jsonObjectFree(is_agg);
2665 char* col_list = buffer_release(select_buf);
2667 if (from_function) table = searchValueTransform(join_hash);
2668 else table = getSourceDefinition(core_meta);
2670 // Put it all together
2671 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\" ", col_list, table, core_class );
2675 if (!from_function) {
2676 // Now, walk the join tree and add that clause
2678 char* join_clause = searchJOIN( join_hash, core_meta );
2679 buffer_add(sql_buf, join_clause);
2683 // Build a WHERE clause, if there is one
2684 if ( search_hash ) {
2685 buffer_add(sql_buf, " WHERE ");
2687 // and it's on the WHERE clause
2688 char* pred = searchWHERE( search_hash, core_meta, AND_OP_JOIN, ctx );
2691 buffer_add(sql_buf, pred);
2695 osrfAppSessionStatus(
2697 OSRF_STATUS_INTERNALSERVERERROR,
2698 "osrfMethodException",
2700 "Severe query error in WHERE predicate -- see error log for more details"
2704 buffer_free(having_buf);
2705 buffer_free(group_buf);
2706 buffer_free(order_buf);
2707 buffer_free(sql_buf);
2708 if (defaultselhash) jsonObjectFree(defaultselhash);
2713 // Build a HAVING clause, if there is one
2714 if ( having_hash ) {
2715 buffer_add(sql_buf, " HAVING ");
2717 // and it's on the the WHERE clause
2718 char* pred = searchWHERE( having_hash, core_meta, AND_OP_JOIN, ctx );
2721 buffer_add(sql_buf, pred);
2725 osrfAppSessionStatus(
2727 OSRF_STATUS_INTERNALSERVERERROR,
2728 "osrfMethodException",
2730 "Severe query error in HAVING predicate -- see error log for more details"
2734 buffer_free(having_buf);
2735 buffer_free(group_buf);
2736 buffer_free(order_buf);
2737 buffer_free(sql_buf);
2738 if (defaultselhash) jsonObjectFree(defaultselhash);
2743 // Build an ORDER BY clause, if there is one
2745 jsonIterator* class_itr = jsonNewIterator( order_hash );
2746 while ( (snode = jsonIteratorNext( class_itr )) ) {
2748 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
2751 if ( snode->type == JSON_HASH ) {
2753 jsonIterator* order_itr = jsonNewIterator( snode );
2754 while ( (onode = jsonIteratorNext( order_itr )) ) {
2756 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
2759 char* direction = NULL;
2760 if ( onode->type == JSON_HASH ) {
2761 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
2762 string = searchFieldTransform(
2764 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
2768 growing_buffer* field_buf = buffer_init(16);
2769 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
2770 string = buffer_release(field_buf);
2773 if ( (tmp_const = jsonObjectGetKeyConst( onode, "direction" )) ) {
2774 direction = jsonObjectToSimpleString(tmp_const);
2775 if (!strncasecmp(direction, "d", 1)) {
2777 direction = " DESC";
2785 string = strdup(order_itr->key);
2786 direction = jsonObjectToSimpleString(onode);
2787 if (!strncasecmp(direction, "d", 1)) {
2789 direction = " DESC";
2799 buffer_add(order_buf, ", ");
2802 buffer_add(order_buf, string);
2806 buffer_add(order_buf, direction);
2810 // jsonIteratorFree(order_itr);
2812 } else if ( snode->type == JSON_ARRAY ) {
2814 jsonIterator* order_itr = jsonNewIterator( snode );
2815 while ( (onode = jsonIteratorNext( order_itr )) ) {
2817 char* _f = jsonObjectToSimpleString( onode );
2819 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, _f))
2825 buffer_add(order_buf, ", ");
2828 buffer_add(order_buf, _f);
2832 // jsonIteratorFree(order_itr);
2835 // IT'S THE OOOOOOOOOOOLD STYLE!
2837 osrfLogError(OSRF_LOG_MARK, "%s: Possible SQL injection attempt; direct order by is not allowed", MODULENAME);
2839 osrfAppSessionStatus(
2841 OSRF_STATUS_INTERNALSERVERERROR,
2842 "osrfMethodException",
2844 "Severe query error -- see error log for more details"
2849 buffer_free(having_buf);
2850 buffer_free(group_buf);
2851 buffer_free(order_buf);
2852 buffer_free(sql_buf);
2853 if (defaultselhash) jsonObjectFree(defaultselhash);
2854 jsonIteratorFree(class_itr);
2859 // jsonIteratorFree(class_itr);
2863 string = buffer_release(group_buf);
2865 if (strlen(string)) {
2866 OSRF_BUFFER_ADD( sql_buf, " GROUP BY " );
2867 OSRF_BUFFER_ADD( sql_buf, string );
2872 string = buffer_release(having_buf);
2874 if (strlen(string)) {
2875 OSRF_BUFFER_ADD( sql_buf, " HAVING " );
2876 OSRF_BUFFER_ADD( sql_buf, string );
2881 string = buffer_release(order_buf);
2883 if (strlen(string)) {
2884 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
2885 OSRF_BUFFER_ADD( sql_buf, string );
2891 string = jsonObjectToSimpleString(limit);
2892 buffer_fadd( sql_buf, " LIMIT %d", atoi(string) );
2897 string = jsonObjectToSimpleString(offset);
2898 buffer_fadd( sql_buf, " OFFSET %d", atoi(string) );
2902 if (!(flags & SUBSELECT)) OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
2905 if (defaultselhash) jsonObjectFree(defaultselhash);
2907 return buffer_release(sql_buf);
2911 static char* buildSELECT ( jsonObject* search_hash, jsonObject* order_hash, osrfHash* meta, osrfMethodContext* ctx ) {
2913 const char* locale = osrf_message_get_last_locale();
2915 osrfHash* fields = osrfHashGet(meta, "fields");
2916 char* core_class = osrfHashGet(meta, "classname");
2918 const jsonObject* join_hash = jsonObjectGetKeyConst( order_hash, "join" );
2920 jsonObject* node = NULL;
2921 jsonObject* snode = NULL;
2922 jsonObject* onode = NULL;
2923 const jsonObject* _tmp = NULL;
2924 jsonObject* selhash = NULL;
2925 jsonObject* defaultselhash = NULL;
2927 growing_buffer* sql_buf = buffer_init(128);
2928 growing_buffer* select_buf = buffer_init(128);
2930 if ( !(selhash = jsonObjectGetKey( order_hash, "select" )) ) {
2931 defaultselhash = jsonNewObjectType(JSON_HASH);
2932 selhash = defaultselhash;
2935 if ( !jsonObjectGetKeyConst(selhash,core_class) ) {
2936 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2937 jsonObject* flist = jsonObjectGetKey( selhash, core_class );
2942 osrfStringArray* keys = osrfHashKeys( fields );
2943 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
2944 if( ! str_is_true( osrfHashGet( osrfHashGet( fields, field ), "virtual" ) ) )
2945 jsonObjectPush( flist, jsonNewObject( field ) );
2947 osrfStringArrayFree(keys);
2951 jsonIterator* class_itr = jsonNewIterator( selhash );
2952 while ( (snode = jsonIteratorNext( class_itr )) ) {
2954 char* cname = class_itr->key;
2955 osrfHash* idlClass = osrfHashGet( oilsIDL(), cname );
2956 if (!idlClass) continue;
2958 if (strcmp(core_class,class_itr->key)) {
2959 if (!join_hash) continue;
2961 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", class_itr->key);
2963 jsonObjectFree(found);
2967 jsonObjectFree(found);
2970 jsonIterator* select_itr = jsonNewIterator( snode );
2971 while ( (node = jsonIteratorNext( select_itr )) ) {
2972 char* item_str = jsonObjectToSimpleString(node);
2973 osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), item_str );
2975 char* fname = osrfHashGet(field, "name");
2977 if (!field) continue;
2982 OSRF_BUFFER_ADD_CHAR(select_buf, ',');
2987 const jsonObject* no_i18n_obj = jsonObjectGetKey( order_hash, "no_i18n" );
2988 if ( obj_is_true( no_i18n_obj ) ) // Suppress internationalization?
2991 i18n = osrfHashGet(field, "i18n");
2993 if( str_is_true( i18n ) ) {
2994 char* pkey = osrfHashGet(idlClass, "primarykey");
2995 char* tname = osrfHashGet(idlClass, "tablename");
2997 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);
2999 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
3002 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
3006 jsonIteratorFree(select_itr);
3009 jsonIteratorFree(class_itr);
3011 char* col_list = buffer_release(select_buf);
3012 char* table = getSourceDefinition(meta);
3014 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\"", col_list, table, core_class );
3019 char* join_clause = searchJOIN( join_hash, meta );
3020 OSRF_BUFFER_ADD_CHAR(sql_buf, ' ');
3021 OSRF_BUFFER_ADD(sql_buf, join_clause);
3025 osrfLogDebug(OSRF_LOG_MARK, "%s pre-predicate SQL = %s",
3026 MODULENAME, OSRF_BUFFER_C_STR(sql_buf));
3028 buffer_add(sql_buf, " WHERE ");
3030 char* pred = searchWHERE( search_hash, meta, AND_OP_JOIN, ctx );
3032 osrfAppSessionStatus(
3034 OSRF_STATUS_INTERNALSERVERERROR,
3035 "osrfMethodException",
3037 "Severe query error -- see error log for more details"
3039 buffer_free(sql_buf);
3040 if(defaultselhash) jsonObjectFree(defaultselhash);
3043 buffer_add(sql_buf, pred);
3048 char* string = NULL;
3049 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "order_by" )) ){
3051 growing_buffer* order_buf = buffer_init(128);
3054 jsonIterator* class_itr = jsonNewIterator( _tmp );
3055 while ( (snode = jsonIteratorNext( class_itr )) ) {
3057 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
3060 if ( snode->type == JSON_HASH ) {
3062 jsonIterator* order_itr = jsonNewIterator( snode );
3063 while ( (onode = jsonIteratorNext( order_itr )) ) {
3065 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
3068 char* direction = NULL;
3069 if ( onode->type == JSON_HASH ) {
3070 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
3071 string = searchFieldTransform(
3073 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
3077 growing_buffer* field_buf = buffer_init(16);
3078 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
3079 string = buffer_release(field_buf);
3082 if ( (_tmp = jsonObjectGetKeyConst( onode, "direction" )) ) {
3083 direction = jsonObjectToSimpleString(_tmp);
3084 if (!strncasecmp(direction, "d", 1)) {
3086 direction = " DESC";
3094 string = strdup(order_itr->key);
3095 direction = jsonObjectToSimpleString(onode);
3096 if (!strncasecmp(direction, "d", 1)) {
3098 direction = " DESC";
3108 buffer_add(order_buf, ", ");
3111 buffer_add(order_buf, string);
3115 buffer_add(order_buf, direction);
3120 jsonIteratorFree(order_itr);
3123 string = jsonObjectToSimpleString(snode);
3124 buffer_add(order_buf, string);
3131 jsonIteratorFree(class_itr);
3133 string = buffer_release(order_buf);
3135 if (strlen(string)) {
3136 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
3137 OSRF_BUFFER_ADD( sql_buf, string );
3143 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "limit" )) ){
3144 string = jsonObjectToSimpleString(_tmp);
3153 _tmp = jsonObjectGetKeyConst( order_hash, "offset" );
3155 string = jsonObjectToSimpleString(_tmp);
3165 if (defaultselhash) jsonObjectFree(defaultselhash);
3167 OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
3168 return buffer_release(sql_buf);
3171 int doJSONSearch ( osrfMethodContext* ctx ) {
3172 if(osrfMethodVerifyContext( ctx )) {
3173 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
3177 osrfLogDebug(OSRF_LOG_MARK, "Recieved query request");
3182 dbhandle = writehandle;
3184 jsonObject* hash = jsonObjectGetIndex(ctx->params, 0);
3188 if ( obj_is_true( jsonObjectGetKey( hash, "distinct" ) ) )
3189 flags |= SELECT_DISTINCT;
3191 if ( obj_is_true( jsonObjectGetKey( hash, "no_i18n" ) ) )
3192 flags |= DISABLE_I18N;
3194 osrfLogDebug(OSRF_LOG_MARK, "Building SQL ...");
3197 jsonObjectGetKey( hash, "select" ),
3198 jsonObjectGetKey( hash, "from" ),
3199 jsonObjectGetKey( hash, "where" ),
3200 jsonObjectGetKey( hash, "having" ),
3201 jsonObjectGetKey( hash, "order_by" ),
3202 jsonObjectGetKey( hash, "limit" ),
3203 jsonObjectGetKey( hash, "offset" ),
3212 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3213 dbi_result result = dbi_conn_query(dbhandle, sql);
3216 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3218 if (dbi_result_first_row(result)) {
3219 /* JSONify the result */
3220 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3223 jsonObject* return_val = oilsMakeJSONFromResult( result );
3224 osrfAppRespond( ctx, return_val );
3225 jsonObjectFree( return_val );
3226 } while (dbi_result_next_row(result));
3229 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
3232 osrfAppRespondComplete( ctx, NULL );
3234 /* clean up the query */
3235 dbi_result_free(result);
3239 osrfLogError(OSRF_LOG_MARK, "%s: Error with query [%s]", MODULENAME, sql);
3240 osrfAppSessionStatus(
3242 OSRF_STATUS_INTERNALSERVERERROR,
3243 "osrfMethodException",
3245 "Severe query error -- see error log for more details"
3253 static jsonObject* doFieldmapperSearch ( osrfMethodContext* ctx, osrfHash* meta,
3254 const jsonObject* params, int* err ) {
3257 dbhandle = writehandle;
3259 osrfHash* links = osrfHashGet(meta, "links");
3260 osrfHash* fields = osrfHashGet(meta, "fields");
3261 char* core_class = osrfHashGet(meta, "classname");
3262 char* pkey = osrfHashGet(meta, "primarykey");
3264 const jsonObject* _tmp;
3266 jsonObject* search_hash = jsonObjectGetIndex(params, 0);
3267 jsonObject* order_hash = jsonObjectGetIndex(params, 1);
3269 char* sql = buildSELECT( search_hash, order_hash, meta, ctx );
3271 osrfLogDebug(OSRF_LOG_MARK, "Problem building query, returning NULL");
3276 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3278 dbi_result result = dbi_conn_query(dbhandle, sql);
3279 if( NULL == result ) {
3280 osrfLogError(OSRF_LOG_MARK, "%s: Error retrieving %s with query [%s]",
3281 MODULENAME, osrfHashGet(meta, "fieldmapper"), sql);
3282 osrfAppSessionStatus(
3284 OSRF_STATUS_INTERNALSERVERERROR,
3285 "osrfMethodException",
3287 "Severe query error -- see error log for more details"
3294 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3297 jsonObject* res_list = jsonNewObjectType(JSON_ARRAY);
3298 osrfHash* dedup = osrfNewHash();
3300 if (dbi_result_first_row(result)) {
3301 /* JSONify the result */
3302 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3304 obj = oilsMakeFieldmapperFromResult( result, meta );
3305 char* pkey_val = oilsFMGetString( obj, pkey );
3306 if ( osrfHashGet( dedup, pkey_val ) ) {
3307 jsonObjectFree(obj);
3310 osrfHashSet( dedup, pkey_val, pkey_val );
3311 jsonObjectPush(res_list, obj);
3313 } while (dbi_result_next_row(result));
3315 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s",
3319 osrfHashFree(dedup);
3320 /* clean up the query */
3321 dbi_result_free(result);
3324 if (res_list->size && order_hash) {
3325 _tmp = jsonObjectGetKeyConst( order_hash, "flesh" );
3327 int x = (int)jsonObjectGetNumber(_tmp);
3328 if (x == -1 || x > max_flesh_depth) x = max_flesh_depth;
3330 const jsonObject* temp_blob;
3331 if ((temp_blob = jsonObjectGetKeyConst( order_hash, "flesh_fields" )) && x > 0) {
3333 jsonObject* flesh_blob = jsonObjectClone( temp_blob );
3334 const jsonObject* flesh_fields = jsonObjectGetKeyConst( flesh_blob, core_class );
3336 osrfStringArray* link_fields = NULL;
3339 if (flesh_fields->size == 1) {
3340 char* _t = jsonObjectToSimpleString( jsonObjectGetIndex( flesh_fields, 0 ) );
3341 if (!strcmp(_t,"*")) link_fields = osrfHashKeys( links );
3347 link_fields = osrfNewStringArray(1);
3348 jsonIterator* _i = jsonNewIterator( flesh_fields );
3349 while ((_f = jsonIteratorNext( _i ))) {
3350 osrfStringArrayAdd( link_fields, jsonObjectToSimpleString( _f ) );
3352 jsonIteratorFree(_i);
3357 jsonIterator* itr = jsonNewIterator( res_list );
3358 while ((cur = jsonIteratorNext( itr ))) {
3363 while ( (link_field = osrfStringArrayGetString(link_fields, i++)) ) {
3365 osrfLogDebug(OSRF_LOG_MARK, "Starting to flesh %s", link_field);
3367 osrfHash* kid_link = osrfHashGet(links, link_field);
3368 if (!kid_link) continue;
3370 osrfHash* field = osrfHashGet(fields, link_field);
3371 if (!field) continue;
3373 osrfHash* value_field = field;
3375 osrfHash* kid_idl = osrfHashGet(oilsIDL(), osrfHashGet(kid_link, "class"));
3376 if (!kid_idl) continue;
3378 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3379 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3382 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) { // might_have
3383 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3386 osrfStringArray* link_map = osrfHashGet( kid_link, "map" );
3388 if (link_map->size > 0) {
3389 jsonObject* _kid_key = jsonNewObjectType(JSON_ARRAY);
3392 jsonNewObject( osrfStringArrayGetString( link_map, 0 ) )
3397 osrfHashGet(kid_link, "class"),
3404 "Link field: %s, remote class: %s, fkey: %s, reltype: %s",
3405 osrfHashGet(kid_link, "field"),
3406 osrfHashGet(kid_link, "class"),
3407 osrfHashGet(kid_link, "key"),
3408 osrfHashGet(kid_link, "reltype")
3411 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
3412 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // search hash
3413 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // order/flesh hash
3415 osrfLogDebug(OSRF_LOG_MARK, "Creating dummy params object...");
3418 jsonObjectToSimpleString(
3421 atoi( osrfHashGet(value_field, "array_position") )
3426 osrfLogDebug(OSRF_LOG_MARK, "Nothing to search for!");
3431 jsonObjectGetIndex(fake_params, 0),
3432 osrfHashGet(kid_link, "key"),
3433 jsonNewObject( search_key )
3440 jsonObjectGetIndex(fake_params, 1),
3442 jsonNewNumberObject( (double)(x - 1 + link_map->size) )
3446 jsonObjectSetKey( jsonObjectGetIndex(fake_params, 1), "flesh_fields", jsonObjectClone(flesh_blob) );
3448 if (jsonObjectGetKeyConst(order_hash, "order_by")) {
3450 jsonObjectGetIndex(fake_params, 1),
3452 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "order_by"))
3456 if (jsonObjectGetKeyConst(order_hash, "select")) {
3458 jsonObjectGetIndex(fake_params, 1),
3460 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "select"))
3464 jsonObject* kids = doFieldmapperSearch(ctx, kid_idl, fake_params, err);
3467 jsonObjectFree( fake_params );
3468 osrfStringArrayFree(link_fields);
3469 jsonIteratorFree(itr);
3470 jsonObjectFree(res_list);
3471 jsonObjectFree(flesh_blob);
3475 osrfLogDebug(OSRF_LOG_MARK, "Search for %s return %d linked objects", osrfHashGet(kid_link, "class"), kids->size);
3477 jsonObject* X = NULL;
3478 if ( link_map->size > 0 && kids->size > 0 ) {
3480 kids = jsonNewObjectType(JSON_ARRAY);
3482 jsonObject* _k_node;
3483 jsonIterator* _k = jsonNewIterator( X );
3484 while ((_k_node = jsonIteratorNext( _k ))) {
3490 (unsigned long)atoi(
3496 osrfHashGet(kid_link, "class")
3500 osrfStringArrayGetString( link_map, 0 )
3509 jsonIteratorFree(_k);
3512 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_a" )) || !(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) {
3513 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3516 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3517 jsonObjectClone( jsonObjectGetIndex(kids, 0) )
3521 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3522 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3525 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3526 jsonObjectClone( kids )
3531 jsonObjectFree(kids);
3535 jsonObjectFree( kids );
3536 jsonObjectFree( fake_params );
3538 osrfLogDebug(OSRF_LOG_MARK, "Fleshing of %s complete", osrfHashGet(kid_link, "field"));
3539 osrfLogDebug(OSRF_LOG_MARK, "%s", jsonObjectToJSON(cur));
3543 jsonObjectFree( flesh_blob );
3544 osrfStringArrayFree(link_fields);
3545 jsonIteratorFree(itr);
3554 static jsonObject* doUpdate(osrfMethodContext* ctx, int* err ) {
3556 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3558 jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
3560 jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
3563 if (!verifyObjectClass(ctx, target)) {
3568 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3569 osrfAppSessionStatus(
3571 OSRF_STATUS_BADREQUEST,
3572 "osrfMethodException",
3574 "No active transaction -- required for UPDATE"
3580 // The following test is harmless but redundant. If a class is
3581 // readonly, we don't register an update method for it.
3582 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
3583 osrfAppSessionStatus(
3585 OSRF_STATUS_BADREQUEST,
3586 "osrfMethodException",
3588 "Cannot UPDATE readonly class"
3594 dbhandle = writehandle;
3596 char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
3598 // Set the last_xact_id
3599 int index = oilsIDL_ntop( target->classname, "last_xact_id" );
3601 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
3602 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
3605 char* pkey = osrfHashGet(meta, "primarykey");
3606 osrfHash* fields = osrfHashGet(meta, "fields");
3608 char* id = oilsFMGetString( target, pkey );
3612 "%s updating %s object with %s = %s",
3614 osrfHashGet(meta, "fieldmapper"),
3619 growing_buffer* sql = buffer_init(128);
3620 buffer_fadd(sql,"UPDATE %s SET", osrfHashGet(meta, "tablename"));
3625 osrfStringArray* field_list = osrfHashKeys( fields );
3626 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
3628 osrfHash* field = osrfHashGet( fields, field_name );
3630 if(!( strcmp( field_name, pkey ) )) continue;
3631 if( str_is_true( osrfHashGet(osrfHashGet(fields,field_name), "virtual") ) )
3634 const jsonObject* field_object = oilsFMGetObject( target, field_name );
3637 if (field_object && field_object->classname) {
3638 value = oilsFMGetString(
3640 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
3643 value = jsonObjectToSimpleString( field_object );
3646 osrfLogDebug( OSRF_LOG_MARK, "Updating %s object with %s = %s", osrfHashGet(meta, "fieldmapper"), field_name, value);
3648 if (!field_object || field_object->type == JSON_NULL) {
3649 if ( !(!( strcmp( osrfHashGet(meta, "classname"), "au" ) ) && !( strcmp( field_name, "passwd" ) )) ) { // arg at the special case!
3650 if (first) first = 0;
3651 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3652 buffer_fadd( sql, " %s = NULL", field_name );
3655 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
3656 if (first) first = 0;
3657 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3659 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
3660 buffer_fadd( sql, " %s = %ld", field_name, atol(value) );
3661 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
3662 buffer_fadd( sql, " %s = %f", field_name, atof(value) );
3665 osrfLogDebug( OSRF_LOG_MARK, "%s is of type %s", field_name, osrfHashGet(field, "datatype"));
3668 if ( dbi_conn_quote_string(dbhandle, &value) ) {
3669 if (first) first = 0;
3670 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3671 buffer_fadd( sql, " %s = %s", field_name, value );
3674 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
3675 osrfAppSessionStatus(
3677 OSRF_STATUS_INTERNALSERVERERROR,
3678 "osrfMethodException",
3680 "Error quoting string -- please see the error log for more details"
3694 jsonObject* obj = jsonNewObject(id);
3696 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
3697 dbi_conn_quote_string(dbhandle, &id);
3699 buffer_fadd( sql, " WHERE %s = %s;", pkey, id );
3701 char* query = buffer_release(sql);
3702 osrfLogDebug(OSRF_LOG_MARK, "%s: Update SQL [%s]", MODULENAME, query);
3704 dbi_result result = dbi_conn_query(dbhandle, query);
3708 jsonObjectFree(obj);
3709 obj = jsonNewObject(NULL);
3712 "%s ERROR updating %s object with %s = %s",
3714 osrfHashGet(meta, "fieldmapper"),
3725 static jsonObject* doDelete(osrfMethodContext* ctx, int* err ) {
3727 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3729 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3730 osrfAppSessionStatus(
3732 OSRF_STATUS_BADREQUEST,
3733 "osrfMethodException",
3735 "No active transaction -- required for DELETE"
3741 // The following test is harmless but redundant. If a class is
3742 // readonly, we don't register a delete method for it.
3743 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
3744 osrfAppSessionStatus(
3746 OSRF_STATUS_BADREQUEST,
3747 "osrfMethodException",
3749 "Cannot DELETE readonly class"
3755 dbhandle = writehandle;
3759 char* pkey = osrfHashGet(meta, "primarykey");
3767 if (jsonObjectGetIndex(ctx->params, _obj_pos)->classname) {
3768 if (!verifyObjectClass(ctx, jsonObjectGetIndex( ctx->params, _obj_pos ))) {
3773 id = oilsFMGetString( jsonObjectGetIndex(ctx->params, _obj_pos), pkey );
3776 if (!verifyObjectPCRUD( ctx, NULL )) {
3781 id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, _obj_pos));
3786 "%s deleting %s object with %s = %s",
3788 osrfHashGet(meta, "fieldmapper"),
3793 obj = jsonNewObject(id);
3795 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
3796 dbi_conn_quote_string(writehandle, &id);
3798 dbi_result result = dbi_conn_queryf(writehandle, "DELETE FROM %s WHERE %s = %s;", osrfHashGet(meta, "tablename"), pkey, id);
3801 jsonObjectFree(obj);
3802 obj = jsonNewObject(NULL);
3805 "%s ERROR deleting %s object with %s = %s",
3807 osrfHashGet(meta, "fieldmapper"),
3820 static jsonObject* oilsMakeFieldmapperFromResult( dbi_result result, osrfHash* meta) {
3821 if(!(result && meta)) return jsonNULL;
3823 jsonObject* object = jsonNewObject(NULL);
3824 jsonObjectSetClass(object, osrfHashGet(meta, "classname"));
3826 osrfHash* fields = osrfHashGet(meta, "fields");
3828 osrfLogInternal(OSRF_LOG_MARK, "Setting object class to %s ", object->classname);
3832 char dt_string[256];
3836 int columnIndex = 1;
3838 unsigned short type;
3839 const char* columnName;
3841 /* cycle through the column list */
3842 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
3844 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
3846 fmIndex = -1; // reset the position
3848 /* determine the field type and storage attributes */
3849 type = dbi_result_get_field_type(result, columnName);
3850 attr = dbi_result_get_field_attribs(result, columnName);
3852 /* fetch the fieldmapper index */
3853 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
3855 if ( str_is_true( osrfHashGet(_f, "virtual") ) )
3858 const char* pos = (char*)osrfHashGet(_f, "array_position");
3859 if ( !pos ) continue;
3861 fmIndex = atoi( pos );
3862 osrfLogInternal(OSRF_LOG_MARK, "... Found column at position [%s]...", pos);
3867 if (dbi_result_field_is_null(result, columnName)) {
3868 jsonObjectSetIndex( object, fmIndex, jsonNewObject(NULL) );
3873 case DBI_TYPE_INTEGER :
3875 if( attr & DBI_INTEGER_SIZE8 )
3876 jsonObjectSetIndex( object, fmIndex,
3877 jsonNewNumberObject(dbi_result_get_longlong(result, columnName)));
3879 jsonObjectSetIndex( object, fmIndex,
3880 jsonNewNumberObject(dbi_result_get_int(result, columnName)));
3884 case DBI_TYPE_DECIMAL :
3885 jsonObjectSetIndex( object, fmIndex,
3886 jsonNewNumberObject(dbi_result_get_double(result, columnName)));
3889 case DBI_TYPE_STRING :
3895 jsonNewObject( dbi_result_get_string(result, columnName) )
3900 case DBI_TYPE_DATETIME :
3902 memset(dt_string, '\0', sizeof(dt_string));
3903 memset(&gmdt, '\0', sizeof(gmdt));
3905 _tmp_dt = dbi_result_get_datetime(result, columnName);
3908 if (!(attr & DBI_DATETIME_DATE)) {
3909 gmtime_r( &_tmp_dt, &gmdt );
3910 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
3911 } else if (!(attr & DBI_DATETIME_TIME)) {
3912 localtime_r( &_tmp_dt, &gmdt );
3913 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
3915 localtime_r( &_tmp_dt, &gmdt );
3916 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
3919 jsonObjectSetIndex( object, fmIndex, jsonNewObject(dt_string) );
3923 case DBI_TYPE_BINARY :
3924 osrfLogError( OSRF_LOG_MARK,
3925 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
3933 static jsonObject* oilsMakeJSONFromResult( dbi_result result ) {
3934 if(!result) return jsonNULL;
3936 jsonObject* object = jsonNewObject(NULL);
3939 char dt_string[256];
3943 int columnIndex = 1;
3945 unsigned short type;
3946 const char* columnName;
3948 /* cycle through the column list */
3949 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
3951 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
3953 fmIndex = -1; // reset the position
3955 /* determine the field type and storage attributes */
3956 type = dbi_result_get_field_type(result, columnName);
3957 attr = dbi_result_get_field_attribs(result, columnName);
3959 if (dbi_result_field_is_null(result, columnName)) {
3960 jsonObjectSetKey( object, columnName, jsonNewObject(NULL) );
3965 case DBI_TYPE_INTEGER :
3967 if( attr & DBI_INTEGER_SIZE8 )
3968 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_longlong(result, columnName)) );
3970 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_int(result, columnName)) );
3973 case DBI_TYPE_DECIMAL :
3974 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_double(result, columnName)) );
3977 case DBI_TYPE_STRING :
3978 jsonObjectSetKey( object, columnName, jsonNewObject(dbi_result_get_string(result, columnName)) );
3981 case DBI_TYPE_DATETIME :
3983 memset(dt_string, '\0', sizeof(dt_string));
3984 memset(&gmdt, '\0', sizeof(gmdt));
3986 _tmp_dt = dbi_result_get_datetime(result, columnName);
3989 if (!(attr & DBI_DATETIME_DATE)) {
3990 gmtime_r( &_tmp_dt, &gmdt );
3991 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
3992 } else if (!(attr & DBI_DATETIME_TIME)) {
3993 localtime_r( &_tmp_dt, &gmdt );
3994 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
3996 localtime_r( &_tmp_dt, &gmdt );
3997 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
4000 jsonObjectSetKey( object, columnName, jsonNewObject(dt_string) );
4003 case DBI_TYPE_BINARY :
4004 osrfLogError( OSRF_LOG_MARK,
4005 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
4013 // Interpret a string as true or false
4014 static int str_is_true( const char* str ) {
4015 if( NULL == str || strcasecmp( str, "true" ) )
4021 // Interpret a jsonObject as true or false
4022 static int obj_is_true( const jsonObject* obj ) {
4025 else switch( obj->type )
4033 if( strcasecmp( obj->value.s, "true" ) )
4037 case JSON_NUMBER : // Support 1/0 for perl's sake
4038 if( jsonObjectGetNumber( obj ) == 1.0 )