1 #include "opensrf/osrf_application.h"
2 #include "opensrf/osrf_settings.h"
3 #include "opensrf/osrf_message.h"
4 #include "opensrf/utils.h"
5 #include "opensrf/osrf_json.h"
6 #include "opensrf/log.h"
7 #include "openils/oils_utils.h"
16 # define MODULENAME "open-ils.reporter-store"
19 # define MODULENAME "open-ils.pcrud"
21 # define MODULENAME "open-ils.cstore"
26 #define DISABLE_I18N 2
27 #define SELECT_DISTINCT 1
31 int osrfAppChildInit();
32 int osrfAppInitialize();
33 void osrfAppChildExit();
35 static int verifyObjectClass ( osrfMethodContext*, const jsonObject* );
37 int beginTransaction ( osrfMethodContext* );
38 int commitTransaction ( osrfMethodContext* );
39 int rollbackTransaction ( osrfMethodContext* );
41 int setSavepoint ( osrfMethodContext* );
42 int releaseSavepoint ( osrfMethodContext* );
43 int rollbackSavepoint ( osrfMethodContext* );
45 int doJSONSearch ( osrfMethodContext* );
47 int dispatchCRUDMethod ( osrfMethodContext* );
48 static jsonObject* doCreate ( osrfMethodContext*, int* );
49 static jsonObject* doRetrieve ( osrfMethodContext*, int* );
50 static jsonObject* doUpdate ( osrfMethodContext*, int* );
51 static jsonObject* doDelete ( osrfMethodContext*, int* );
52 static jsonObject* doFieldmapperSearch ( osrfMethodContext*, osrfHash*,
53 const jsonObject*, int* );
54 static jsonObject* oilsMakeFieldmapperFromResult( dbi_result, osrfHash* );
55 static jsonObject* oilsMakeJSONFromResult( dbi_result );
57 static char* searchWriteSimplePredicate ( const char*, osrfHash*,
58 const char*, const char*, const char* );
59 static char* searchSimplePredicate ( const char*, const char*, osrfHash*, const jsonObject* );
60 static char* searchFunctionPredicate ( const char*, osrfHash*, const jsonObject*, const char* );
61 static char* searchFieldTransform ( const char*, osrfHash*, const jsonObject*);
62 static char* searchFieldTransformPredicate ( const char*, osrfHash*, jsonObject*, const char* );
63 static char* searchBETWEENPredicate ( const char*, osrfHash*, jsonObject* );
64 static char* searchINPredicate ( const char*, osrfHash*,
65 jsonObject*, const char*, osrfMethodContext* );
66 static char* searchPredicate ( const char*, osrfHash*, jsonObject*, osrfMethodContext* );
67 static char* searchJOIN ( const jsonObject*, osrfHash* );
68 static char* searchWHERE ( const jsonObject*, osrfHash*, int, osrfMethodContext* );
69 static char* buildSELECT ( jsonObject*, jsonObject*, osrfHash*, osrfMethodContext* );
71 char* SELECT ( osrfMethodContext*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, int );
73 void userDataFree( void* );
74 static void sessionDataFree( char*, void* );
75 static char* getSourceDefinition( osrfHash* );
76 static int str_is_true( const char* str );
77 static int obj_is_true( const jsonObject* obj );
80 static jsonObject* verifyUserPCRUD( osrfMethodContext* );
81 static int verifyObjectPCRUD( osrfMethodContext*, const jsonObject* );
84 static dbi_conn writehandle; /* our MASTER db connection */
85 static dbi_conn dbhandle; /* our CURRENT db connection */
86 //static osrfHash * readHandles;
87 static jsonObject* jsonNULL = NULL; //
88 static int max_flesh_depth = 100;
90 /* called when this process is about to exit */
91 void osrfAppChildExit() {
92 osrfLogDebug(OSRF_LOG_MARK, "Child is exiting, disconnecting from database...");
95 if (writehandle == dbhandle) same = 1;
97 dbi_conn_query(writehandle, "ROLLBACK;");
98 dbi_conn_close(writehandle);
101 if (dbhandle && !same)
102 dbi_conn_close(dbhandle);
104 // XXX add cleanup of readHandles whenever that gets used
109 int osrfAppInitialize() {
111 osrfLogInfo(OSRF_LOG_MARK, "Initializing the CStore Server...");
112 osrfLogInfo(OSRF_LOG_MARK, "Finding XML file...");
114 if (!oilsIDLInit( osrf_settings_host_value("/IDL") )) return 1; /* return non-zero to indicate error */
116 growing_buffer* method_name = buffer_init(64);
118 // Generic search thingy
119 buffer_add(method_name, MODULENAME);
120 buffer_add(method_name, ".json_query");
121 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
122 "doJSONSearch", "", 1, OSRF_METHOD_STREAMING );
125 // first we register all the transaction and savepoint methods
126 buffer_reset(method_name);
127 OSRF_BUFFER_ADD(method_name, MODULENAME);
128 OSRF_BUFFER_ADD(method_name, ".transaction.begin");
129 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
130 "beginTransaction", "", 0, 0 );
132 buffer_reset(method_name);
133 OSRF_BUFFER_ADD(method_name, MODULENAME);
134 OSRF_BUFFER_ADD(method_name, ".transaction.commit");
135 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
136 "commitTransaction", "", 0, 0 );
138 buffer_reset(method_name);
139 OSRF_BUFFER_ADD(method_name, MODULENAME);
140 OSRF_BUFFER_ADD(method_name, ".transaction.rollback");
141 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
142 "rollbackTransaction", "", 0, 0 );
144 buffer_reset(method_name);
145 OSRF_BUFFER_ADD(method_name, MODULENAME);
146 OSRF_BUFFER_ADD(method_name, ".savepoint.set");
147 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
148 "setSavepoint", "", 1, 0 );
150 buffer_reset(method_name);
151 OSRF_BUFFER_ADD(method_name, MODULENAME);
152 OSRF_BUFFER_ADD(method_name, ".savepoint.release");
153 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
154 "releaseSavepoint", "", 1, 0 );
156 buffer_reset(method_name);
157 OSRF_BUFFER_ADD(method_name, MODULENAME);
158 OSRF_BUFFER_ADD(method_name, ".savepoint.rollback");
159 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
160 "rollbackSavepoint", "", 1, 0 );
162 buffer_free(method_name);
164 static const char* global_method[] = {
172 const int global_method_count
173 = sizeof( global_method ) / sizeof ( global_method[0] );
177 osrfStringArray* classes = osrfHashKeys( oilsIDL() );
178 osrfLogDebug(OSRF_LOG_MARK, "%d classes loaded", classes->size );
179 osrfLogDebug(OSRF_LOG_MARK,
180 "At least %d methods will be generated", classes->size * global_method_count);
182 while ( (classname = osrfStringArrayGetString(classes, c_index++)) ) {
183 osrfLogInfo(OSRF_LOG_MARK, "Generating class methods for %s", classname);
185 osrfHash* idlClass = osrfHashGet(oilsIDL(), classname);
187 if (!osrfStringArrayContains( osrfHashGet(idlClass, "controller"), MODULENAME )) {
188 osrfLogInfo(OSRF_LOG_MARK, "%s is not listed as a controller for %s, moving on", MODULENAME, classname);
192 if ( str_is_true( osrfHashGet(idlClass, "virtual") ) ) {
193 osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
197 // Look up some other attributes of the current class
198 const char* idlClass_fieldmapper = osrfHashGet(idlClass, "fieldmapper");
199 const char* readonly = osrfHashGet(idlClass, "readonly");
201 osrfHash* idlClass_permacrud = osrfHashGet(idlClass, "permacrud");
205 for( i = 0; i < global_method_count; ++i ) {
206 const char* method_type = global_method[ i ];
207 osrfLogDebug(OSRF_LOG_MARK,
208 "Using files to build %s class methods for %s", method_type, classname);
210 if (!idlClass_fieldmapper) continue;
213 if (!idlClass_permacrud) continue;
215 const char* tmp_method = method_type;
216 if ( *tmp_method == 'i' || *tmp_method == 's') {
217 tmp_method = "retrieve";
219 if (!osrfHashGet( idlClass_permacrud, tmp_method )) continue;
222 if ( str_is_true( readonly ) &&
223 ( *method_type == 'c' || *method_type == 'u' || *method_type == 'd')
226 osrfHash* method_meta = osrfNewHash();
227 osrfHashSet(method_meta, idlClass, "class");
229 method_name = buffer_init(64);
231 buffer_fadd(method_name, "%s.%s.%s", MODULENAME, method_type, classname);
235 char* _fm = strdup( idlClass_fieldmapper );
236 part = strtok_r(_fm, ":", &st_tmp);
238 buffer_fadd(method_name, "%s.direct.%s", MODULENAME, part);
240 while ((part = strtok_r(NULL, ":", &st_tmp))) {
241 OSRF_BUFFER_ADD_CHAR(method_name, '.');
242 OSRF_BUFFER_ADD(method_name, part);
244 OSRF_BUFFER_ADD_CHAR(method_name, '.');
245 OSRF_BUFFER_ADD(method_name, method_type);
249 char* method = buffer_release(method_name);
251 osrfHashSet( method_meta, method, "methodname" );
252 osrfHashSet( method_meta, strdup(method_type), "methodtype" );
255 if (*method_type == 'i' || *method_type == 's') {
256 flags = flags | OSRF_METHOD_STREAMING;
259 osrfAppRegisterExtendedMethod(
262 "dispatchCRUDMethod",
276 static char* getSourceDefinition( osrfHash* class ) {
278 char* tabledef = osrfHashGet(class, "tablename");
281 growing_buffer* tablebuf = buffer_init(128);
282 tabledef = osrfHashGet(class, "source_definition");
285 buffer_fadd( tablebuf, "(%s)", tabledef );
286 tabledef = buffer_release(tablebuf);
288 tabledef = strdup(tabledef);
295 * Connects to the database
297 int osrfAppChildInit() {
299 osrfLogDebug(OSRF_LOG_MARK, "Attempting to initialize libdbi...");
300 dbi_initialize(NULL);
301 osrfLogDebug(OSRF_LOG_MARK, "... libdbi initialized.");
303 char* driver = osrf_settings_host_value("/apps/%s/app_settings/driver", MODULENAME);
304 char* user = osrf_settings_host_value("/apps/%s/app_settings/database/user", MODULENAME);
305 char* host = osrf_settings_host_value("/apps/%s/app_settings/database/host", MODULENAME);
306 char* port = osrf_settings_host_value("/apps/%s/app_settings/database/port", MODULENAME);
307 char* db = osrf_settings_host_value("/apps/%s/app_settings/database/db", MODULENAME);
308 char* pw = osrf_settings_host_value("/apps/%s/app_settings/database/pw", MODULENAME);
309 char* md = osrf_settings_host_value("/apps/%s/app_settings/max_query_recursion", MODULENAME);
311 osrfLogDebug(OSRF_LOG_MARK, "Attempting to load the database driver [%s]...", driver);
312 writehandle = dbi_conn_new(driver);
315 osrfLogError(OSRF_LOG_MARK, "Error loading database driver [%s]", driver);
318 osrfLogDebug(OSRF_LOG_MARK, "Database driver [%s] seems OK", driver);
320 osrfLogInfo(OSRF_LOG_MARK, "%s connecting to database. host=%s, "
321 "port=%s, user=%s, pw=%s, db=%s", MODULENAME, host, port, user, pw, db );
323 if(host) dbi_conn_set_option(writehandle, "host", host );
324 if(port) dbi_conn_set_option_numeric( writehandle, "port", atoi(port) );
325 if(user) dbi_conn_set_option(writehandle, "username", user);
326 if(pw) dbi_conn_set_option(writehandle, "password", pw );
327 if(db) dbi_conn_set_option(writehandle, "dbname", db );
329 if(md) max_flesh_depth = atoi(md);
330 if(max_flesh_depth < 0) max_flesh_depth = 1;
331 if(max_flesh_depth > 1000) max_flesh_depth = 1000;
340 if (dbi_conn_connect(writehandle) < 0) {
342 if (dbi_conn_connect(writehandle) < 0) {
343 dbi_conn_error(writehandle, &err);
344 osrfLogError( OSRF_LOG_MARK, "Error connecting to database: %s", err);
349 osrfLogInfo(OSRF_LOG_MARK, "%s successfully connected to the database", MODULENAME);
355 osrfStringArray* classes = osrfHashKeys( oilsIDL() );
357 while ( (classname = osrfStringArrayGetString(classes, i++)) ) {
358 osrfHash* class = osrfHashGet( oilsIDL(), classname );
359 osrfHash* fields = osrfHashGet( class, "fields" );
361 if( str_is_true( osrfHashGet(class, "virtual") ) ) {
362 osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
366 char* tabledef = getSourceDefinition(class);
368 growing_buffer* sql_buf = buffer_init(32);
369 buffer_fadd( sql_buf, "SELECT * FROM %s AS x WHERE 1=0;", tabledef );
373 char* sql = buffer_release(sql_buf);
374 osrfLogDebug(OSRF_LOG_MARK, "%s Investigatory SQL = %s", MODULENAME, sql);
376 dbi_result result = dbi_conn_query(writehandle, sql);
382 const char* columnName;
384 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
386 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
388 /* fetch the fieldmapper index */
389 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
391 osrfLogDebug(OSRF_LOG_MARK, "Found [%s] in IDL hash...", (char*)columnName);
393 /* determine the field type and storage attributes */
394 type = dbi_result_get_field_type(result, columnName);
395 attr = dbi_result_get_field_attribs(result, columnName);
399 case DBI_TYPE_INTEGER :
401 if ( !osrfHashGet(_f, "primitive") )
402 osrfHashSet(_f,"number", "primitive");
404 if( attr & DBI_INTEGER_SIZE8 )
405 osrfHashSet(_f,"INT8", "datatype");
407 osrfHashSet(_f,"INT", "datatype");
410 case DBI_TYPE_DECIMAL :
411 if ( !osrfHashGet(_f, "primitive") )
412 osrfHashSet(_f,"number", "primitive");
414 osrfHashSet(_f,"NUMERIC", "datatype");
417 case DBI_TYPE_STRING :
418 if ( !osrfHashGet(_f, "primitive") )
419 osrfHashSet(_f,"string", "primitive");
420 osrfHashSet(_f,"TEXT", "datatype");
423 case DBI_TYPE_DATETIME :
424 if ( !osrfHashGet(_f, "primitive") )
425 osrfHashSet(_f,"string", "primitive");
427 osrfHashSet(_f,"TIMESTAMP", "datatype");
430 case DBI_TYPE_BINARY :
431 if ( !osrfHashGet(_f, "primitive") )
432 osrfHashSet(_f,"string", "primitive");
434 osrfHashSet(_f,"BYTEA", "datatype");
439 "Setting [%s] to primitive [%s] and datatype [%s]...",
441 osrfHashGet(_f, "primitive"),
442 osrfHashGet(_f, "datatype")
446 dbi_result_free(result);
448 osrfLogDebug(OSRF_LOG_MARK, "No data found for class [%s]...", (char*)classname);
452 osrfStringArrayFree(classes);
457 void userDataFree( void* blob ) {
458 osrfHashFree( (osrfHash*)blob );
462 static void sessionDataFree( char* key, void* item ) {
463 if (!(strcmp(key,"xact_id"))) {
465 dbi_conn_query(writehandle, "ROLLBACK;");
472 int beginTransaction ( osrfMethodContext* ctx ) {
473 if(osrfMethodVerifyContext( ctx )) {
474 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
479 jsonObject* user = verifyUserPCRUD( ctx );
480 if (!user) return -1;
481 jsonObjectFree(user);
484 dbi_result result = dbi_conn_query(writehandle, "START TRANSACTION;");
486 osrfLogError(OSRF_LOG_MARK, "%s: Error starting transaction", MODULENAME );
487 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error starting transaction" );
490 jsonObject* ret = jsonNewObject(ctx->session->session_id);
491 osrfAppRespondComplete( ctx, ret );
494 if (!ctx->session->userData) {
495 ctx->session->userData = osrfNewHash();
496 osrfHashSetCallback((osrfHash*)ctx->session->userData, &sessionDataFree);
499 osrfHashSet( (osrfHash*)ctx->session->userData, strdup( ctx->session->session_id ), "xact_id" );
500 ctx->session->userDataFree = &userDataFree;
506 int setSavepoint ( osrfMethodContext* ctx ) {
507 if(osrfMethodVerifyContext( ctx )) {
508 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
515 jsonObject* user = verifyUserPCRUD( ctx );
516 if (!user) return -1;
517 jsonObjectFree(user);
520 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
521 osrfAppSessionStatus(
523 OSRF_STATUS_INTERNALSERVERERROR,
524 "osrfMethodException",
526 "No active transaction -- required for savepoints"
531 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
533 dbi_result result = dbi_conn_queryf(writehandle, "SAVEPOINT \"%s\";", spName);
537 "%s: Error creating savepoint %s in transaction %s",
540 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
542 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error creating savepoint" );
546 jsonObject* ret = jsonNewObject(spName);
547 osrfAppRespondComplete( ctx, ret );
554 int releaseSavepoint ( osrfMethodContext* ctx ) {
555 if(osrfMethodVerifyContext( ctx )) {
556 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
563 jsonObject* user = verifyUserPCRUD( ctx );
564 if (!user) return -1;
565 jsonObjectFree(user);
568 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
569 osrfAppSessionStatus(
571 OSRF_STATUS_INTERNALSERVERERROR,
572 "osrfMethodException",
574 "No active transaction -- required for savepoints"
579 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
581 dbi_result result = dbi_conn_queryf(writehandle, "RELEASE SAVEPOINT \"%s\";", spName);
585 "%s: Error releasing savepoint %s in transaction %s",
588 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
590 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error releasing savepoint" );
594 jsonObject* ret = jsonNewObject(spName);
595 osrfAppRespondComplete( ctx, ret );
602 int rollbackSavepoint ( osrfMethodContext* ctx ) {
603 if(osrfMethodVerifyContext( ctx )) {
604 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
611 jsonObject* user = verifyUserPCRUD( ctx );
612 if (!user) return -1;
613 jsonObjectFree(user);
616 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
617 osrfAppSessionStatus(
619 OSRF_STATUS_INTERNALSERVERERROR,
620 "osrfMethodException",
622 "No active transaction -- required for savepoints"
627 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
629 dbi_result result = dbi_conn_queryf(writehandle, "ROLLBACK TO SAVEPOINT \"%s\";", spName);
633 "%s: Error rolling back savepoint %s in transaction %s",
636 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
638 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back savepoint" );
642 jsonObject* ret = jsonNewObject(spName);
643 osrfAppRespondComplete( ctx, ret );
650 int commitTransaction ( osrfMethodContext* ctx ) {
651 if(osrfMethodVerifyContext( ctx )) {
652 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
657 jsonObject* user = verifyUserPCRUD( ctx );
658 if (!user) return -1;
659 jsonObjectFree(user);
662 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
663 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to commit" );
667 dbi_result result = dbi_conn_query(writehandle, "COMMIT;");
669 osrfLogError(OSRF_LOG_MARK, "%s: Error committing transaction", MODULENAME );
670 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error committing transaction" );
673 osrfHashRemove(ctx->session->userData, "xact_id");
674 jsonObject* ret = jsonNewObject(ctx->session->session_id);
675 osrfAppRespondComplete( ctx, ret );
681 int rollbackTransaction ( osrfMethodContext* ctx ) {
682 if(osrfMethodVerifyContext( ctx )) {
683 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
688 jsonObject* user = verifyUserPCRUD( ctx );
689 if (!user) return -1;
690 jsonObjectFree(user);
693 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
694 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to roll back" );
698 dbi_result result = dbi_conn_query(writehandle, "ROLLBACK;");
700 osrfLogError(OSRF_LOG_MARK, "%s: Error rolling back transaction", MODULENAME );
701 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back transaction" );
704 osrfHashRemove(ctx->session->userData, "xact_id");
705 jsonObject* ret = jsonNewObject(ctx->session->session_id);
706 osrfAppRespondComplete( ctx, ret );
712 int dispatchCRUDMethod ( osrfMethodContext* ctx ) {
713 if(osrfMethodVerifyContext( ctx )) {
714 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
718 osrfHash* meta = (osrfHash*) ctx->method->userData;
719 osrfHash* class_obj = osrfHashGet( meta, "class" );
723 const char* methodtype = osrfHashGet(meta, "methodtype");
724 jsonObject * obj = NULL;
726 if (!strcmp(methodtype, "create")) {
727 obj = doCreate(ctx, &err);
728 osrfAppRespondComplete( ctx, obj );
730 else if (!strcmp(methodtype, "retrieve")) {
731 obj = doRetrieve(ctx, &err);
732 osrfAppRespondComplete( ctx, obj );
734 else if (!strcmp(methodtype, "update")) {
735 obj = doUpdate(ctx, &err);
736 osrfAppRespondComplete( ctx, obj );
738 else if (!strcmp(methodtype, "delete")) {
739 obj = doDelete(ctx, &err);
740 osrfAppRespondComplete( ctx, obj );
742 else if (!strcmp(methodtype, "search")) {
744 jsonObject* _p = jsonObjectClone( ctx->params );
747 _p = jsonParseString("[]");
748 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 1)));
749 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 2)));
752 obj = doFieldmapperSearch(ctx, class_obj, _p, &err);
758 jsonIterator* itr = jsonNewIterator( obj );
759 while ((cur = jsonIteratorNext( itr ))) {
761 if(!verifyObjectPCRUD(ctx, cur)) continue;
763 osrfAppRespond( ctx, cur );
765 jsonIteratorFree(itr);
766 osrfAppRespondComplete( ctx, NULL );
768 } else if (!strcmp(methodtype, "id_list")) {
770 jsonObject* _p = jsonObjectClone( ctx->params );
773 _p = jsonParseString("[]");
774 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 1)));
775 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 2)));
778 if (jsonObjectGetIndex( _p, 1 )) {
779 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "select" );
780 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "no_i18n" );
781 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh" );
782 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh_columns" );
784 jsonObjectSetIndex( _p, 1, jsonNewObjectType(JSON_HASH) );
787 jsonObjectSetKey( jsonObjectGetIndex( _p, 1 ), "no_i18n", jsonNewBoolObject( 1 ) );
790 jsonObjectGetIndex( _p, 1 ),
793 "{ \"%s\":[\"%s\"] }",
794 osrfHashGet( class_obj, "classname" ),
795 osrfHashGet( class_obj, "primarykey" )
799 obj = doFieldmapperSearch(ctx, class_obj, _p, &err);
805 jsonIterator* itr = jsonNewIterator( obj );
806 while ((cur = jsonIteratorNext( itr ))) {
808 if(!verifyObjectPCRUD(ctx, cur)) continue;
812 oilsFMGetObject( cur, osrfHashGet( class_obj, "primarykey" ) )
815 jsonIteratorFree(itr);
816 osrfAppRespondComplete( ctx, NULL );
819 osrfAppRespondComplete( ctx, obj );
827 static int verifyObjectClass ( osrfMethodContext* ctx, const jsonObject* param ) {
830 osrfHash* meta = (osrfHash*) ctx->method->userData;
831 osrfHash* class = osrfHashGet( meta, "class" );
833 if (!param->classname || (strcmp( osrfHashGet(class, "classname"), param->classname ))) {
835 growing_buffer* msg = buffer_init(128);
838 "%s: %s method for type %s was passed a %s",
840 osrfHashGet(meta, "methodtype"),
841 osrfHashGet(class, "classname"),
845 char* m = buffer_release(msg);
846 osrfAppSessionStatus( ctx->session, OSRF_STATUS_BADREQUEST, "osrfMethodException", ctx->request, m );
854 ret = verifyObjectPCRUD( ctx, param );
862 static jsonObject* verifyUserPCRUD( osrfMethodContext* ctx ) {
863 char* auth = jsonObjectToSimpleString( jsonObjectGetIndex( ctx->params, 0 ) );
864 jsonObject* auth_object = jsonNewObject(auth);
865 jsonObject* user = oilsUtilsQuickReq("open-ils.auth","open-ils.auth.session.retrieve", auth_object);
866 jsonObjectFree(auth_object);
868 if (!user->classname || strcmp(user->classname, "au")) {
870 growing_buffer* msg = buffer_init(128);
873 "%s: permacrud received a bad auth token: %s",
878 char* m = buffer_release(msg);
879 osrfAppSessionStatus( ctx->session, OSRF_STATUS_UNAUTHORIZED, "osrfMethodException", ctx->request, m );
882 jsonObjectFree(user);
891 static int verifyObjectPCRUD ( osrfMethodContext* ctx, const jsonObject* obj ) {
893 dbhandle = writehandle;
895 osrfHash* meta = (osrfHash*) ctx->method->userData;
896 osrfHash* class = osrfHashGet( meta, "class" );
897 char* method_type = strdup( osrfHashGet(meta, "methodtype") );
900 if ( ( *method_type == 's' || *method_type == 'i' ) ) {
902 method_type = strdup("retrieve"); // search and id_list are equivelant to retrieve for this
903 } else if ( *method_type == 'u' || *method_type == 'd' ) {
904 fetch = 1; // MUST go to the db for the object for update and delete
907 osrfHash* pcrud = osrfHashGet( osrfHashGet(class, "permacrud"), method_type );
911 // No permacrud for this method type on this class
913 growing_buffer* msg = buffer_init(128);
916 "%s: %s on class %s has no permacrud IDL entry",
918 osrfHashGet(meta, "methodtype"),
919 osrfHashGet(class, "classname")
922 char* m = buffer_release(msg);
923 osrfAppSessionStatus( ctx->session, OSRF_STATUS_FORBIDDEN, "osrfMethodException", ctx->request, m );
930 jsonObject* user = verifyUserPCRUD( ctx );
933 int userid = atoi( oilsFMGetString( user, "id" ) );
934 jsonObjectFree(user);
936 osrfStringArray* permission = osrfHashGet(pcrud, "permission");
937 osrfStringArray* local_context = osrfHashGet(pcrud, "local_context");
938 osrfHash* foreign_context = osrfHashGet(pcrud, "foreign_context");
940 osrfStringArray* context_org_array = osrfNewStringArray(1);
943 char* pkey_value = NULL;
944 if ( str_is_true( osrfHashGet(pcrud, "global_required") ) ) {
945 osrfLogDebug( OSRF_LOG_MARK, "global-level permissions required, fetching top of the org tree" );
947 // check for perm at top of org tree
948 jsonObject* _tmp_params = jsonParseString("[{\"parent_ou\":null}]");
949 jsonObject* _list = doFieldmapperSearch(ctx, osrfHashGet( oilsIDL(), "aou" ), _tmp_params, &err);
951 jsonObject* _tree_top = jsonObjectGetIndex(_list, 0);
954 jsonObjectFree(_tmp_params);
955 jsonObjectFree(_list);
957 growing_buffer* msg = buffer_init(128);
958 OSRF_BUFFER_ADD( msg, MODULENAME );
959 OSRF_BUFFER_ADD( msg,
960 ": Internal error, could not find the top of the org tree (parent_ou = NULL)" );
962 char* m = buffer_release(msg);
963 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, m );
969 osrfStringArrayAdd( context_org_array, oilsFMGetString( _tree_top, "id" ) );
970 osrfLogDebug( OSRF_LOG_MARK, "top of the org tree is %s", osrfStringArrayGetString(context_org_array, 0) );
972 jsonObjectFree(_tmp_params);
973 jsonObjectFree(_list);
976 osrfLogDebug( OSRF_LOG_MARK, "global-level permissions not required, fetching context org ids" );
977 char* pkey = osrfHashGet(class, "primarykey");
978 jsonObject *param = NULL;
980 if (obj->classname) {
981 pkey_value = oilsFMGetString( obj, pkey );
982 if (!fetch) param = jsonObjectClone(obj);
983 osrfLogDebug( OSRF_LOG_MARK, "Object supplied, using primary key value of %s", pkey_value );
985 pkey_value = jsonObjectToSimpleString( obj );
987 osrfLogDebug( OSRF_LOG_MARK, "Object not supplied, using primary key value of %s and retrieving from the database", pkey_value );
991 jsonObject* _tmp_params = jsonParseStringFmt("[{\"%s\":\"%s\"}]", pkey, pkey_value);
992 jsonObject* _list = doFieldmapperSearch(
999 param = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1001 jsonObjectFree(_tmp_params);
1002 jsonObjectFree(_list);
1006 osrfLogDebug( OSRF_LOG_MARK, "Object not found in the database with primary key %s of %s", pkey, pkey_value );
1008 growing_buffer* msg = buffer_init(128);
1011 "%s: no object found with primary key %s of %s",
1017 char* m = buffer_release(msg);
1018 osrfAppSessionStatus(
1020 OSRF_STATUS_INTERNALSERVERERROR,
1021 "osrfMethodException",
1027 if (pkey_value) free(pkey_value);
1032 if (local_context->size > 0) {
1033 osrfLogDebug( OSRF_LOG_MARK, "%d class-local context field(s) specified", local_context->size);
1035 char* lcontext = NULL;
1036 while ( (lcontext = osrfStringArrayGetString(local_context, i++)) ) {
1037 osrfStringArrayAdd( context_org_array, oilsFMGetString( param, lcontext ) );
1040 "adding class-local field %s (value: %s) to the context org list",
1042 osrfStringArrayGetString(context_org_array, context_org_array->size - 1)
1047 osrfStringArray* class_list;
1049 if (foreign_context) {
1050 class_list = osrfHashKeys( foreign_context );
1051 osrfLogDebug( OSRF_LOG_MARK, "%d foreign context classes(s) specified", class_list->size);
1053 if (class_list->size > 0) {
1056 char* class_name = NULL;
1057 while ( (class_name = osrfStringArrayGetString(class_list, i++)) ) {
1058 osrfHash* fcontext = osrfHashGet(foreign_context, class_name);
1062 "%d foreign context fields(s) specified for class %s",
1063 ((osrfStringArray*)osrfHashGet(fcontext,"context"))->size,
1067 char* foreign_pkey = osrfHashGet(fcontext, "field");
1068 char* foreign_pkey_value = oilsFMGetString(param, osrfHashGet(fcontext, "fkey"));
1070 jsonObject* _tmp_params = jsonParseStringFmt(
1071 "[{\"%s\":\"%s\"}]",
1076 jsonObject* _list = doFieldmapperSearch(
1078 osrfHashGet( oilsIDL(), class_name ),
1083 jsonObject* _fparam = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1084 jsonObjectFree(_tmp_params);
1085 jsonObjectFree(_list);
1087 osrfStringArray* jump_list = osrfHashGet(fcontext, "jump");
1089 if (_fparam && jump_list) {
1092 while ( (flink = osrfStringArrayGetString(jump_list, k++)) && _fparam ) {
1093 free(foreign_pkey_value);
1095 osrfHash* foreign_link_hash = oilsIDLFindPath( "/%s/links/%s", _fparam->classname, flink );
1097 foreign_pkey_value = oilsFMGetString(_fparam, flink);
1098 foreign_pkey = osrfHashGet( foreign_link_hash, "key" );
1100 _tmp_params = jsonParseStringFmt(
1101 "[{\"%s\":\"%s\"}]",
1106 _list = doFieldmapperSearch(
1108 osrfHashGet( oilsIDL(), osrfHashGet( foreign_link_hash, "class" ) ),
1113 _fparam = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1114 jsonObjectFree(_tmp_params);
1115 jsonObjectFree(_list);
1122 growing_buffer* msg = buffer_init(128);
1125 "%s: no object found with primary key %s of %s",
1131 char* m = buffer_release(msg);
1132 osrfAppSessionStatus(
1134 OSRF_STATUS_INTERNALSERVERERROR,
1135 "osrfMethodException",
1141 osrfStringArrayFree(class_list);
1142 free(foreign_pkey_value);
1143 jsonObjectFree(param);
1148 free(foreign_pkey_value);
1151 char* foreign_field = NULL;
1152 while ( (foreign_field = osrfStringArrayGetString(osrfHashGet(fcontext,"context"), j++)) ) {
1153 osrfStringArrayAdd( context_org_array, oilsFMGetString( _fparam, foreign_field ) );
1156 "adding foreign class %s field %s (value: %s) to the context org list",
1159 osrfStringArrayGetString(context_org_array, context_org_array->size - 1)
1163 jsonObjectFree(_fparam);
1166 osrfStringArrayFree(class_list);
1170 jsonObjectFree(param);
1173 char* context_org = NULL;
1177 if (permission->size == 0) {
1178 osrfLogDebug( OSRF_LOG_MARK, "No permission specified for this action, passing through" );
1183 while ( (perm = osrfStringArrayGetString(permission, i++)) ) {
1185 while ( (context_org = osrfStringArrayGetString(context_org_array, j++)) ) {
1191 "Checking object permission [%s] for user %d on object %s (class %s) at org %d",
1195 osrfHashGet(class, "classname"),
1199 result = dbi_conn_queryf(
1201 "SELECT permission.usr_has_object_perm(%d, '%s', '%s', '%s', %d) AS has_perm;",
1204 osrfHashGet(class, "classname"),
1212 "Recieved a result for object permission [%s] for user %d on object %s (class %s) at org %d",
1216 osrfHashGet(class, "classname"),
1220 if (dbi_result_first_row(result)) {
1221 jsonObject* return_val = oilsMakeJSONFromResult( result );
1222 char* has_perm = jsonObjectToSimpleString( jsonObjectGetKeyConst(return_val, "has_perm") );
1226 "Status of object permission [%s] for user %d on object %s (class %s) at org %d is %s",
1230 osrfHashGet(class, "classname"),
1235 if ( *has_perm == 't' ) OK = 1;
1237 jsonObjectFree(return_val);
1240 dbi_result_free(result);
1245 osrfLogDebug( OSRF_LOG_MARK, "Checking non-object permission [%s] for user %d at org %d", perm, userid, atoi(context_org) );
1246 result = dbi_conn_queryf(
1248 "SELECT permission.usr_has_perm(%d, '%s', %d) AS has_perm;",
1255 osrfLogDebug( OSRF_LOG_MARK, "Recieved a result for permission [%s] for user %d at org %d", perm, userid, atoi(context_org) );
1256 if (dbi_result_first_row(result)) {
1257 jsonObject* return_val = oilsMakeJSONFromResult( result );
1258 char* has_perm = jsonObjectToSimpleString( jsonObjectGetKeyConst(return_val, "has_perm") );
1259 osrfLogDebug( OSRF_LOG_MARK, "Status of permission [%s] for user %d at org %d is [%s]", perm, userid, atoi(context_org), has_perm );
1260 if ( *has_perm == 't' ) OK = 1;
1262 jsonObjectFree(return_val);
1265 dbi_result_free(result);
1273 if (pkey_value) free(pkey_value);
1274 osrfStringArrayFree(context_org_array);
1281 static jsonObject* doCreate(osrfMethodContext* ctx, int* err ) {
1283 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1285 jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
1286 jsonObject* options = jsonObjectGetIndex( ctx->params, 2 );
1288 jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
1289 jsonObject* options = jsonObjectGetIndex( ctx->params, 1 );
1292 if (!verifyObjectClass(ctx, target)) {
1297 osrfLogDebug( OSRF_LOG_MARK, "Object seems to be of the correct type" );
1299 if (!ctx->session || !ctx->session->userData || !osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
1300 osrfLogError( OSRF_LOG_MARK, "No active transaction -- required for CREATE" );
1302 osrfAppSessionStatus(
1304 OSRF_STATUS_BADREQUEST,
1305 "osrfMethodException",
1307 "No active transaction -- required for CREATE"
1313 // The following test is harmless but redundant. If a class is
1314 // readonly, we don't register a create method for it.
1315 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
1316 osrfAppSessionStatus(
1318 OSRF_STATUS_BADREQUEST,
1319 "osrfMethodException",
1321 "Cannot INSERT readonly class"
1328 char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
1330 // Set the last_xact_id
1331 int index = oilsIDL_ntop( target->classname, "last_xact_id" );
1333 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
1334 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
1337 osrfLogDebug( OSRF_LOG_MARK, "There is a transaction running..." );
1339 dbhandle = writehandle;
1341 osrfHash* fields = osrfHashGet(meta, "fields");
1342 char* pkey = osrfHashGet(meta, "primarykey");
1343 char* seq = osrfHashGet(meta, "sequence");
1345 growing_buffer* table_buf = buffer_init(128);
1346 growing_buffer* col_buf = buffer_init(128);
1347 growing_buffer* val_buf = buffer_init(128);
1349 OSRF_BUFFER_ADD(table_buf, "INSERT INTO ");
1350 OSRF_BUFFER_ADD(table_buf, osrfHashGet(meta, "tablename"));
1351 OSRF_BUFFER_ADD_CHAR( col_buf, '(' );
1352 buffer_add(val_buf,"VALUES (");
1358 osrfStringArray* field_list = osrfHashKeys( fields );
1359 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
1361 osrfHash* field = osrfHashGet( fields, field_name );
1363 if( str_is_true( osrfHashGet( field, "virtual" ) ) )
1366 const jsonObject* field_object = oilsFMGetObject( target, field_name );
1369 if (field_object && field_object->classname) {
1370 value = oilsFMGetString(
1372 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
1375 value = jsonObjectToSimpleString( field_object );
1382 OSRF_BUFFER_ADD_CHAR( col_buf, ',' );
1383 OSRF_BUFFER_ADD_CHAR( val_buf, ',' );
1386 buffer_add(col_buf, field_name);
1388 if (!field_object || field_object->type == JSON_NULL) {
1389 buffer_add( val_buf, "DEFAULT" );
1391 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1392 if ( !strcmp(osrfHashGet(field, "datatype"), "INT8") ) {
1393 buffer_fadd( val_buf, "%lld", atoll(value) );
1395 } else if ( !strcmp(osrfHashGet(field, "datatype"), "INT") ) {
1396 buffer_fadd( val_buf, "%d", atoi(value) );
1398 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
1399 buffer_fadd( val_buf, "%f", atof(value) );
1402 if ( dbi_conn_quote_string(writehandle, &value) ) {
1403 OSRF_BUFFER_ADD( val_buf, value );
1406 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
1407 osrfAppSessionStatus(
1409 OSRF_STATUS_INTERNALSERVERERROR,
1410 "osrfMethodException",
1412 "Error quoting string -- please see the error log for more details"
1415 buffer_free(table_buf);
1416 buffer_free(col_buf);
1417 buffer_free(val_buf);
1428 OSRF_BUFFER_ADD_CHAR( col_buf, ')' );
1429 OSRF_BUFFER_ADD_CHAR( val_buf, ')' );
1431 char* table_str = buffer_release(table_buf);
1432 char* col_str = buffer_release(col_buf);
1433 char* val_str = buffer_release(val_buf);
1434 growing_buffer* sql = buffer_init(128);
1435 buffer_fadd( sql, "%s %s %s;", table_str, col_str, val_str );
1440 char* query = buffer_release(sql);
1442 osrfLogDebug(OSRF_LOG_MARK, "%s: Insert SQL [%s]", MODULENAME, query);
1445 dbi_result result = dbi_conn_query(writehandle, query);
1447 jsonObject* obj = NULL;
1450 obj = jsonNewObject(NULL);
1453 "%s ERROR inserting %s object using query [%s]",
1455 osrfHashGet(meta, "fieldmapper"),
1458 osrfAppSessionStatus(
1460 OSRF_STATUS_INTERNALSERVERERROR,
1461 "osrfMethodException",
1463 "INSERT error -- please see the error log for more details"
1468 char* id = oilsFMGetString(target, pkey);
1470 unsigned long long new_id = dbi_conn_sequence_last(writehandle, seq);
1471 growing_buffer* _id = buffer_init(10);
1472 buffer_fadd(_id, "%lld", new_id);
1473 id = buffer_release(_id);
1476 // Find quietness specification, if present
1477 char* quiet_str = NULL;
1479 const jsonObject* quiet_obj = jsonObjectGetKeyConst( options, "quiet" );
1481 quiet_str = jsonObjectToSimpleString( quiet_obj );
1484 if( str_is_true( quiet_str ) ) { // if quietness is specified
1485 obj = jsonNewObject(id);
1489 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
1490 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH));
1493 jsonObjectGetIndex(fake_params, 0),
1498 jsonObject* list = doFieldmapperSearch( ctx,meta, fake_params, err);
1501 jsonObjectFree( fake_params );
1504 obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
1507 jsonObjectFree( list );
1508 jsonObjectFree( fake_params );
1511 if(quiet_str) free(quiet_str);
1522 static jsonObject* doRetrieve(osrfMethodContext* ctx, int* err ) {
1532 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1534 char* id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, id_pos));
1535 jsonObject* order_hash = jsonObjectGetIndex(ctx->params, order_pos);
1539 "%s retrieving %s object with primary key value of %s",
1541 osrfHashGet(meta, "fieldmapper"),
1546 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
1547 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH));
1550 jsonObjectGetIndex(fake_params, 0),
1551 osrfHashGet(meta, "primarykey"),
1552 jsonObjectClone(jsonObjectGetIndex(ctx->params, id_pos))
1556 if (order_hash) jsonObjectPush(fake_params, jsonObjectClone(order_hash) );
1558 jsonObject* list = doFieldmapperSearch( ctx,meta, fake_params, err);
1561 jsonObjectFree( fake_params );
1565 jsonObject* obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
1567 jsonObjectFree( list );
1568 jsonObjectFree( fake_params );
1571 if(!verifyObjectPCRUD(ctx, obj)) {
1572 jsonObjectFree(obj);
1575 growing_buffer* msg = buffer_init(128);
1576 OSRF_BUFFER_ADD( msg, MODULENAME );
1577 OSRF_BUFFER_ADD( msg, ": Insufficient permissions to retrieve object" );
1579 char* m = buffer_release(msg);
1580 osrfAppSessionStatus( ctx->session, OSRF_STATUS_NOTALLOWED, "osrfMethodException", ctx->request, m );
1591 static char* jsonNumberToDBString ( osrfHash* field, const jsonObject* value ) {
1592 growing_buffer* val_buf = buffer_init(32);
1594 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
1595 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%ld", (long)jsonObjectGetNumber(value) );
1597 char* val_str = jsonObjectToSimpleString(value);
1598 buffer_fadd( val_buf, "%ld", atol(val_str) );
1602 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
1603 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%f", jsonObjectGetNumber(value) );
1605 char* val_str = jsonObjectToSimpleString(value);
1606 buffer_fadd( val_buf, "%f", atof(val_str) );
1611 return buffer_release(val_buf);
1614 static char* searchINPredicate (const char* class, osrfHash* field,
1615 jsonObject* node, const char* op, osrfMethodContext* ctx ) {
1616 growing_buffer* sql_buf = buffer_init(32);
1622 osrfHashGet(field, "name")
1626 buffer_add(sql_buf, "IN (");
1627 } else if (!(strcasecmp(op,"not in"))) {
1628 buffer_add(sql_buf, "NOT IN (");
1630 buffer_add(sql_buf, "IN (");
1633 if (node->type == JSON_HASH) {
1634 // subquery predicate
1635 char* subpred = SELECT(
1637 jsonObjectGetKey( node, "select" ),
1638 jsonObjectGetKey( node, "from" ),
1639 jsonObjectGetKey( node, "where" ),
1640 jsonObjectGetKey( node, "having" ),
1641 jsonObjectGetKey( node, "order_by" ),
1642 jsonObjectGetKey( node, "limit" ),
1643 jsonObjectGetKey( node, "offset" ),
1647 buffer_add(sql_buf, subpred);
1650 } else if (node->type == JSON_ARRAY) {
1651 // litteral value list
1652 int in_item_index = 0;
1653 int in_item_first = 1;
1654 jsonObject* in_item;
1655 while ( (in_item = jsonObjectGetIndex(node, in_item_index++)) ) {
1660 buffer_add(sql_buf, ", ");
1662 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1663 char* val = jsonNumberToDBString( field, in_item );
1664 OSRF_BUFFER_ADD( sql_buf, val );
1668 char* key_string = jsonObjectToSimpleString(in_item);
1669 if ( dbi_conn_quote_string(dbhandle, &key_string) ) {
1670 OSRF_BUFFER_ADD( sql_buf, key_string );
1673 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, key_string);
1675 buffer_free(sql_buf);
1682 OSRF_BUFFER_ADD_CHAR( sql_buf, ')' );
1684 return buffer_release(sql_buf);
1687 // Receive a JSON_ARRAY representing a function call. The first
1688 // entry in the array is the function name. The rest are parameters.
1689 static char* searchValueTransform( const jsonObject* array ) {
1690 growing_buffer* sql_buf = buffer_init(32);
1693 jsonObject* func_item;
1695 // Get the function name
1696 if( array->size > 0 ) {
1697 func_item = jsonObjectGetIndex( array, 0 );
1698 val = jsonObjectToSimpleString( func_item );
1699 OSRF_BUFFER_ADD( sql_buf, val );
1700 OSRF_BUFFER_ADD( sql_buf, "( " );
1704 // Get the parameters
1705 int func_item_index = 1; // We already grabbed the zeroth entry
1706 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1708 // Add a separator comma, if we need one
1709 if( func_item_index > 2 )
1710 buffer_add( sql_buf, ", " );
1712 // Add the current parameter
1713 if (func_item->type == JSON_NULL) {
1714 buffer_add( sql_buf, "NULL" );
1716 val = jsonObjectToSimpleString(func_item);
1717 if ( dbi_conn_quote_string(dbhandle, &val) ) {
1718 OSRF_BUFFER_ADD( sql_buf, val );
1721 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1722 buffer_free(sql_buf);
1729 buffer_add( sql_buf, " )" );
1731 return buffer_release(sql_buf);
1734 static char* searchFunctionPredicate (const char* class, osrfHash* field,
1735 const jsonObject* node, const char* node_key) {
1736 growing_buffer* sql_buf = buffer_init(32);
1738 char* val = searchValueTransform(node);
1744 osrfHashGet(field, "name"),
1751 return buffer_release(sql_buf);
1754 // class is a class name
1755 // field is a field definition as stored in the IDL
1756 // node comes from the method parameter, and represents an entry in the SELECT list
1757 static char* searchFieldTransform (const char* class, osrfHash* field, const jsonObject* node) {
1758 growing_buffer* sql_buf = buffer_init(32);
1760 char* field_transform = jsonObjectToSimpleString( jsonObjectGetKeyConst( node, "transform" ) );
1761 char* transform_subcolumn = jsonObjectToSimpleString( jsonObjectGetKeyConst( node, "result_field" ) );
1763 if(transform_subcolumn)
1764 OSRF_BUFFER_ADD_CHAR( sql_buf, '(' ); // enclose transform in parentheses
1766 if (field_transform) {
1767 buffer_fadd( sql_buf, "%s(\"%s\".%s", field_transform, class, osrfHashGet(field, "name"));
1768 const jsonObject* array = jsonObjectGetKeyConst( node, "params" );
1771 int func_item_index = 0;
1772 jsonObject* func_item;
1773 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1775 char* val = jsonObjectToSimpleString(func_item);
1778 buffer_add( sql_buf, ",NULL" );
1779 } else if ( dbi_conn_quote_string(dbhandle, &val) ) {
1780 OSRF_BUFFER_ADD_CHAR( sql_buf, ',' );
1781 OSRF_BUFFER_ADD( sql_buf, val );
1783 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1784 free(transform_subcolumn);
1785 free(field_transform);
1787 buffer_free(sql_buf);
1794 buffer_add( sql_buf, " )" );
1797 buffer_fadd( sql_buf, "\"%s\".%s", class, osrfHashGet(field, "name"));
1800 if (transform_subcolumn)
1801 buffer_fadd( sql_buf, ").\"%s\"", transform_subcolumn );
1803 if (field_transform) free(field_transform);
1804 if (transform_subcolumn) free(transform_subcolumn);
1806 return buffer_release(sql_buf);
1809 static char* searchFieldTransformPredicate (const char* class, osrfHash* field, jsonObject* node, const char* node_key) {
1810 char* field_transform = searchFieldTransform( class, field, node );
1813 if (!jsonObjectGetKeyConst( node, "value" )) {
1814 value = searchWHERE( node, osrfHashGet( oilsIDL(), class ), AND_OP_JOIN, NULL );
1815 } else if (jsonObjectGetKeyConst( node, "value" )->type == JSON_ARRAY) {
1816 value = searchValueTransform(jsonObjectGetKeyConst( node, "value" ));
1817 } else if (jsonObjectGetKeyConst( node, "value" )->type == JSON_HASH) {
1818 value = searchWHERE( jsonObjectGetKeyConst( node, "value" ), osrfHashGet( oilsIDL(), class ), AND_OP_JOIN, NULL );
1819 } else if (jsonObjectGetKeyConst( node, "value" )->type != JSON_NULL) {
1820 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1821 value = jsonNumberToDBString( field, jsonObjectGetKeyConst( node, "value" ) );
1823 value = jsonObjectToSimpleString(jsonObjectGetKeyConst( node, "value" ));
1824 if ( !dbi_conn_quote_string(dbhandle, &value) ) {
1825 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, value);
1827 free(field_transform);
1833 growing_buffer* sql_buf = buffer_init(32);
1844 free(field_transform);
1846 return buffer_release(sql_buf);
1849 static char* searchSimplePredicate (const char* orig_op, const char* class,
1850 osrfHash* field, const jsonObject* node) {
1854 if (node->type != JSON_NULL) {
1855 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1856 val = jsonNumberToDBString( field, node );
1858 val = jsonObjectToSimpleString(node);
1862 char* pred = searchWriteSimplePredicate( class, field, osrfHashGet(field, "name"), orig_op, val );
1869 static char* searchWriteSimplePredicate ( const char* class, osrfHash* field,
1870 const char* left, const char* orig_op, const char* right ) {
1874 if (right == NULL) {
1875 val = strdup("NULL");
1877 if (strcmp( orig_op, "=" ))
1878 op = strdup("IS NOT");
1882 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1883 val = strdup(right);
1884 op = strdup(orig_op);
1887 val = strdup(right);
1888 if ( !dbi_conn_quote_string(dbhandle, &val) ) {
1889 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1893 op = strdup(orig_op);
1896 growing_buffer* sql_buf = buffer_init(16);
1897 buffer_fadd( sql_buf, "\"%s\".%s %s %s", class, left, op, val );
1901 return buffer_release(sql_buf);
1904 static char* searchBETWEENPredicate (const char* class, osrfHash* field, jsonObject* node) {
1909 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1910 x_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,0));
1911 y_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,1));
1914 x_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,0));
1915 y_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,1));
1916 if ( !(dbi_conn_quote_string(dbhandle, &x_string) && dbi_conn_quote_string(dbhandle, &y_string)) ) {
1917 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key strings [%s] and [%s]", MODULENAME, x_string, y_string);
1924 growing_buffer* sql_buf = buffer_init(32);
1925 buffer_fadd( sql_buf, "%s BETWEEN %s AND %s", osrfHashGet(field, "name"), x_string, y_string );
1929 return buffer_release(sql_buf);
1932 static char* searchPredicate ( const char* class, osrfHash* field,
1933 jsonObject* node, osrfMethodContext* ctx ) {
1936 if (node->type == JSON_ARRAY) { // equality IN search
1937 pred = searchINPredicate( class, field, node, NULL, ctx );
1938 } else if (node->type == JSON_HASH) { // non-equality search
1939 jsonObject* pred_node;
1940 jsonIterator* pred_itr = jsonNewIterator( node );
1941 while ( (pred_node = jsonIteratorNext( pred_itr )) ) {
1942 if ( !(strcasecmp( pred_itr->key,"between" )) )
1943 pred = searchBETWEENPredicate( class, field, pred_node );
1944 else if ( !(strcasecmp( pred_itr->key,"in" )) || !(strcasecmp( pred_itr->key,"not in" )) )
1945 pred = searchINPredicate( class, field, pred_node, pred_itr->key, ctx );
1946 else if ( pred_node->type == JSON_ARRAY )
1947 pred = searchFunctionPredicate( class, field, pred_node, pred_itr->key );
1948 else if ( pred_node->type == JSON_HASH )
1949 pred = searchFieldTransformPredicate( class, field, pred_node, pred_itr->key );
1951 pred = searchSimplePredicate( pred_itr->key, class, field, pred_node );
1955 jsonIteratorFree(pred_itr);
1956 } else if (node->type == JSON_NULL) { // IS NULL search
1957 growing_buffer* _p = buffer_init(64);
1960 "\"%s\".%s IS NULL",
1962 osrfHashGet(field, "name")
1964 pred = buffer_release(_p);
1965 } else { // equality search
1966 pred = searchSimplePredicate( "=", class, field, node );
1985 field : call_number,
2001 static char* searchJOIN ( const jsonObject* join_hash, osrfHash* leftmeta ) {
2003 const jsonObject* working_hash;
2004 jsonObject* freeable_hash = NULL;
2006 if (join_hash->type == JSON_STRING) {
2007 // create a wrapper around a copy of the original
2008 char* _tmp = jsonObjectToSimpleString( join_hash );
2009 freeable_hash = jsonNewObjectType(JSON_HASH);
2010 jsonObjectSetKey(freeable_hash, _tmp, NULL);
2012 working_hash = freeable_hash;
2015 working_hash = join_hash;
2017 growing_buffer* join_buf = buffer_init(128);
2018 const char* leftclass = osrfHashGet(leftmeta, "classname");
2020 jsonObject* snode = NULL;
2021 jsonIterator* search_itr = jsonNewIterator( working_hash );
2023 jsonObjectFree(freeable_hash);
2025 while ( (snode = jsonIteratorNext( search_itr )) ) {
2026 osrfHash* idlClass = osrfHashGet( oilsIDL(), search_itr->key );
2028 const char* class = osrfHashGet(idlClass, "classname");
2030 char* fkey = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "fkey" ) );
2031 char* field = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "field" ) );
2033 if (field && !fkey) {
2034 fkey = (char*)oilsIDLFindPath("/%s/links/%s/key", class, field);
2038 "%s: JOIN failed. No link defined from %s.%s to %s",
2044 buffer_free(join_buf);
2046 jsonIteratorFree(search_itr);
2049 fkey = strdup( fkey );
2051 } else if (!field && fkey) {
2052 field = (char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, fkey );
2056 "%s: JOIN failed. No link defined from %s.%s to %s",
2062 buffer_free(join_buf);
2064 jsonIteratorFree(search_itr);
2067 field = strdup( field );
2069 } else if (!field && !fkey) {
2070 osrfHash* _links = oilsIDLFindPath("/%s/links", leftclass);
2073 const char* tmp_fkey;
2074 osrfStringArray* keys = osrfHashKeys( _links );
2075 while ( (tmp_fkey = osrfStringArrayGetString(keys, i++)) ) {
2076 if ( !strcmp( (char*)oilsIDLFindPath("/%s/links/%s/class", leftclass, tmp_fkey), class) ) {
2077 field = strdup( (char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, tmp_fkey) );
2078 fkey = strdup(tmp_fkey);
2082 osrfStringArrayFree(keys);
2084 if (!field && !fkey) {
2085 _links = oilsIDLFindPath("/%s/links", class);
2088 const char* tmp_fld;
2089 keys = osrfHashKeys( _links );
2090 while ( (tmp_fld = osrfStringArrayGetString(keys, i++)) ) {
2091 if ( !strcmp( (char*)oilsIDLFindPath("/%s/links/%s/class", class, tmp_fld), class) ) {
2092 fkey = strdup( (char*)oilsIDLFindPath("/%s/links/%s/key", class, tmp_fld) );
2093 field = strdup( tmp_fld );
2097 osrfStringArrayFree(keys);
2100 if (!field && !fkey) {
2103 "%s: JOIN failed. No link defined between %s and %s",
2108 buffer_free(join_buf);
2109 jsonIteratorFree(search_itr);
2115 char* type = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "type" ) );
2117 if ( !strcasecmp(type,"left") ) {
2118 buffer_add(join_buf, " LEFT JOIN");
2119 } else if ( !strcasecmp(type,"right") ) {
2120 buffer_add(join_buf, " RIGHT JOIN");
2121 } else if ( !strcasecmp(type,"full") ) {
2122 buffer_add(join_buf, " FULL JOIN");
2124 buffer_add(join_buf, " INNER JOIN");
2127 buffer_add(join_buf, " INNER JOIN");
2131 char* table = getSourceDefinition(idlClass);
2132 buffer_fadd(join_buf, " %s AS \"%s\" ON ( \"%s\".%s = \"%s\".%s",
2133 table, class, class, field, leftclass, fkey);
2136 const jsonObject* filter = jsonObjectGetKeyConst( snode, "filter" );
2138 char* filter_op = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "filter_op" ) );
2140 if (!strcasecmp("or",filter_op)) {
2141 buffer_add( join_buf, " OR " );
2143 buffer_add( join_buf, " AND " );
2146 buffer_add( join_buf, " AND " );
2149 char* jpred = searchWHERE( filter, idlClass, AND_OP_JOIN, NULL );
2150 OSRF_BUFFER_ADD_CHAR( join_buf, ' ' );
2151 OSRF_BUFFER_ADD( join_buf, jpred );
2156 buffer_add(join_buf, " ) ");
2158 const jsonObject* join_filter = jsonObjectGetKeyConst( snode, "join" );
2160 char* jpred = searchJOIN( join_filter, idlClass );
2161 OSRF_BUFFER_ADD_CHAR( join_buf, ' ' );
2162 OSRF_BUFFER_ADD( join_buf, jpred );
2170 jsonIteratorFree(search_itr);
2172 return buffer_release(join_buf);
2177 { +class : { -or|-and : { field : { op : value }, ... } ... }, ... }
2178 { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }
2179 [ { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }, ... ]
2183 static char* searchWHERE ( const jsonObject* search_hash, osrfHash* meta, int opjoin_type, osrfMethodContext* ctx ) {
2187 "%s: Entering searchWHERE; search_hash addr = %p, meta addr = %p, opjoin_type = %d, ctx addr = %p",
2195 growing_buffer* sql_buf = buffer_init(128);
2197 jsonObject* node = NULL;
2200 if ( search_hash->type == JSON_ARRAY ) {
2201 osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_ARRAY", MODULENAME);
2202 jsonIterator* search_itr = jsonNewIterator( search_hash );
2203 while ( (node = jsonIteratorNext( search_itr )) ) {
2207 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2208 else buffer_add(sql_buf, " AND ");
2211 char* subpred = searchWHERE( node, meta, opjoin_type, ctx );
2212 buffer_fadd(sql_buf, "( %s )", subpred);
2215 jsonIteratorFree(search_itr);
2217 } else if ( search_hash->type == JSON_HASH ) {
2218 osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_HASH", MODULENAME);
2219 jsonIterator* search_itr = jsonNewIterator( search_hash );
2220 while ( (node = jsonIteratorNext( search_itr )) ) {
2225 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2226 else buffer_add(sql_buf, " AND ");
2229 if ( !strncmp("+",search_itr->key,1) ) {
2230 if ( node->type == JSON_STRING ) {
2231 char* subpred = jsonObjectToSimpleString( node );
2232 buffer_fadd(sql_buf, " \"%s\".%s ", search_itr->key + 1, subpred);
2235 char* subpred = searchWHERE( node, osrfHashGet( oilsIDL(), search_itr->key + 1 ), AND_OP_JOIN, ctx );
2236 buffer_fadd(sql_buf, "( %s )", subpred);
2239 } else if ( !strcasecmp("-or",search_itr->key) ) {
2240 char* subpred = searchWHERE( node, meta, OR_OP_JOIN, ctx );
2241 buffer_fadd(sql_buf, "( %s )", subpred);
2243 } else if ( !strcasecmp("-and",search_itr->key) ) {
2244 char* subpred = searchWHERE( node, meta, AND_OP_JOIN, ctx );
2245 buffer_fadd(sql_buf, "( %s )", subpred);
2247 } else if ( !strcasecmp("-exists",search_itr->key) ) {
2248 char* subpred = SELECT(
2250 jsonObjectGetKey( node, "select" ),
2251 jsonObjectGetKey( node, "from" ),
2252 jsonObjectGetKey( node, "where" ),
2253 jsonObjectGetKey( node, "having" ),
2254 jsonObjectGetKey( node, "order_by" ),
2255 jsonObjectGetKey( node, "limit" ),
2256 jsonObjectGetKey( node, "offset" ),
2260 buffer_fadd(sql_buf, "EXISTS ( %s )", subpred);
2262 } else if ( !strcasecmp("-not-exists",search_itr->key) ) {
2263 char* subpred = SELECT(
2265 jsonObjectGetKey( node, "select" ),
2266 jsonObjectGetKey( node, "from" ),
2267 jsonObjectGetKey( node, "where" ),
2268 jsonObjectGetKey( node, "having" ),
2269 jsonObjectGetKey( node, "order_by" ),
2270 jsonObjectGetKey( node, "limit" ),
2271 jsonObjectGetKey( node, "offset" ),
2275 buffer_fadd(sql_buf, "NOT EXISTS ( %s )", subpred);
2279 char* class = osrfHashGet(meta, "classname");
2280 osrfHash* fields = osrfHashGet(meta, "fields");
2281 osrfHash* field = osrfHashGet( fields, search_itr->key );
2285 char* table = getSourceDefinition(meta);
2288 "%s: Attempt to reference non-existent column %s on %s (%s)",
2294 buffer_free(sql_buf);
2296 jsonIteratorFree(search_itr);
2300 char* subpred = searchPredicate( class, field, node, ctx );
2301 buffer_add( sql_buf, subpred );
2305 jsonIteratorFree(search_itr);
2308 // ERROR ... only hash and array allowed at this level
2309 char* predicate_string = jsonObjectToJSON( search_hash );
2312 "%s: Invalid predicate structure: %s",
2316 buffer_free(sql_buf);
2317 free(predicate_string);
2322 return buffer_release(sql_buf);
2326 /* method context */ osrfMethodContext* ctx,
2328 /* SELECT */ jsonObject* selhash,
2329 /* FROM */ jsonObject* join_hash,
2330 /* WHERE */ jsonObject* search_hash,
2331 /* HAVING */ jsonObject* having_hash,
2332 /* ORDER BY */ jsonObject* order_hash,
2333 /* LIMIT */ jsonObject* limit,
2334 /* OFFSET */ jsonObject* offset,
2335 /* flags */ int flags
2337 const char* locale = osrf_message_get_last_locale();
2339 // in case we don't get a select list
2340 jsonObject* defaultselhash = NULL;
2342 // general tmp objects
2343 const jsonObject* tmp_const;
2344 jsonObject* selclass = NULL;
2345 jsonObject* selfield = NULL;
2346 jsonObject* snode = NULL;
2347 jsonObject* onode = NULL;
2349 char* string = NULL;
2350 int from_function = 0;
2355 // the core search class
2356 char* core_class = NULL;
2358 // metadata about the core search class
2359 osrfHash* core_meta = NULL;
2361 // punt if there's no core class
2362 if (!join_hash || ( join_hash->type == JSON_HASH && !join_hash->size ))
2365 // get the core class -- the only key of the top level FROM clause, or a string
2366 if (join_hash->type == JSON_HASH) {
2367 jsonIterator* tmp_itr = jsonNewIterator( join_hash );
2368 snode = jsonIteratorNext( tmp_itr );
2370 core_class = strdup( tmp_itr->key );
2373 jsonObject* extra = jsonIteratorNext( tmp_itr );
2375 jsonIteratorFree( tmp_itr );
2378 // There shouldn't be more than one entry in join_hash
2380 return NULL; // Malformed join_hash; extra entry
2382 } else if (join_hash->type == JSON_ARRAY) {
2384 core_class = jsonObjectToSimpleString( jsonObjectGetIndex(join_hash, 0) );
2387 } else if (join_hash->type == JSON_STRING) {
2388 core_class = jsonObjectToSimpleString( join_hash );
2394 // punt if we don't know about the core class (and it's not a function)
2395 if (!from_function && !(core_meta = osrfHashGet( oilsIDL(), core_class ))) {
2400 // if the select list is empty, or the core class field list is '*',
2401 // build the default select list ...
2403 selhash = defaultselhash = jsonNewObjectType(JSON_HASH);
2404 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2405 } else if ( (tmp_const = jsonObjectGetKeyConst( selhash, core_class )) && tmp_const->type == JSON_STRING ) {
2406 char* _x = jsonObjectToSimpleString( tmp_const );
2407 if (!strncmp( "*", _x, 1 )) {
2408 jsonObjectRemoveKey( selhash, core_class );
2409 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2415 growing_buffer* sql_buf = buffer_init(128);
2417 // temp buffer for the SELECT list
2418 growing_buffer* select_buf = buffer_init(128);
2419 growing_buffer* order_buf = buffer_init(128);
2420 growing_buffer* group_buf = buffer_init(128);
2421 growing_buffer* having_buf = buffer_init(128);
2423 // Build a select list
2424 if(from_function) // From a function we select everything
2425 OSRF_BUFFER_ADD_CHAR( select_buf, '*' );
2428 // If we need to build a default list, do so
2429 jsonObject* _tmp = jsonObjectGetKey( selhash, core_class );
2430 if ( _tmp && !_tmp->size ) {
2434 osrfHash* core_fields = osrfHashGet( core_meta, "fields" );
2436 osrfStringArray* keys = osrfHashKeys( core_fields );
2437 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
2438 if( ! str_is_true( osrfHashGet( osrfHashGet( core_fields, field ), "virtual" ) ) )
2439 jsonObjectPush( _tmp, jsonNewObject( field ) ); // not virtual; use it
2441 osrfStringArrayFree(keys);
2444 // Now build the actual select list
2446 jsonObject* is_agg = jsonObjectFindPath(selhash, "//aggregate");
2449 jsonIterator* selclass_itr = jsonNewIterator( selhash );
2450 while ( (selclass = jsonIteratorNext( selclass_itr )) ) { // For each class
2452 // round trip through the idl, just to be safe
2453 const char* cname = selclass_itr->key;
2454 osrfHash* idlClass = osrfHashGet( oilsIDL(), cname );
2456 // No such class. Skip it.
2459 // Make sure the target relation is in the join tree.
2461 // At this point join_hash is a step down from the join_hash we
2462 // received as a parameter. If the original was a JSON_STRING,
2463 // then json_hash is now NULL. If the original was a JSON_HASH,
2464 // then json_hash is now the first (and only) entry in it,
2465 // denoting the core class. We've already excluded the
2466 // possibility that the original was a JSON_ARRAY, because in
2467 // that case from_function would be non-NULL, and we wouldn't
2470 if ( strcmp( core_class, cname )) {
2472 // There's only one class in the FROM clause,
2473 // and this isn't it. Skip it.
2476 if (join_hash->type == JSON_STRING) {
2477 string = jsonObjectToSimpleString(join_hash);
2478 int different = strcmp( string, cname );
2481 // There's only one class in the FROM clause,
2482 // and this isn't it. Skip it.
2485 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", cname);
2486 unsigned long size = found->size;
2487 jsonObjectFree( found );
2489 // No such class anywhere in the join tree. Skip it.
2494 // Look up some attributes of the current class, so that we
2495 // don't have to look them up again for each field
2496 osrfHash* class_field_set = osrfHashGet( idlClass, "fields" );
2497 char* class_pkey = osrfHashGet( idlClass, "primarykey" );
2498 char* class_tname = osrfHashGet( idlClass, "tablename" );
2500 // stitch together the column list ...
2501 jsonIterator* select_itr = jsonNewIterator( selclass );
2502 while ( (selfield = jsonIteratorNext( select_itr )) ) { // for each SELECT column
2504 // If we need a separator comma, add one
2508 OSRF_BUFFER_ADD_CHAR( select_buf, ',' );
2511 // ... if it's a string, just toss it on the pile
2512 if (selfield->type == JSON_STRING) {
2514 // again, just to be safe
2515 const char* _requested_col = selfield->value.s;
2516 osrfHash* field = osrfHashGet( class_field_set, _requested_col );
2517 if (!field) continue; // No such field in current class; skip it
2519 const char* col_name = osrfHashGet(field, "name");
2523 if (flags & DISABLE_I18N)
2526 i18n = osrfHashGet(field, "i18n");
2528 if( str_is_true( i18n ) ) {
2529 buffer_fadd( select_buf,
2530 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2531 class_tname, cname, col_name, class_pkey, cname, class_pkey, locale, col_name );
2533 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2536 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2539 // ... but it could be an object, in which case we check for a Field Transform
2542 char* _column = jsonObjectToSimpleString( jsonObjectGetKeyConst( selfield, "column" ) );
2544 // Get the field definition from the IDL
2545 osrfHash* field = osrfHashGet( class_field_set, _column );
2546 if (!field) continue; // No such field defined in IDL. Skip it.
2548 // Decide what to use as a column alias
2550 if ((tmp_const = jsonObjectGetKeyConst( selfield, "alias" ))) {
2551 _alias = jsonObjectToSimpleString( tmp_const );
2553 } else { // Use column name as its own alias
2556 _column = NULL; // To emphasize that we're through with _column
2558 if (jsonObjectGetKeyConst( selfield, "transform" )) {
2559 char* transform_str = searchFieldTransform(cname, field, selfield);
2560 buffer_fadd(select_buf, " %s AS \"%s\"", transform_str, _alias);
2561 free(transform_str);
2564 const char* fname = osrfHashGet(field, "name");
2568 if (flags & DISABLE_I18N)
2571 i18n = osrfHashGet(field, "i18n");
2573 if( str_is_true( i18n ) ) {
2574 buffer_fadd( select_buf,
2575 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2576 class_tname, cname, fname, class_pkey, cname, class_pkey, locale, _alias);
2578 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, fname, _alias);
2581 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, fname, _alias);
2588 if (is_agg->size || (flags & SELECT_DISTINCT)) {
2590 const jsonObject* aggregate_obj = jsonObjectGetKey( selfield, "aggregate" );
2591 if ( ! obj_is_true( aggregate_obj ) ) {
2595 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
2598 buffer_fadd(group_buf, " %d", sel_pos);
2600 } else if (is_agg = jsonObjectGetKey( selfield, "having" )) {
2604 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
2607 _column = searchFieldTransform(cname, field, selfield);
2608 OSRF_BUFFER_ADD_CHAR(group_buf, ' ');
2609 OSRF_BUFFER_ADD(group_buf, _column);
2610 _column = searchFieldTransform(cname, field, selfield);
2616 } // end while -- iterating across SELECT columns
2618 jsonIteratorFree(select_itr);
2619 } // end while -- iterating across classes
2621 jsonIteratorFree(selclass_itr);
2623 if (is_agg) jsonObjectFree(is_agg);
2627 char* col_list = buffer_release(select_buf);
2629 if (from_function) table = searchValueTransform(join_hash);
2630 else table = getSourceDefinition(core_meta);
2632 // Put it all together
2633 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\" ", col_list, table, core_class );
2637 if (!from_function) {
2638 // Now, walk the join tree and add that clause
2640 char* join_clause = searchJOIN( join_hash, core_meta );
2641 buffer_add(sql_buf, join_clause);
2645 // Build a WHERE clause, if there is one
2646 if ( search_hash ) {
2647 buffer_add(sql_buf, " WHERE ");
2649 // and it's on the WHERE clause
2650 char* pred = searchWHERE( search_hash, core_meta, AND_OP_JOIN, ctx );
2653 buffer_add(sql_buf, pred);
2657 osrfAppSessionStatus(
2659 OSRF_STATUS_INTERNALSERVERERROR,
2660 "osrfMethodException",
2662 "Severe query error in WHERE predicate -- see error log for more details"
2666 buffer_free(having_buf);
2667 buffer_free(group_buf);
2668 buffer_free(order_buf);
2669 buffer_free(sql_buf);
2670 if (defaultselhash) jsonObjectFree(defaultselhash);
2675 // Build a HAVING clause, if there is one
2676 if ( having_hash ) {
2677 buffer_add(sql_buf, " HAVING ");
2679 // and it's on the the WHERE clause
2680 char* pred = searchWHERE( having_hash, core_meta, AND_OP_JOIN, ctx );
2683 buffer_add(sql_buf, pred);
2687 osrfAppSessionStatus(
2689 OSRF_STATUS_INTERNALSERVERERROR,
2690 "osrfMethodException",
2692 "Severe query error in HAVING predicate -- see error log for more details"
2696 buffer_free(having_buf);
2697 buffer_free(group_buf);
2698 buffer_free(order_buf);
2699 buffer_free(sql_buf);
2700 if (defaultselhash) jsonObjectFree(defaultselhash);
2705 // Build an ORDER BY clause, if there is one
2707 jsonIterator* class_itr = jsonNewIterator( order_hash );
2708 while ( (snode = jsonIteratorNext( class_itr )) ) {
2710 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
2713 if ( snode->type == JSON_HASH ) {
2715 jsonIterator* order_itr = jsonNewIterator( snode );
2716 while ( (onode = jsonIteratorNext( order_itr )) ) {
2718 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
2721 char* direction = NULL;
2722 if ( onode->type == JSON_HASH ) {
2723 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
2724 string = searchFieldTransform(
2726 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
2730 growing_buffer* field_buf = buffer_init(16);
2731 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
2732 string = buffer_release(field_buf);
2735 if ( (tmp_const = jsonObjectGetKeyConst( onode, "direction" )) ) {
2736 direction = jsonObjectToSimpleString(tmp_const);
2737 if (!strncasecmp(direction, "d", 1)) {
2739 direction = " DESC";
2747 string = strdup(order_itr->key);
2748 direction = jsonObjectToSimpleString(onode);
2749 if (!strncasecmp(direction, "d", 1)) {
2751 direction = " DESC";
2761 buffer_add(order_buf, ", ");
2764 buffer_add(order_buf, string);
2768 buffer_add(order_buf, direction);
2772 // jsonIteratorFree(order_itr);
2774 } else if ( snode->type == JSON_ARRAY ) {
2776 jsonIterator* order_itr = jsonNewIterator( snode );
2777 while ( (onode = jsonIteratorNext( order_itr )) ) {
2779 char* _f = jsonObjectToSimpleString( onode );
2781 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, _f))
2787 buffer_add(order_buf, ", ");
2790 buffer_add(order_buf, _f);
2794 // jsonIteratorFree(order_itr);
2797 // IT'S THE OOOOOOOOOOOLD STYLE!
2799 osrfLogError(OSRF_LOG_MARK, "%s: Possible SQL injection attempt; direct order by is not allowed", MODULENAME);
2801 osrfAppSessionStatus(
2803 OSRF_STATUS_INTERNALSERVERERROR,
2804 "osrfMethodException",
2806 "Severe query error -- see error log for more details"
2811 buffer_free(having_buf);
2812 buffer_free(group_buf);
2813 buffer_free(order_buf);
2814 buffer_free(sql_buf);
2815 if (defaultselhash) jsonObjectFree(defaultselhash);
2816 jsonIteratorFree(class_itr);
2821 // jsonIteratorFree(class_itr);
2825 string = buffer_release(group_buf);
2827 if (strlen(string)) {
2828 OSRF_BUFFER_ADD( sql_buf, " GROUP BY " );
2829 OSRF_BUFFER_ADD( sql_buf, string );
2834 string = buffer_release(having_buf);
2836 if (strlen(string)) {
2837 OSRF_BUFFER_ADD( sql_buf, " HAVING " );
2838 OSRF_BUFFER_ADD( sql_buf, string );
2843 string = buffer_release(order_buf);
2845 if (strlen(string)) {
2846 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
2847 OSRF_BUFFER_ADD( sql_buf, string );
2853 string = jsonObjectToSimpleString(limit);
2854 buffer_fadd( sql_buf, " LIMIT %d", atoi(string) );
2859 string = jsonObjectToSimpleString(offset);
2860 buffer_fadd( sql_buf, " OFFSET %d", atoi(string) );
2864 if (!(flags & SUBSELECT)) OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
2867 if (defaultselhash) jsonObjectFree(defaultselhash);
2869 return buffer_release(sql_buf);
2873 static char* buildSELECT ( jsonObject* search_hash, jsonObject* order_hash, osrfHash* meta, osrfMethodContext* ctx ) {
2875 const char* locale = osrf_message_get_last_locale();
2877 osrfHash* fields = osrfHashGet(meta, "fields");
2878 char* core_class = osrfHashGet(meta, "classname");
2880 const jsonObject* join_hash = jsonObjectGetKeyConst( order_hash, "join" );
2882 jsonObject* node = NULL;
2883 jsonObject* snode = NULL;
2884 jsonObject* onode = NULL;
2885 const jsonObject* _tmp = NULL;
2886 jsonObject* selhash = NULL;
2887 jsonObject* defaultselhash = NULL;
2889 growing_buffer* sql_buf = buffer_init(128);
2890 growing_buffer* select_buf = buffer_init(128);
2892 if ( !(selhash = jsonObjectGetKey( order_hash, "select" )) ) {
2893 defaultselhash = jsonNewObjectType(JSON_HASH);
2894 selhash = defaultselhash;
2897 if ( !jsonObjectGetKeyConst(selhash,core_class) ) {
2898 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2899 jsonObject* flist = jsonObjectGetKey( selhash, core_class );
2904 osrfStringArray* keys = osrfHashKeys( fields );
2905 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
2906 if( ! str_is_true( osrfHashGet( osrfHashGet( fields, field ), "virtual" ) ) )
2907 jsonObjectPush( flist, jsonNewObject( field ) );
2909 osrfStringArrayFree(keys);
2913 jsonIterator* class_itr = jsonNewIterator( selhash );
2914 while ( (snode = jsonIteratorNext( class_itr )) ) {
2916 osrfHash* idlClass = osrfHashGet( oilsIDL(), class_itr->key );
2917 if (!idlClass) continue;
2918 char* cname = osrfHashGet(idlClass, "classname");
2920 if (strcmp(core_class,class_itr->key)) {
2921 if (!join_hash) continue;
2923 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", class_itr->key);
2925 jsonObjectFree(found);
2929 jsonObjectFree(found);
2932 jsonIterator* select_itr = jsonNewIterator( snode );
2933 while ( (node = jsonIteratorNext( select_itr )) ) {
2934 char* item_str = jsonObjectToSimpleString(node);
2935 osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), item_str );
2937 char* fname = osrfHashGet(field, "name");
2939 if (!field) continue;
2944 OSRF_BUFFER_ADD_CHAR(select_buf, ',');
2949 const jsonObject* no_i18n_obj = jsonObjectGetKey( order_hash, "no_i18n" );
2950 if ( obj_is_true( no_i18n_obj ) ) // Suppress internationalization?
2953 i18n = osrfHashGet(field, "i18n");
2955 if( str_is_true( i18n ) ) {
2956 char* pkey = osrfHashGet(idlClass, "primarykey");
2957 char* tname = osrfHashGet(idlClass, "tablename");
2959 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);
2961 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
2964 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
2968 jsonIteratorFree(select_itr);
2971 jsonIteratorFree(class_itr);
2973 char* col_list = buffer_release(select_buf);
2974 char* table = getSourceDefinition(meta);
2976 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\"", col_list, table, core_class );
2981 char* join_clause = searchJOIN( join_hash, meta );
2982 OSRF_BUFFER_ADD_CHAR(sql_buf, ' ');
2983 OSRF_BUFFER_ADD(sql_buf, join_clause);
2987 osrfLogDebug(OSRF_LOG_MARK, "%s pre-predicate SQL = %s",
2988 MODULENAME, OSRF_BUFFER_C_STR(sql_buf));
2990 buffer_add(sql_buf, " WHERE ");
2992 char* pred = searchWHERE( search_hash, meta, AND_OP_JOIN, ctx );
2994 osrfAppSessionStatus(
2996 OSRF_STATUS_INTERNALSERVERERROR,
2997 "osrfMethodException",
2999 "Severe query error -- see error log for more details"
3001 buffer_free(sql_buf);
3002 if(defaultselhash) jsonObjectFree(defaultselhash);
3005 buffer_add(sql_buf, pred);
3010 char* string = NULL;
3011 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "order_by" )) ){
3013 growing_buffer* order_buf = buffer_init(128);
3016 jsonIterator* class_itr = jsonNewIterator( _tmp );
3017 while ( (snode = jsonIteratorNext( class_itr )) ) {
3019 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
3022 if ( snode->type == JSON_HASH ) {
3024 jsonIterator* order_itr = jsonNewIterator( snode );
3025 while ( (onode = jsonIteratorNext( order_itr )) ) {
3027 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
3030 char* direction = NULL;
3031 if ( onode->type == JSON_HASH ) {
3032 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
3033 string = searchFieldTransform(
3035 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
3039 growing_buffer* field_buf = buffer_init(16);
3040 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
3041 string = buffer_release(field_buf);
3044 if ( (_tmp = jsonObjectGetKeyConst( onode, "direction" )) ) {
3045 direction = jsonObjectToSimpleString(_tmp);
3046 if (!strncasecmp(direction, "d", 1)) {
3048 direction = " DESC";
3056 string = strdup(order_itr->key);
3057 direction = jsonObjectToSimpleString(onode);
3058 if (!strncasecmp(direction, "d", 1)) {
3060 direction = " DESC";
3070 buffer_add(order_buf, ", ");
3073 buffer_add(order_buf, string);
3077 buffer_add(order_buf, direction);
3082 jsonIteratorFree(order_itr);
3085 string = jsonObjectToSimpleString(snode);
3086 buffer_add(order_buf, string);
3093 jsonIteratorFree(class_itr);
3095 string = buffer_release(order_buf);
3097 if (strlen(string)) {
3098 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
3099 OSRF_BUFFER_ADD( sql_buf, string );
3105 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "limit" )) ){
3106 string = jsonObjectToSimpleString(_tmp);
3115 _tmp = jsonObjectGetKeyConst( order_hash, "offset" );
3117 string = jsonObjectToSimpleString(_tmp);
3127 if (defaultselhash) jsonObjectFree(defaultselhash);
3129 OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
3130 return buffer_release(sql_buf);
3133 int doJSONSearch ( osrfMethodContext* ctx ) {
3134 if(osrfMethodVerifyContext( ctx )) {
3135 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
3139 osrfLogDebug(OSRF_LOG_MARK, "Recieved query request");
3144 dbhandle = writehandle;
3146 jsonObject* hash = jsonObjectGetIndex(ctx->params, 0);
3150 if ( obj_is_true( jsonObjectGetKey( hash, "distinct" ) ) )
3151 flags |= SELECT_DISTINCT;
3153 if ( obj_is_true( jsonObjectGetKey( hash, "no_i18n" ) ) )
3154 flags |= DISABLE_I18N;
3156 osrfLogDebug(OSRF_LOG_MARK, "Building SQL ...");
3159 jsonObjectGetKey( hash, "select" ),
3160 jsonObjectGetKey( hash, "from" ),
3161 jsonObjectGetKey( hash, "where" ),
3162 jsonObjectGetKey( hash, "having" ),
3163 jsonObjectGetKey( hash, "order_by" ),
3164 jsonObjectGetKey( hash, "limit" ),
3165 jsonObjectGetKey( hash, "offset" ),
3174 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3175 dbi_result result = dbi_conn_query(dbhandle, sql);
3178 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3180 if (dbi_result_first_row(result)) {
3181 /* JSONify the result */
3182 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3185 jsonObject* return_val = oilsMakeJSONFromResult( result );
3186 osrfAppRespond( ctx, return_val );
3187 jsonObjectFree( return_val );
3188 } while (dbi_result_next_row(result));
3191 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
3194 osrfAppRespondComplete( ctx, NULL );
3196 /* clean up the query */
3197 dbi_result_free(result);
3201 osrfLogError(OSRF_LOG_MARK, "%s: Error with query [%s]", MODULENAME, sql);
3202 osrfAppSessionStatus(
3204 OSRF_STATUS_INTERNALSERVERERROR,
3205 "osrfMethodException",
3207 "Severe query error -- see error log for more details"
3215 static jsonObject* doFieldmapperSearch ( osrfMethodContext* ctx, osrfHash* meta,
3216 const jsonObject* params, int* err ) {
3219 dbhandle = writehandle;
3221 osrfHash* links = osrfHashGet(meta, "links");
3222 osrfHash* fields = osrfHashGet(meta, "fields");
3223 char* core_class = osrfHashGet(meta, "classname");
3224 char* pkey = osrfHashGet(meta, "primarykey");
3226 const jsonObject* _tmp;
3228 jsonObject* search_hash = jsonObjectGetIndex(params, 0);
3229 jsonObject* order_hash = jsonObjectGetIndex(params, 1);
3231 char* sql = buildSELECT( search_hash, order_hash, meta, ctx );
3233 osrfLogDebug(OSRF_LOG_MARK, "Problem building query, returning NULL");
3238 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3240 dbi_result result = dbi_conn_query(dbhandle, sql);
3241 if( NULL == result ) {
3242 osrfLogError(OSRF_LOG_MARK, "%s: Error retrieving %s with query [%s]",
3243 MODULENAME, osrfHashGet(meta, "fieldmapper"), sql);
3244 osrfAppSessionStatus(
3246 OSRF_STATUS_INTERNALSERVERERROR,
3247 "osrfMethodException",
3249 "Severe query error -- see error log for more details"
3256 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3259 jsonObject* res_list = jsonNewObjectType(JSON_ARRAY);
3260 osrfHash* dedup = osrfNewHash();
3262 if (dbi_result_first_row(result)) {
3263 /* JSONify the result */
3264 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3266 obj = oilsMakeFieldmapperFromResult( result, meta );
3267 char* pkey_val = oilsFMGetString( obj, pkey );
3268 if ( osrfHashGet( dedup, pkey_val ) ) {
3269 jsonObjectFree(obj);
3272 osrfHashSet( dedup, pkey_val, pkey_val );
3273 jsonObjectPush(res_list, obj);
3275 } while (dbi_result_next_row(result));
3277 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s",
3281 osrfHashFree(dedup);
3282 /* clean up the query */
3283 dbi_result_free(result);
3286 if (res_list->size && order_hash) {
3287 _tmp = jsonObjectGetKeyConst( order_hash, "flesh" );
3289 int x = (int)jsonObjectGetNumber(_tmp);
3290 if (x == -1 || x > max_flesh_depth) x = max_flesh_depth;
3292 const jsonObject* temp_blob;
3293 if ((temp_blob = jsonObjectGetKeyConst( order_hash, "flesh_fields" )) && x > 0) {
3295 jsonObject* flesh_blob = jsonObjectClone( temp_blob );
3296 const jsonObject* flesh_fields = jsonObjectGetKeyConst( flesh_blob, core_class );
3298 osrfStringArray* link_fields = NULL;
3301 if (flesh_fields->size == 1) {
3302 char* _t = jsonObjectToSimpleString( jsonObjectGetIndex( flesh_fields, 0 ) );
3303 if (!strcmp(_t,"*")) link_fields = osrfHashKeys( links );
3309 link_fields = osrfNewStringArray(1);
3310 jsonIterator* _i = jsonNewIterator( flesh_fields );
3311 while ((_f = jsonIteratorNext( _i ))) {
3312 osrfStringArrayAdd( link_fields, jsonObjectToSimpleString( _f ) );
3314 jsonIteratorFree(_i);
3319 jsonIterator* itr = jsonNewIterator( res_list );
3320 while ((cur = jsonIteratorNext( itr ))) {
3325 while ( (link_field = osrfStringArrayGetString(link_fields, i++)) ) {
3327 osrfLogDebug(OSRF_LOG_MARK, "Starting to flesh %s", link_field);
3329 osrfHash* kid_link = osrfHashGet(links, link_field);
3330 if (!kid_link) continue;
3332 osrfHash* field = osrfHashGet(fields, link_field);
3333 if (!field) continue;
3335 osrfHash* value_field = field;
3337 osrfHash* kid_idl = osrfHashGet(oilsIDL(), osrfHashGet(kid_link, "class"));
3338 if (!kid_idl) continue;
3340 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3341 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3344 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) { // might_have
3345 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3348 osrfStringArray* link_map = osrfHashGet( kid_link, "map" );
3350 if (link_map->size > 0) {
3351 jsonObject* _kid_key = jsonNewObjectType(JSON_ARRAY);
3354 jsonNewObject( osrfStringArrayGetString( link_map, 0 ) )
3359 osrfHashGet(kid_link, "class"),
3366 "Link field: %s, remote class: %s, fkey: %s, reltype: %s",
3367 osrfHashGet(kid_link, "field"),
3368 osrfHashGet(kid_link, "class"),
3369 osrfHashGet(kid_link, "key"),
3370 osrfHashGet(kid_link, "reltype")
3373 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
3374 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // search hash
3375 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // order/flesh hash
3377 osrfLogDebug(OSRF_LOG_MARK, "Creating dummy params object...");
3380 jsonObjectToSimpleString(
3383 atoi( osrfHashGet(value_field, "array_position") )
3388 osrfLogDebug(OSRF_LOG_MARK, "Nothing to search for!");
3393 jsonObjectGetIndex(fake_params, 0),
3394 osrfHashGet(kid_link, "key"),
3395 jsonNewObject( search_key )
3402 jsonObjectGetIndex(fake_params, 1),
3404 jsonNewNumberObject( (double)(x - 1 + link_map->size) )
3408 jsonObjectSetKey( jsonObjectGetIndex(fake_params, 1), "flesh_fields", jsonObjectClone(flesh_blob) );
3410 if (jsonObjectGetKeyConst(order_hash, "order_by")) {
3412 jsonObjectGetIndex(fake_params, 1),
3414 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "order_by"))
3418 if (jsonObjectGetKeyConst(order_hash, "select")) {
3420 jsonObjectGetIndex(fake_params, 1),
3422 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "select"))
3426 jsonObject* kids = doFieldmapperSearch(ctx, kid_idl, fake_params, err);
3429 jsonObjectFree( fake_params );
3430 osrfStringArrayFree(link_fields);
3431 jsonIteratorFree(itr);
3432 jsonObjectFree(res_list);
3433 jsonObjectFree(flesh_blob);
3437 osrfLogDebug(OSRF_LOG_MARK, "Search for %s return %d linked objects", osrfHashGet(kid_link, "class"), kids->size);
3439 jsonObject* X = NULL;
3440 if ( link_map->size > 0 && kids->size > 0 ) {
3442 kids = jsonNewObjectType(JSON_ARRAY);
3444 jsonObject* _k_node;
3445 jsonIterator* _k = jsonNewIterator( X );
3446 while ((_k_node = jsonIteratorNext( _k ))) {
3452 (unsigned long)atoi(
3458 osrfHashGet(kid_link, "class")
3462 osrfStringArrayGetString( link_map, 0 )
3471 jsonIteratorFree(_k);
3474 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_a" )) || !(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) {
3475 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3478 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3479 jsonObjectClone( jsonObjectGetIndex(kids, 0) )
3483 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3484 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3487 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3488 jsonObjectClone( kids )
3493 jsonObjectFree(kids);
3497 jsonObjectFree( kids );
3498 jsonObjectFree( fake_params );
3500 osrfLogDebug(OSRF_LOG_MARK, "Fleshing of %s complete", osrfHashGet(kid_link, "field"));
3501 osrfLogDebug(OSRF_LOG_MARK, "%s", jsonObjectToJSON(cur));
3505 jsonObjectFree( flesh_blob );
3506 osrfStringArrayFree(link_fields);
3507 jsonIteratorFree(itr);
3516 static jsonObject* doUpdate(osrfMethodContext* ctx, int* err ) {
3518 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3520 jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
3522 jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
3525 if (!verifyObjectClass(ctx, target)) {
3530 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3531 osrfAppSessionStatus(
3533 OSRF_STATUS_BADREQUEST,
3534 "osrfMethodException",
3536 "No active transaction -- required for UPDATE"
3542 // The following test is harmless but redundant. If a class is
3543 // readonly, we don't register an update method for it.
3544 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
3545 osrfAppSessionStatus(
3547 OSRF_STATUS_BADREQUEST,
3548 "osrfMethodException",
3550 "Cannot UPDATE readonly class"
3556 dbhandle = writehandle;
3558 char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
3560 // Set the last_xact_id
3561 int index = oilsIDL_ntop( target->classname, "last_xact_id" );
3563 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
3564 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
3567 char* pkey = osrfHashGet(meta, "primarykey");
3568 osrfHash* fields = osrfHashGet(meta, "fields");
3570 char* id = oilsFMGetString( target, pkey );
3574 "%s updating %s object with %s = %s",
3576 osrfHashGet(meta, "fieldmapper"),
3581 growing_buffer* sql = buffer_init(128);
3582 buffer_fadd(sql,"UPDATE %s SET", osrfHashGet(meta, "tablename"));
3587 osrfStringArray* field_list = osrfHashKeys( fields );
3588 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
3590 osrfHash* field = osrfHashGet( fields, field_name );
3592 if(!( strcmp( field_name, pkey ) )) continue;
3593 if( str_is_true( osrfHashGet(osrfHashGet(fields,field_name), "virtual") ) )
3596 const jsonObject* field_object = oilsFMGetObject( target, field_name );
3599 if (field_object && field_object->classname) {
3600 value = oilsFMGetString(
3602 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
3605 value = jsonObjectToSimpleString( field_object );
3608 osrfLogDebug( OSRF_LOG_MARK, "Updating %s object with %s = %s", osrfHashGet(meta, "fieldmapper"), field_name, value);
3610 if (!field_object || field_object->type == JSON_NULL) {
3611 if ( !(!( strcmp( osrfHashGet(meta, "classname"), "au" ) ) && !( strcmp( field_name, "passwd" ) )) ) { // arg at the special case!
3612 if (first) first = 0;
3613 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3614 buffer_fadd( sql, " %s = NULL", field_name );
3617 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
3618 if (first) first = 0;
3619 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3621 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
3622 buffer_fadd( sql, " %s = %ld", field_name, atol(value) );
3623 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
3624 buffer_fadd( sql, " %s = %f", field_name, atof(value) );
3627 osrfLogDebug( OSRF_LOG_MARK, "%s is of type %s", field_name, osrfHashGet(field, "datatype"));
3630 if ( dbi_conn_quote_string(dbhandle, &value) ) {
3631 if (first) first = 0;
3632 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3633 buffer_fadd( sql, " %s = %s", field_name, value );
3636 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
3637 osrfAppSessionStatus(
3639 OSRF_STATUS_INTERNALSERVERERROR,
3640 "osrfMethodException",
3642 "Error quoting string -- please see the error log for more details"
3656 jsonObject* obj = jsonNewObject(id);
3658 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
3659 dbi_conn_quote_string(dbhandle, &id);
3661 buffer_fadd( sql, " WHERE %s = %s;", pkey, id );
3663 char* query = buffer_release(sql);
3664 osrfLogDebug(OSRF_LOG_MARK, "%s: Update SQL [%s]", MODULENAME, query);
3666 dbi_result result = dbi_conn_query(dbhandle, query);
3670 jsonObjectFree(obj);
3671 obj = jsonNewObject(NULL);
3674 "%s ERROR updating %s object with %s = %s",
3676 osrfHashGet(meta, "fieldmapper"),
3687 static jsonObject* doDelete(osrfMethodContext* ctx, int* err ) {
3689 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3691 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3692 osrfAppSessionStatus(
3694 OSRF_STATUS_BADREQUEST,
3695 "osrfMethodException",
3697 "No active transaction -- required for DELETE"
3703 // The following test is harmless but redundant. If a class is
3704 // readonly, we don't register a delete method for it.
3705 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
3706 osrfAppSessionStatus(
3708 OSRF_STATUS_BADREQUEST,
3709 "osrfMethodException",
3711 "Cannot DELETE readonly class"
3717 dbhandle = writehandle;
3721 char* pkey = osrfHashGet(meta, "primarykey");
3729 if (jsonObjectGetIndex(ctx->params, _obj_pos)->classname) {
3730 if (!verifyObjectClass(ctx, jsonObjectGetIndex( ctx->params, _obj_pos ))) {
3735 id = oilsFMGetString( jsonObjectGetIndex(ctx->params, _obj_pos), pkey );
3738 if (!verifyObjectPCRUD( ctx, NULL )) {
3743 id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, _obj_pos));
3748 "%s deleting %s object with %s = %s",
3750 osrfHashGet(meta, "fieldmapper"),
3755 obj = jsonNewObject(id);
3757 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
3758 dbi_conn_quote_string(writehandle, &id);
3760 dbi_result result = dbi_conn_queryf(writehandle, "DELETE FROM %s WHERE %s = %s;", osrfHashGet(meta, "tablename"), pkey, id);
3763 jsonObjectFree(obj);
3764 obj = jsonNewObject(NULL);
3767 "%s ERROR deleting %s object with %s = %s",
3769 osrfHashGet(meta, "fieldmapper"),
3782 static jsonObject* oilsMakeFieldmapperFromResult( dbi_result result, osrfHash* meta) {
3783 if(!(result && meta)) return jsonNULL;
3785 jsonObject* object = jsonNewObject(NULL);
3786 jsonObjectSetClass(object, osrfHashGet(meta, "classname"));
3788 osrfHash* fields = osrfHashGet(meta, "fields");
3790 osrfLogInternal(OSRF_LOG_MARK, "Setting object class to %s ", object->classname);
3794 char dt_string[256];
3798 int columnIndex = 1;
3800 unsigned short type;
3801 const char* columnName;
3803 /* cycle through the column list */
3804 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
3806 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
3808 fmIndex = -1; // reset the position
3810 /* determine the field type and storage attributes */
3811 type = dbi_result_get_field_type(result, columnName);
3812 attr = dbi_result_get_field_attribs(result, columnName);
3814 /* fetch the fieldmapper index */
3815 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
3817 if ( str_is_true( osrfHashGet(_f, "virtual") ) )
3820 const char* pos = (char*)osrfHashGet(_f, "array_position");
3821 if ( !pos ) continue;
3823 fmIndex = atoi( pos );
3824 osrfLogInternal(OSRF_LOG_MARK, "... Found column at position [%s]...", pos);
3829 if (dbi_result_field_is_null(result, columnName)) {
3830 jsonObjectSetIndex( object, fmIndex, jsonNewObject(NULL) );
3835 case DBI_TYPE_INTEGER :
3837 if( attr & DBI_INTEGER_SIZE8 )
3838 jsonObjectSetIndex( object, fmIndex,
3839 jsonNewNumberObject(dbi_result_get_longlong(result, columnName)));
3841 jsonObjectSetIndex( object, fmIndex,
3842 jsonNewNumberObject(dbi_result_get_int(result, columnName)));
3846 case DBI_TYPE_DECIMAL :
3847 jsonObjectSetIndex( object, fmIndex,
3848 jsonNewNumberObject(dbi_result_get_double(result, columnName)));
3851 case DBI_TYPE_STRING :
3857 jsonNewObject( dbi_result_get_string(result, columnName) )
3862 case DBI_TYPE_DATETIME :
3864 memset(dt_string, '\0', sizeof(dt_string));
3865 memset(&gmdt, '\0', sizeof(gmdt));
3867 _tmp_dt = dbi_result_get_datetime(result, columnName);
3870 if (!(attr & DBI_DATETIME_DATE)) {
3871 gmtime_r( &_tmp_dt, &gmdt );
3872 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
3873 } else if (!(attr & DBI_DATETIME_TIME)) {
3874 localtime_r( &_tmp_dt, &gmdt );
3875 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
3877 localtime_r( &_tmp_dt, &gmdt );
3878 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
3881 jsonObjectSetIndex( object, fmIndex, jsonNewObject(dt_string) );
3885 case DBI_TYPE_BINARY :
3886 osrfLogError( OSRF_LOG_MARK,
3887 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
3895 static jsonObject* oilsMakeJSONFromResult( dbi_result result ) {
3896 if(!result) return jsonNULL;
3898 jsonObject* object = jsonNewObject(NULL);
3901 char dt_string[256];
3905 int columnIndex = 1;
3907 unsigned short type;
3908 const char* columnName;
3910 /* cycle through the column list */
3911 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
3913 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
3915 fmIndex = -1; // reset the position
3917 /* determine the field type and storage attributes */
3918 type = dbi_result_get_field_type(result, columnName);
3919 attr = dbi_result_get_field_attribs(result, columnName);
3921 if (dbi_result_field_is_null(result, columnName)) {
3922 jsonObjectSetKey( object, columnName, jsonNewObject(NULL) );
3927 case DBI_TYPE_INTEGER :
3929 if( attr & DBI_INTEGER_SIZE8 )
3930 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_longlong(result, columnName)) );
3932 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_int(result, columnName)) );
3935 case DBI_TYPE_DECIMAL :
3936 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_double(result, columnName)) );
3939 case DBI_TYPE_STRING :
3940 jsonObjectSetKey( object, columnName, jsonNewObject(dbi_result_get_string(result, columnName)) );
3943 case DBI_TYPE_DATETIME :
3945 memset(dt_string, '\0', sizeof(dt_string));
3946 memset(&gmdt, '\0', sizeof(gmdt));
3948 _tmp_dt = dbi_result_get_datetime(result, columnName);
3951 if (!(attr & DBI_DATETIME_DATE)) {
3952 gmtime_r( &_tmp_dt, &gmdt );
3953 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
3954 } else if (!(attr & DBI_DATETIME_TIME)) {
3955 localtime_r( &_tmp_dt, &gmdt );
3956 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
3958 localtime_r( &_tmp_dt, &gmdt );
3959 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
3962 jsonObjectSetKey( object, columnName, jsonNewObject(dt_string) );
3965 case DBI_TYPE_BINARY :
3966 osrfLogError( OSRF_LOG_MARK,
3967 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
3975 // Interpret a string as true or false
3976 static int str_is_true( const char* str ) {
3977 if( NULL == str || strcasecmp( str, "true" ) )
3983 // Interpret a jsonObject as true or false
3984 static int obj_is_true( const jsonObject* obj ) {
3987 else switch( obj->type )
3995 if( strcasecmp( obj->value.s, "true" ) )
3999 case JSON_NUMBER : // Support 1/0 for perl's sake
4000 if( jsonObjectGetNumber( obj ) == 1.0 )