1 #include "opensrf/osrf_application.h"
2 #include "opensrf/osrf_settings.h"
3 #include "opensrf/osrf_message.h"
4 #include "opensrf/utils.h"
5 #include "opensrf/osrf_json.h"
6 #include "opensrf/log.h"
7 #include "openils/oils_utils.h"
16 # define MODULENAME "open-ils.reporter-store"
19 # define MODULENAME "open-ils.pcrud"
21 # define MODULENAME "open-ils.cstore"
26 #define DISABLE_I18N 2
27 #define SELECT_DISTINCT 1
31 int osrfAppChildInit();
32 int osrfAppInitialize();
33 void osrfAppChildExit();
35 static int verifyObjectClass ( osrfMethodContext*, const jsonObject* );
37 int beginTransaction ( osrfMethodContext* );
38 int commitTransaction ( osrfMethodContext* );
39 int rollbackTransaction ( osrfMethodContext* );
41 int setSavepoint ( osrfMethodContext* );
42 int releaseSavepoint ( osrfMethodContext* );
43 int rollbackSavepoint ( osrfMethodContext* );
45 int doJSONSearch ( osrfMethodContext* );
47 int dispatchCRUDMethod ( osrfMethodContext* );
48 static jsonObject* doCreate ( osrfMethodContext*, int* );
49 static jsonObject* doRetrieve ( osrfMethodContext*, int* );
50 static jsonObject* doUpdate ( osrfMethodContext*, int* );
51 static jsonObject* doDelete ( osrfMethodContext*, int* );
52 static jsonObject* doFieldmapperSearch ( osrfMethodContext*, osrfHash*,
53 const jsonObject*, int* );
54 static jsonObject* oilsMakeFieldmapperFromResult( dbi_result, osrfHash* );
55 static jsonObject* oilsMakeJSONFromResult( dbi_result );
57 static char* searchWriteSimplePredicate ( const char*, osrfHash*,
58 const char*, const char*, const char* );
59 static char* searchSimplePredicate ( const char*, const char*, osrfHash*, const jsonObject* );
60 static char* searchFunctionPredicate ( const char*, osrfHash*, const jsonObject*, const char* );
61 static char* searchFieldTransform ( const char*, osrfHash*, const jsonObject*);
62 static char* searchFieldTransformPredicate ( const char*, osrfHash*, jsonObject*, const char* );
63 static char* searchBETWEENPredicate ( const char*, osrfHash*, jsonObject* );
64 static char* searchINPredicate ( const char*, osrfHash*,
65 jsonObject*, const char*, osrfMethodContext* );
66 static char* searchPredicate ( const char*, osrfHash*, jsonObject*, osrfMethodContext* );
67 static char* searchJOIN ( const jsonObject*, osrfHash* );
68 static char* searchWHERE ( const jsonObject*, osrfHash*, int, osrfMethodContext* );
69 static char* buildSELECT ( jsonObject*, jsonObject*, osrfHash*, osrfMethodContext* );
71 char* SELECT ( osrfMethodContext*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, int );
73 void userDataFree( void* );
74 static void sessionDataFree( char*, void* );
75 static char* getSourceDefinition( osrfHash* );
76 static int str_is_true( const char* str );
77 static int obj_is_true( const jsonObject* obj );
80 static jsonObject* verifyUserPCRUD( osrfMethodContext* );
81 static int verifyObjectPCRUD( osrfMethodContext*, const jsonObject* );
84 static dbi_conn writehandle; /* our MASTER db connection */
85 static dbi_conn dbhandle; /* our CURRENT db connection */
86 //static osrfHash * readHandles;
87 static jsonObject* jsonNULL = NULL; //
88 static int max_flesh_depth = 100;
90 /* called when this process is about to exit */
91 void osrfAppChildExit() {
92 osrfLogDebug(OSRF_LOG_MARK, "Child is exiting, disconnecting from database...");
95 if (writehandle == dbhandle) same = 1;
97 dbi_conn_query(writehandle, "ROLLBACK;");
98 dbi_conn_close(writehandle);
101 if (dbhandle && !same)
102 dbi_conn_close(dbhandle);
104 // XXX add cleanup of readHandles whenever that gets used
109 int osrfAppInitialize() {
111 osrfLogInfo(OSRF_LOG_MARK, "Initializing the CStore Server...");
112 osrfLogInfo(OSRF_LOG_MARK, "Finding XML file...");
114 if (!oilsIDLInit( osrf_settings_host_value("/IDL") )) return 1; /* return non-zero to indicate error */
116 growing_buffer* method_name = buffer_init(64);
118 // Generic search thingy
119 buffer_add(method_name, MODULENAME);
120 buffer_add(method_name, ".json_query");
121 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
122 "doJSONSearch", "", 1, OSRF_METHOD_STREAMING );
125 // first we register all the transaction and savepoint methods
126 buffer_reset(method_name);
127 OSRF_BUFFER_ADD(method_name, MODULENAME);
128 OSRF_BUFFER_ADD(method_name, ".transaction.begin");
129 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
130 "beginTransaction", "", 0, 0 );
132 buffer_reset(method_name);
133 OSRF_BUFFER_ADD(method_name, MODULENAME);
134 OSRF_BUFFER_ADD(method_name, ".transaction.commit");
135 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
136 "commitTransaction", "", 0, 0 );
138 buffer_reset(method_name);
139 OSRF_BUFFER_ADD(method_name, MODULENAME);
140 OSRF_BUFFER_ADD(method_name, ".transaction.rollback");
141 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
142 "rollbackTransaction", "", 0, 0 );
144 buffer_reset(method_name);
145 OSRF_BUFFER_ADD(method_name, MODULENAME);
146 OSRF_BUFFER_ADD(method_name, ".savepoint.set");
147 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
148 "setSavepoint", "", 1, 0 );
150 buffer_reset(method_name);
151 OSRF_BUFFER_ADD(method_name, MODULENAME);
152 OSRF_BUFFER_ADD(method_name, ".savepoint.release");
153 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
154 "releaseSavepoint", "", 1, 0 );
156 buffer_reset(method_name);
157 OSRF_BUFFER_ADD(method_name, MODULENAME);
158 OSRF_BUFFER_ADD(method_name, ".savepoint.rollback");
159 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
160 "rollbackSavepoint", "", 1, 0 );
162 buffer_free(method_name);
164 static const char* global_method[] = {
172 const int global_method_count
173 = sizeof( global_method ) / sizeof ( global_method[0] );
177 osrfStringArray* classes = osrfHashKeys( oilsIDL() );
178 osrfLogDebug(OSRF_LOG_MARK, "%d classes loaded", classes->size );
179 osrfLogDebug(OSRF_LOG_MARK,
180 "At least %d methods will be generated", classes->size * global_method_count);
182 while ( (classname = osrfStringArrayGetString(classes, c_index++)) ) {
183 osrfLogInfo(OSRF_LOG_MARK, "Generating class methods for %s", classname);
185 osrfHash* idlClass = osrfHashGet(oilsIDL(), classname);
187 if (!osrfStringArrayContains( osrfHashGet(idlClass, "controller"), MODULENAME )) {
188 osrfLogInfo(OSRF_LOG_MARK, "%s is not listed as a controller for %s, moving on", MODULENAME, classname);
192 if ( str_is_true( osrfHashGet(idlClass, "virtual") ) ) {
193 osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
197 // Look up some other attributes of the current class
198 const char* idlClass_fieldmapper = osrfHashGet(idlClass, "fieldmapper");
199 const char* readonly = osrfHashGet(idlClass, "readonly");
201 osrfHash* idlClass_permacrud = osrfHashGet(idlClass, "permacrud");
205 for( i = 0; i < global_method_count; ++i ) {
206 const char* method_type = global_method[ i ];
207 osrfLogDebug(OSRF_LOG_MARK,
208 "Using files to build %s class methods for %s", method_type, classname);
210 if (!idlClass_fieldmapper) continue;
213 if (!idlClass_permacrud) continue;
215 const char* tmp_method = method_type;
216 if ( *tmp_method == 'i' || *tmp_method == 's') {
217 tmp_method = "retrieve";
219 if (!osrfHashGet( idlClass_permacrud, tmp_method )) continue;
222 if ( str_is_true( readonly ) &&
223 ( *method_type == 'c' || *method_type == 'u' || *method_type == 'd')
226 osrfHash* method_meta = osrfNewHash();
227 osrfHashSet(method_meta, idlClass, "class");
229 method_name = buffer_init(64);
231 buffer_fadd(method_name, "%s.%s.%s", MODULENAME, method_type, classname);
235 char* _fm = strdup( idlClass_fieldmapper );
236 part = strtok_r(_fm, ":", &st_tmp);
238 buffer_fadd(method_name, "%s.direct.%s", MODULENAME, part);
240 while ((part = strtok_r(NULL, ":", &st_tmp))) {
241 OSRF_BUFFER_ADD_CHAR(method_name, '.');
242 OSRF_BUFFER_ADD(method_name, part);
244 OSRF_BUFFER_ADD_CHAR(method_name, '.');
245 OSRF_BUFFER_ADD(method_name, method_type);
249 char* method = buffer_release(method_name);
251 osrfHashSet( method_meta, method, "methodname" );
252 osrfHashSet( method_meta, strdup(method_type), "methodtype" );
255 if (*method_type == 'i' || *method_type == 's') {
256 flags = flags | OSRF_METHOD_STREAMING;
259 osrfAppRegisterExtendedMethod(
262 "dispatchCRUDMethod",
276 static char* getSourceDefinition( osrfHash* class ) {
278 char* tabledef = osrfHashGet(class, "tablename");
281 growing_buffer* tablebuf = buffer_init(128);
282 tabledef = osrfHashGet(class, "source_definition");
285 buffer_fadd( tablebuf, "(%s)", tabledef );
286 tabledef = buffer_release(tablebuf);
288 tabledef = strdup(tabledef);
295 * Connects to the database
297 int osrfAppChildInit() {
299 osrfLogDebug(OSRF_LOG_MARK, "Attempting to initialize libdbi...");
300 dbi_initialize(NULL);
301 osrfLogDebug(OSRF_LOG_MARK, "... libdbi initialized.");
303 char* driver = osrf_settings_host_value("/apps/%s/app_settings/driver", MODULENAME);
304 char* user = osrf_settings_host_value("/apps/%s/app_settings/database/user", MODULENAME);
305 char* host = osrf_settings_host_value("/apps/%s/app_settings/database/host", MODULENAME);
306 char* port = osrf_settings_host_value("/apps/%s/app_settings/database/port", MODULENAME);
307 char* db = osrf_settings_host_value("/apps/%s/app_settings/database/db", MODULENAME);
308 char* pw = osrf_settings_host_value("/apps/%s/app_settings/database/pw", MODULENAME);
309 char* md = osrf_settings_host_value("/apps/%s/app_settings/max_query_recursion", MODULENAME);
311 osrfLogDebug(OSRF_LOG_MARK, "Attempting to load the database driver [%s]...", driver);
312 writehandle = dbi_conn_new(driver);
315 osrfLogError(OSRF_LOG_MARK, "Error loading database driver [%s]", driver);
318 osrfLogDebug(OSRF_LOG_MARK, "Database driver [%s] seems OK", driver);
320 osrfLogInfo(OSRF_LOG_MARK, "%s connecting to database. host=%s, "
321 "port=%s, user=%s, pw=%s, db=%s", MODULENAME, host, port, user, pw, db );
323 if(host) dbi_conn_set_option(writehandle, "host", host );
324 if(port) dbi_conn_set_option_numeric( writehandle, "port", atoi(port) );
325 if(user) dbi_conn_set_option(writehandle, "username", user);
326 if(pw) dbi_conn_set_option(writehandle, "password", pw );
327 if(db) dbi_conn_set_option(writehandle, "dbname", db );
329 if(md) max_flesh_depth = atoi(md);
330 if(max_flesh_depth < 0) max_flesh_depth = 1;
331 if(max_flesh_depth > 1000) max_flesh_depth = 1000;
340 if (dbi_conn_connect(writehandle) < 0) {
342 if (dbi_conn_connect(writehandle) < 0) {
343 dbi_conn_error(writehandle, &err);
344 osrfLogError( OSRF_LOG_MARK, "Error connecting to database: %s", err);
349 osrfLogInfo(OSRF_LOG_MARK, "%s successfully connected to the database", MODULENAME);
355 osrfStringArray* classes = osrfHashKeys( oilsIDL() );
357 while ( (classname = osrfStringArrayGetString(classes, i++)) ) {
358 osrfHash* class = osrfHashGet( oilsIDL(), classname );
359 osrfHash* fields = osrfHashGet( class, "fields" );
361 if( str_is_true( osrfHashGet(class, "virtual") ) ) {
362 osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
366 char* tabledef = getSourceDefinition(class);
368 growing_buffer* sql_buf = buffer_init(32);
369 buffer_fadd( sql_buf, "SELECT * FROM %s AS x WHERE 1=0;", tabledef );
373 char* sql = buffer_release(sql_buf);
374 osrfLogDebug(OSRF_LOG_MARK, "%s Investigatory SQL = %s", MODULENAME, sql);
376 dbi_result result = dbi_conn_query(writehandle, sql);
382 const char* columnName;
384 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
386 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
388 /* fetch the fieldmapper index */
389 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
391 osrfLogDebug(OSRF_LOG_MARK, "Found [%s] in IDL hash...", (char*)columnName);
393 /* determine the field type and storage attributes */
394 type = dbi_result_get_field_type(result, columnName);
395 attr = dbi_result_get_field_attribs(result, columnName);
399 case DBI_TYPE_INTEGER :
401 if ( !osrfHashGet(_f, "primitive") )
402 osrfHashSet(_f,"number", "primitive");
404 if( attr & DBI_INTEGER_SIZE8 )
405 osrfHashSet(_f,"INT8", "datatype");
407 osrfHashSet(_f,"INT", "datatype");
410 case DBI_TYPE_DECIMAL :
411 if ( !osrfHashGet(_f, "primitive") )
412 osrfHashSet(_f,"number", "primitive");
414 osrfHashSet(_f,"NUMERIC", "datatype");
417 case DBI_TYPE_STRING :
418 if ( !osrfHashGet(_f, "primitive") )
419 osrfHashSet(_f,"string", "primitive");
420 osrfHashSet(_f,"TEXT", "datatype");
423 case DBI_TYPE_DATETIME :
424 if ( !osrfHashGet(_f, "primitive") )
425 osrfHashSet(_f,"string", "primitive");
427 osrfHashSet(_f,"TIMESTAMP", "datatype");
430 case DBI_TYPE_BINARY :
431 if ( !osrfHashGet(_f, "primitive") )
432 osrfHashSet(_f,"string", "primitive");
434 osrfHashSet(_f,"BYTEA", "datatype");
439 "Setting [%s] to primitive [%s] and datatype [%s]...",
441 osrfHashGet(_f, "primitive"),
442 osrfHashGet(_f, "datatype")
446 dbi_result_free(result);
448 osrfLogDebug(OSRF_LOG_MARK, "No data found for class [%s]...", (char*)classname);
452 osrfStringArrayFree(classes);
457 void userDataFree( void* blob ) {
458 osrfHashFree( (osrfHash*)blob );
462 static void sessionDataFree( char* key, void* item ) {
463 if (!(strcmp(key,"xact_id"))) {
465 dbi_conn_query(writehandle, "ROLLBACK;");
472 int beginTransaction ( osrfMethodContext* ctx ) {
473 if(osrfMethodVerifyContext( ctx )) {
474 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
479 jsonObject* user = verifyUserPCRUD( ctx );
480 if (!user) return -1;
481 jsonObjectFree(user);
484 dbi_result result = dbi_conn_query(writehandle, "START TRANSACTION;");
486 osrfLogError(OSRF_LOG_MARK, "%s: Error starting transaction", MODULENAME );
487 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error starting transaction" );
490 jsonObject* ret = jsonNewObject(ctx->session->session_id);
491 osrfAppRespondComplete( ctx, ret );
494 if (!ctx->session->userData) {
495 ctx->session->userData = osrfNewHash();
496 osrfHashSetCallback((osrfHash*)ctx->session->userData, &sessionDataFree);
499 osrfHashSet( (osrfHash*)ctx->session->userData, strdup( ctx->session->session_id ), "xact_id" );
500 ctx->session->userDataFree = &userDataFree;
506 int setSavepoint ( osrfMethodContext* ctx ) {
507 if(osrfMethodVerifyContext( ctx )) {
508 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
515 jsonObject* user = verifyUserPCRUD( ctx );
516 if (!user) return -1;
517 jsonObjectFree(user);
520 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
521 osrfAppSessionStatus(
523 OSRF_STATUS_INTERNALSERVERERROR,
524 "osrfMethodException",
526 "No active transaction -- required for savepoints"
531 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
533 dbi_result result = dbi_conn_queryf(writehandle, "SAVEPOINT \"%s\";", spName);
537 "%s: Error creating savepoint %s in transaction %s",
540 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
542 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error creating savepoint" );
546 jsonObject* ret = jsonNewObject(spName);
547 osrfAppRespondComplete( ctx, ret );
554 int releaseSavepoint ( osrfMethodContext* ctx ) {
555 if(osrfMethodVerifyContext( ctx )) {
556 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
563 jsonObject* user = verifyUserPCRUD( ctx );
564 if (!user) return -1;
565 jsonObjectFree(user);
568 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
569 osrfAppSessionStatus(
571 OSRF_STATUS_INTERNALSERVERERROR,
572 "osrfMethodException",
574 "No active transaction -- required for savepoints"
579 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
581 dbi_result result = dbi_conn_queryf(writehandle, "RELEASE SAVEPOINT \"%s\";", spName);
585 "%s: Error releasing savepoint %s in transaction %s",
588 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
590 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error releasing savepoint" );
594 jsonObject* ret = jsonNewObject(spName);
595 osrfAppRespondComplete( ctx, ret );
602 int rollbackSavepoint ( osrfMethodContext* ctx ) {
603 if(osrfMethodVerifyContext( ctx )) {
604 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
611 jsonObject* user = verifyUserPCRUD( ctx );
612 if (!user) return -1;
613 jsonObjectFree(user);
616 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
617 osrfAppSessionStatus(
619 OSRF_STATUS_INTERNALSERVERERROR,
620 "osrfMethodException",
622 "No active transaction -- required for savepoints"
627 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
629 dbi_result result = dbi_conn_queryf(writehandle, "ROLLBACK TO SAVEPOINT \"%s\";", spName);
633 "%s: Error rolling back savepoint %s in transaction %s",
636 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
638 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back savepoint" );
642 jsonObject* ret = jsonNewObject(spName);
643 osrfAppRespondComplete( ctx, ret );
650 int commitTransaction ( osrfMethodContext* ctx ) {
651 if(osrfMethodVerifyContext( ctx )) {
652 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
657 jsonObject* user = verifyUserPCRUD( ctx );
658 if (!user) return -1;
659 jsonObjectFree(user);
662 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
663 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to commit" );
667 dbi_result result = dbi_conn_query(writehandle, "COMMIT;");
669 osrfLogError(OSRF_LOG_MARK, "%s: Error committing transaction", MODULENAME );
670 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error committing transaction" );
673 osrfHashRemove(ctx->session->userData, "xact_id");
674 jsonObject* ret = jsonNewObject(ctx->session->session_id);
675 osrfAppRespondComplete( ctx, ret );
681 int rollbackTransaction ( osrfMethodContext* ctx ) {
682 if(osrfMethodVerifyContext( ctx )) {
683 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
688 jsonObject* user = verifyUserPCRUD( ctx );
689 if (!user) return -1;
690 jsonObjectFree(user);
693 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
694 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to roll back" );
698 dbi_result result = dbi_conn_query(writehandle, "ROLLBACK;");
700 osrfLogError(OSRF_LOG_MARK, "%s: Error rolling back transaction", MODULENAME );
701 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back transaction" );
704 osrfHashRemove(ctx->session->userData, "xact_id");
705 jsonObject* ret = jsonNewObject(ctx->session->session_id);
706 osrfAppRespondComplete( ctx, ret );
712 int dispatchCRUDMethod ( osrfMethodContext* ctx ) {
713 if(osrfMethodVerifyContext( ctx )) {
714 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
718 osrfHash* meta = (osrfHash*) ctx->method->userData;
719 osrfHash* class_obj = osrfHashGet( meta, "class" );
723 const char* methodtype = osrfHashGet(meta, "methodtype");
724 jsonObject * obj = NULL;
726 if (!strcmp(methodtype, "create")) {
727 obj = doCreate(ctx, &err);
728 osrfAppRespondComplete( ctx, obj );
730 else if (!strcmp(methodtype, "retrieve")) {
731 obj = doRetrieve(ctx, &err);
732 osrfAppRespondComplete( ctx, obj );
734 else if (!strcmp(methodtype, "update")) {
735 obj = doUpdate(ctx, &err);
736 osrfAppRespondComplete( ctx, obj );
738 else if (!strcmp(methodtype, "delete")) {
739 obj = doDelete(ctx, &err);
740 osrfAppRespondComplete( ctx, obj );
742 else if (!strcmp(methodtype, "search")) {
744 jsonObject* _p = jsonObjectClone( ctx->params );
747 _p = jsonParseString("[]");
748 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 1)));
749 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 2)));
752 obj = doFieldmapperSearch(ctx, class_obj, _p, &err);
758 jsonIterator* itr = jsonNewIterator( obj );
759 while ((cur = jsonIteratorNext( itr ))) {
761 if(!verifyObjectPCRUD(ctx, cur)) continue;
763 osrfAppRespond( ctx, cur );
765 jsonIteratorFree(itr);
766 osrfAppRespondComplete( ctx, NULL );
768 } else if (!strcmp(methodtype, "id_list")) {
770 jsonObject* _p = jsonObjectClone( ctx->params );
773 _p = jsonParseString("[]");
774 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 1)));
775 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 2)));
778 if (jsonObjectGetIndex( _p, 1 )) {
779 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "select" );
780 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "no_i18n" );
781 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh" );
782 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh_columns" );
784 jsonObjectSetIndex( _p, 1, jsonNewObjectType(JSON_HASH) );
787 jsonObjectSetKey( jsonObjectGetIndex( _p, 1 ), "no_i18n", jsonNewBoolObject( 1 ) );
790 jsonObjectGetIndex( _p, 1 ),
793 "{ \"%s\":[\"%s\"] }",
794 osrfHashGet( class_obj, "classname" ),
795 osrfHashGet( class_obj, "primarykey" )
799 obj = doFieldmapperSearch(ctx, class_obj, _p, &err);
805 jsonIterator* itr = jsonNewIterator( obj );
806 while ((cur = jsonIteratorNext( itr ))) {
808 if(!verifyObjectPCRUD(ctx, cur)) continue;
812 oilsFMGetObject( cur, osrfHashGet( class_obj, "primarykey" ) )
815 jsonIteratorFree(itr);
816 osrfAppRespondComplete( ctx, NULL );
819 osrfAppRespondComplete( ctx, obj );
827 static int verifyObjectClass ( osrfMethodContext* ctx, const jsonObject* param ) {
830 osrfHash* meta = (osrfHash*) ctx->method->userData;
831 osrfHash* class = osrfHashGet( meta, "class" );
833 if (!param->classname || (strcmp( osrfHashGet(class, "classname"), param->classname ))) {
835 growing_buffer* msg = buffer_init(128);
838 "%s: %s method for type %s was passed a %s",
840 osrfHashGet(meta, "methodtype"),
841 osrfHashGet(class, "classname"),
845 char* m = buffer_release(msg);
846 osrfAppSessionStatus( ctx->session, OSRF_STATUS_BADREQUEST, "osrfMethodException", ctx->request, m );
854 ret = verifyObjectPCRUD( ctx, param );
862 static jsonObject* verifyUserPCRUD( osrfMethodContext* ctx ) {
863 char* auth = jsonObjectToSimpleString( jsonObjectGetIndex( ctx->params, 0 ) );
864 jsonObject* auth_object = jsonNewObject(auth);
865 jsonObject* user = oilsUtilsQuickReq("open-ils.auth","open-ils.auth.session.retrieve", auth_object);
866 jsonObjectFree(auth_object);
868 if (!user->classname || strcmp(user->classname, "au")) {
870 growing_buffer* msg = buffer_init(128);
873 "%s: permacrud received a bad auth token: %s",
878 char* m = buffer_release(msg);
879 osrfAppSessionStatus( ctx->session, OSRF_STATUS_UNAUTHORIZED, "osrfMethodException", ctx->request, m );
882 jsonObjectFree(user);
891 static int verifyObjectPCRUD ( osrfMethodContext* ctx, const jsonObject* obj ) {
893 dbhandle = writehandle;
895 osrfHash* meta = (osrfHash*) ctx->method->userData;
896 osrfHash* class = osrfHashGet( meta, "class" );
897 char* method_type = strdup( osrfHashGet(meta, "methodtype") );
900 if ( ( *method_type == 's' || *method_type == 'i' ) ) {
902 method_type = strdup("retrieve"); // search and id_list are equivelant to retrieve for this
903 } else if ( *method_type == 'u' || *method_type == 'd' ) {
904 fetch = 1; // MUST go to the db for the object for update and delete
907 osrfHash* pcrud = osrfHashGet( osrfHashGet(class, "permacrud"), method_type );
911 // No permacrud for this method type on this class
913 growing_buffer* msg = buffer_init(128);
916 "%s: %s on class %s has no permacrud IDL entry",
918 osrfHashGet(meta, "methodtype"),
919 osrfHashGet(class, "classname")
922 char* m = buffer_release(msg);
923 osrfAppSessionStatus( ctx->session, OSRF_STATUS_FORBIDDEN, "osrfMethodException", ctx->request, m );
930 jsonObject* user = verifyUserPCRUD( ctx );
933 int userid = atoi( oilsFMGetString( user, "id" ) );
934 jsonObjectFree(user);
936 osrfStringArray* permission = osrfHashGet(pcrud, "permission");
937 osrfStringArray* local_context = osrfHashGet(pcrud, "local_context");
938 osrfHash* foreign_context = osrfHashGet(pcrud, "foreign_context");
940 osrfStringArray* context_org_array = osrfNewStringArray(1);
943 char* pkey_value = NULL;
944 if ( str_is_true( osrfHashGet(pcrud, "global_required") ) ) {
945 osrfLogDebug( OSRF_LOG_MARK, "global-level permissions required, fetching top of the org tree" );
947 // check for perm at top of org tree
948 jsonObject* _tmp_params = jsonParseString("[{\"parent_ou\":null}]");
949 jsonObject* _list = doFieldmapperSearch(ctx, osrfHashGet( oilsIDL(), "aou" ), _tmp_params, &err);
951 jsonObject* _tree_top = jsonObjectGetIndex(_list, 0);
954 jsonObjectFree(_tmp_params);
955 jsonObjectFree(_list);
957 growing_buffer* msg = buffer_init(128);
958 OSRF_BUFFER_ADD( msg, MODULENAME );
959 OSRF_BUFFER_ADD( msg,
960 ": Internal error, could not find the top of the org tree (parent_ou = NULL)" );
962 char* m = buffer_release(msg);
963 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, m );
969 osrfStringArrayAdd( context_org_array, oilsFMGetString( _tree_top, "id" ) );
970 osrfLogDebug( OSRF_LOG_MARK, "top of the org tree is %s", osrfStringArrayGetString(context_org_array, 0) );
972 jsonObjectFree(_tmp_params);
973 jsonObjectFree(_list);
976 osrfLogDebug( OSRF_LOG_MARK, "global-level permissions not required, fetching context org ids" );
977 char* pkey = osrfHashGet(class, "primarykey");
978 jsonObject *param = NULL;
980 if (obj->classname) {
981 pkey_value = oilsFMGetString( obj, pkey );
982 if (!fetch) param = jsonObjectClone(obj);
983 osrfLogDebug( OSRF_LOG_MARK, "Object supplied, using primary key value of %s", pkey_value );
985 pkey_value = jsonObjectToSimpleString( obj );
987 osrfLogDebug( OSRF_LOG_MARK, "Object not supplied, using primary key value of %s and retrieving from the database", pkey_value );
991 jsonObject* _tmp_params = jsonParseStringFmt("[{\"%s\":\"%s\"}]", pkey, pkey_value);
992 jsonObject* _list = doFieldmapperSearch(
999 param = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1001 jsonObjectFree(_tmp_params);
1002 jsonObjectFree(_list);
1006 osrfLogDebug( OSRF_LOG_MARK, "Object not found in the database with primary key %s of %s", pkey, pkey_value );
1008 growing_buffer* msg = buffer_init(128);
1011 "%s: no object found with primary key %s of %s",
1017 char* m = buffer_release(msg);
1018 osrfAppSessionStatus(
1020 OSRF_STATUS_INTERNALSERVERERROR,
1021 "osrfMethodException",
1027 if (pkey_value) free(pkey_value);
1032 if (local_context->size > 0) {
1033 osrfLogDebug( OSRF_LOG_MARK, "%d class-local context field(s) specified", local_context->size);
1035 char* lcontext = NULL;
1036 while ( (lcontext = osrfStringArrayGetString(local_context, i++)) ) {
1037 osrfStringArrayAdd( context_org_array, oilsFMGetString( param, lcontext ) );
1040 "adding class-local field %s (value: %s) to the context org list",
1042 osrfStringArrayGetString(context_org_array, context_org_array->size - 1)
1047 osrfStringArray* class_list;
1049 if (foreign_context) {
1050 class_list = osrfHashKeys( foreign_context );
1051 osrfLogDebug( OSRF_LOG_MARK, "%d foreign context classes(s) specified", class_list->size);
1053 if (class_list->size > 0) {
1056 char* class_name = NULL;
1057 while ( (class_name = osrfStringArrayGetString(class_list, i++)) ) {
1058 osrfHash* fcontext = osrfHashGet(foreign_context, class_name);
1062 "%d foreign context fields(s) specified for class %s",
1063 ((osrfStringArray*)osrfHashGet(fcontext,"context"))->size,
1067 char* foreign_pkey = osrfHashGet(fcontext, "field");
1068 char* foreign_pkey_value = oilsFMGetString(param, osrfHashGet(fcontext, "fkey"));
1070 jsonObject* _tmp_params = jsonParseStringFmt(
1071 "[{\"%s\":\"%s\"}]",
1076 jsonObject* _list = doFieldmapperSearch(
1078 osrfHashGet( oilsIDL(), class_name ),
1083 jsonObject* _fparam = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1084 jsonObjectFree(_tmp_params);
1085 jsonObjectFree(_list);
1087 osrfStringArray* jump_list = osrfHashGet(fcontext, "jump");
1089 if (_fparam && jump_list) {
1092 while ( (flink = osrfStringArrayGetString(jump_list, k++)) && _fparam ) {
1093 free(foreign_pkey_value);
1095 osrfHash* foreign_link_hash = oilsIDLFindPath( "/%s/links/%s", _fparam->classname, flink );
1097 foreign_pkey_value = oilsFMGetString(_fparam, flink);
1098 foreign_pkey = osrfHashGet( foreign_link_hash, "key" );
1100 _tmp_params = jsonParseStringFmt(
1101 "[{\"%s\":\"%s\"}]",
1106 _list = doFieldmapperSearch(
1108 osrfHashGet( oilsIDL(), osrfHashGet( foreign_link_hash, "class" ) ),
1113 _fparam = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1114 jsonObjectFree(_tmp_params);
1115 jsonObjectFree(_list);
1122 growing_buffer* msg = buffer_init(128);
1125 "%s: no object found with primary key %s of %s",
1131 char* m = buffer_release(msg);
1132 osrfAppSessionStatus(
1134 OSRF_STATUS_INTERNALSERVERERROR,
1135 "osrfMethodException",
1141 osrfStringArrayFree(class_list);
1142 free(foreign_pkey_value);
1143 jsonObjectFree(param);
1148 free(foreign_pkey_value);
1151 char* foreign_field = NULL;
1152 while ( (foreign_field = osrfStringArrayGetString(osrfHashGet(fcontext,"context"), j++)) ) {
1153 osrfStringArrayAdd( context_org_array, oilsFMGetString( _fparam, foreign_field ) );
1156 "adding foreign class %s field %s (value: %s) to the context org list",
1159 osrfStringArrayGetString(context_org_array, context_org_array->size - 1)
1163 jsonObjectFree(_fparam);
1166 osrfStringArrayFree(class_list);
1170 jsonObjectFree(param);
1173 char* context_org = NULL;
1177 if (permission->size == 0) {
1178 osrfLogDebug( OSRF_LOG_MARK, "No permission specified for this action, passing through" );
1183 while ( (perm = osrfStringArrayGetString(permission, i++)) ) {
1185 while ( (context_org = osrfStringArrayGetString(context_org_array, j++)) ) {
1191 "Checking object permission [%s] for user %d on object %s (class %s) at org %d",
1195 osrfHashGet(class, "classname"),
1199 result = dbi_conn_queryf(
1201 "SELECT permission.usr_has_object_perm(%d, '%s', '%s', '%s', %d) AS has_perm;",
1204 osrfHashGet(class, "classname"),
1212 "Recieved a result for object permission [%s] for user %d on object %s (class %s) at org %d",
1216 osrfHashGet(class, "classname"),
1220 if (dbi_result_first_row(result)) {
1221 jsonObject* return_val = oilsMakeJSONFromResult( result );
1222 char* has_perm = jsonObjectToSimpleString( jsonObjectGetKeyConst(return_val, "has_perm") );
1226 "Status of object permission [%s] for user %d on object %s (class %s) at org %d is %s",
1230 osrfHashGet(class, "classname"),
1235 if ( *has_perm == 't' ) OK = 1;
1237 jsonObjectFree(return_val);
1240 dbi_result_free(result);
1245 osrfLogDebug( OSRF_LOG_MARK, "Checking non-object permission [%s] for user %d at org %d", perm, userid, atoi(context_org) );
1246 result = dbi_conn_queryf(
1248 "SELECT permission.usr_has_perm(%d, '%s', %d) AS has_perm;",
1255 osrfLogDebug( OSRF_LOG_MARK, "Recieved a result for permission [%s] for user %d at org %d", perm, userid, atoi(context_org) );
1256 if (dbi_result_first_row(result)) {
1257 jsonObject* return_val = oilsMakeJSONFromResult( result );
1258 char* has_perm = jsonObjectToSimpleString( jsonObjectGetKeyConst(return_val, "has_perm") );
1259 osrfLogDebug( OSRF_LOG_MARK, "Status of permission [%s] for user %d at org %d is [%s]", perm, userid, atoi(context_org), has_perm );
1260 if ( *has_perm == 't' ) OK = 1;
1262 jsonObjectFree(return_val);
1265 dbi_result_free(result);
1273 if (pkey_value) free(pkey_value);
1274 osrfStringArrayFree(context_org_array);
1281 static jsonObject* doCreate(osrfMethodContext* ctx, int* err ) {
1283 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1285 jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
1286 jsonObject* options = jsonObjectGetIndex( ctx->params, 2 );
1288 jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
1289 jsonObject* options = jsonObjectGetIndex( ctx->params, 1 );
1292 if (!verifyObjectClass(ctx, target)) {
1297 osrfLogDebug( OSRF_LOG_MARK, "Object seems to be of the correct type" );
1299 if (!ctx->session || !ctx->session->userData || !osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
1300 osrfLogError( OSRF_LOG_MARK, "No active transaction -- required for CREATE" );
1302 osrfAppSessionStatus(
1304 OSRF_STATUS_BADREQUEST,
1305 "osrfMethodException",
1307 "No active transaction -- required for CREATE"
1313 // The following test is harmless but redundant. If a class is
1314 // readonly, we don't register a create method for it.
1315 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
1316 osrfAppSessionStatus(
1318 OSRF_STATUS_BADREQUEST,
1319 "osrfMethodException",
1321 "Cannot INSERT readonly class"
1328 char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
1330 // Set the last_xact_id
1331 int index = oilsIDL_ntop( target->classname, "last_xact_id" );
1333 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
1334 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
1337 osrfLogDebug( OSRF_LOG_MARK, "There is a transaction running..." );
1339 dbhandle = writehandle;
1341 osrfHash* fields = osrfHashGet(meta, "fields");
1342 char* pkey = osrfHashGet(meta, "primarykey");
1343 char* seq = osrfHashGet(meta, "sequence");
1345 growing_buffer* table_buf = buffer_init(128);
1346 growing_buffer* col_buf = buffer_init(128);
1347 growing_buffer* val_buf = buffer_init(128);
1349 OSRF_BUFFER_ADD(table_buf, "INSERT INTO ");
1350 OSRF_BUFFER_ADD(table_buf, osrfHashGet(meta, "tablename"));
1351 OSRF_BUFFER_ADD_CHAR( col_buf, '(' );
1352 buffer_add(val_buf,"VALUES (");
1358 osrfStringArray* field_list = osrfHashKeys( fields );
1359 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
1361 osrfHash* field = osrfHashGet( fields, field_name );
1363 if( str_is_true( osrfHashGet( field, "virtual" ) ) )
1366 const jsonObject* field_object = oilsFMGetObject( target, field_name );
1369 if (field_object && field_object->classname) {
1370 value = oilsFMGetString(
1372 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
1375 value = jsonObjectToSimpleString( field_object );
1382 OSRF_BUFFER_ADD_CHAR( col_buf, ',' );
1383 OSRF_BUFFER_ADD_CHAR( val_buf, ',' );
1386 buffer_add(col_buf, field_name);
1388 if (!field_object || field_object->type == JSON_NULL) {
1389 buffer_add( val_buf, "DEFAULT" );
1391 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1392 if ( !strcmp(osrfHashGet(field, "datatype"), "INT8") ) {
1393 buffer_fadd( val_buf, "%lld", atoll(value) );
1395 } else if ( !strcmp(osrfHashGet(field, "datatype"), "INT") ) {
1396 buffer_fadd( val_buf, "%d", atoi(value) );
1398 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
1399 buffer_fadd( val_buf, "%f", atof(value) );
1402 if ( dbi_conn_quote_string(writehandle, &value) ) {
1403 OSRF_BUFFER_ADD( val_buf, value );
1406 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
1407 osrfAppSessionStatus(
1409 OSRF_STATUS_INTERNALSERVERERROR,
1410 "osrfMethodException",
1412 "Error quoting string -- please see the error log for more details"
1415 buffer_free(table_buf);
1416 buffer_free(col_buf);
1417 buffer_free(val_buf);
1428 OSRF_BUFFER_ADD_CHAR( col_buf, ')' );
1429 OSRF_BUFFER_ADD_CHAR( val_buf, ')' );
1431 char* table_str = buffer_release(table_buf);
1432 char* col_str = buffer_release(col_buf);
1433 char* val_str = buffer_release(val_buf);
1434 growing_buffer* sql = buffer_init(128);
1435 buffer_fadd( sql, "%s %s %s;", table_str, col_str, val_str );
1440 char* query = buffer_release(sql);
1442 osrfLogDebug(OSRF_LOG_MARK, "%s: Insert SQL [%s]", MODULENAME, query);
1445 dbi_result result = dbi_conn_query(writehandle, query);
1447 jsonObject* obj = NULL;
1450 obj = jsonNewObject(NULL);
1453 "%s ERROR inserting %s object using query [%s]",
1455 osrfHashGet(meta, "fieldmapper"),
1458 osrfAppSessionStatus(
1460 OSRF_STATUS_INTERNALSERVERERROR,
1461 "osrfMethodException",
1463 "INSERT error -- please see the error log for more details"
1468 char* id = oilsFMGetString(target, pkey);
1470 unsigned long long new_id = dbi_conn_sequence_last(writehandle, seq);
1471 growing_buffer* _id = buffer_init(10);
1472 buffer_fadd(_id, "%lld", new_id);
1473 id = buffer_release(_id);
1476 // Find quietness specification, if present
1477 char* quiet_str = NULL;
1479 const jsonObject* quiet_obj = jsonObjectGetKeyConst( options, "quiet" );
1481 quiet_str = jsonObjectToSimpleString( quiet_obj );
1484 if( str_is_true( quiet_str ) ) { // if quietness is specified
1485 obj = jsonNewObject(id);
1489 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
1490 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH));
1493 jsonObjectGetIndex(fake_params, 0),
1498 jsonObject* list = doFieldmapperSearch( ctx,meta, fake_params, err);
1501 jsonObjectFree( fake_params );
1504 obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
1507 jsonObjectFree( list );
1508 jsonObjectFree( fake_params );
1511 if(quiet_str) free(quiet_str);
1522 static jsonObject* doRetrieve(osrfMethodContext* ctx, int* err ) {
1532 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1534 char* id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, id_pos));
1535 jsonObject* order_hash = jsonObjectGetIndex(ctx->params, order_pos);
1539 "%s retrieving %s object with primary key value of %s",
1541 osrfHashGet(meta, "fieldmapper"),
1546 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
1547 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH));
1550 jsonObjectGetIndex(fake_params, 0),
1551 osrfHashGet(meta, "primarykey"),
1552 jsonObjectClone(jsonObjectGetIndex(ctx->params, id_pos))
1556 if (order_hash) jsonObjectPush(fake_params, jsonObjectClone(order_hash) );
1558 jsonObject* list = doFieldmapperSearch( ctx,meta, fake_params, err);
1561 jsonObjectFree( fake_params );
1565 jsonObject* obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
1567 jsonObjectFree( list );
1568 jsonObjectFree( fake_params );
1571 if(!verifyObjectPCRUD(ctx, obj)) {
1572 jsonObjectFree(obj);
1575 growing_buffer* msg = buffer_init(128);
1576 OSRF_BUFFER_ADD( msg, MODULENAME );
1577 OSRF_BUFFER_ADD( msg, ": Insufficient permissions to retrieve object" );
1579 char* m = buffer_release(msg);
1580 osrfAppSessionStatus( ctx->session, OSRF_STATUS_NOTALLOWED, "osrfMethodException", ctx->request, m );
1591 static char* jsonNumberToDBString ( osrfHash* field, const jsonObject* value ) {
1592 growing_buffer* val_buf = buffer_init(32);
1594 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
1595 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%ld", (long)jsonObjectGetNumber(value) );
1597 char* val_str = jsonObjectToSimpleString(value);
1598 buffer_fadd( val_buf, "%ld", atol(val_str) );
1602 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
1603 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%f", jsonObjectGetNumber(value) );
1605 char* val_str = jsonObjectToSimpleString(value);
1606 buffer_fadd( val_buf, "%f", atof(val_str) );
1611 return buffer_release(val_buf);
1614 static char* searchINPredicate (const char* class, osrfHash* field,
1615 jsonObject* node, const char* op, osrfMethodContext* ctx ) {
1616 growing_buffer* sql_buf = buffer_init(32);
1622 osrfHashGet(field, "name")
1626 buffer_add(sql_buf, "IN (");
1627 } else if (!(strcasecmp(op,"not in"))) {
1628 buffer_add(sql_buf, "NOT IN (");
1630 buffer_add(sql_buf, "IN (");
1633 if (node->type == JSON_HASH) {
1634 // subquery predicate
1635 char* subpred = SELECT(
1637 jsonObjectGetKey( node, "select" ),
1638 jsonObjectGetKey( node, "from" ),
1639 jsonObjectGetKey( node, "where" ),
1640 jsonObjectGetKey( node, "having" ),
1641 jsonObjectGetKey( node, "order_by" ),
1642 jsonObjectGetKey( node, "limit" ),
1643 jsonObjectGetKey( node, "offset" ),
1647 buffer_add(sql_buf, subpred);
1650 } else if (node->type == JSON_ARRAY) {
1651 // litteral value list
1652 int in_item_index = 0;
1653 int in_item_first = 1;
1654 jsonObject* in_item;
1655 while ( (in_item = jsonObjectGetIndex(node, in_item_index++)) ) {
1660 buffer_add(sql_buf, ", ");
1662 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1663 char* val = jsonNumberToDBString( field, in_item );
1664 OSRF_BUFFER_ADD( sql_buf, val );
1668 char* key_string = jsonObjectToSimpleString(in_item);
1669 if ( dbi_conn_quote_string(dbhandle, &key_string) ) {
1670 OSRF_BUFFER_ADD( sql_buf, key_string );
1673 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, key_string);
1675 buffer_free(sql_buf);
1682 OSRF_BUFFER_ADD_CHAR( sql_buf, ')' );
1684 return buffer_release(sql_buf);
1687 // Receive a JSON_ARRAY representing a function call. The first
1688 // entry in the array is the function name. The rest are parameters.
1689 static char* searchValueTransform( const jsonObject* array ) {
1690 growing_buffer* sql_buf = buffer_init(32);
1693 jsonObject* func_item;
1695 // Get the function name
1696 if( array->size > 0 ) {
1697 func_item = jsonObjectGetIndex( array, 0 );
1698 val = jsonObjectToSimpleString( func_item );
1699 OSRF_BUFFER_ADD( sql_buf, val );
1700 OSRF_BUFFER_ADD( sql_buf, "( " );
1704 // Get the parameters
1705 int func_item_index = 1; // We already grabbed the zeroth entry
1706 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1708 // Add a separator comma, if we need one
1709 if( func_item_index > 2 )
1710 buffer_add( sql_buf, ", " );
1712 // Add the current parameter
1713 if (func_item->type == JSON_NULL) {
1714 buffer_add( sql_buf, "NULL" );
1716 val = jsonObjectToSimpleString(func_item);
1717 if ( dbi_conn_quote_string(dbhandle, &val) ) {
1718 OSRF_BUFFER_ADD( sql_buf, val );
1721 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1722 buffer_free(sql_buf);
1729 buffer_add( sql_buf, " )" );
1731 return buffer_release(sql_buf);
1734 static char* searchFunctionPredicate (const char* class, osrfHash* field,
1735 const jsonObject* node, const char* node_key) {
1736 growing_buffer* sql_buf = buffer_init(32);
1738 char* val = searchValueTransform(node);
1744 osrfHashGet(field, "name"),
1751 return buffer_release(sql_buf);
1754 // class is a class name
1755 // field is a field definition as stored in the IDL
1756 // node comes from the method parameter, and represents an entry in the SELECT list
1757 static char* searchFieldTransform (const char* class, osrfHash* field, const jsonObject* node) {
1758 growing_buffer* sql_buf = buffer_init(32);
1760 char* field_transform = jsonObjectToSimpleString( jsonObjectGetKeyConst( node, "transform" ) );
1761 char* transform_subcolumn = jsonObjectToSimpleString( jsonObjectGetKeyConst( node, "result_field" ) );
1763 if(transform_subcolumn)
1764 OSRF_BUFFER_ADD_CHAR( sql_buf, '(' ); // enclose transform in parentheses
1766 if (field_transform) {
1767 buffer_fadd( sql_buf, "%s(\"%s\".%s", field_transform, class, osrfHashGet(field, "name"));
1768 const jsonObject* array = jsonObjectGetKeyConst( node, "params" );
1771 int func_item_index = 0;
1772 jsonObject* func_item;
1773 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1775 char* val = jsonObjectToSimpleString(func_item);
1778 buffer_add( sql_buf, ",NULL" );
1779 } else if ( dbi_conn_quote_string(dbhandle, &val) ) {
1780 OSRF_BUFFER_ADD_CHAR( sql_buf, ',' );
1781 OSRF_BUFFER_ADD( sql_buf, val );
1783 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1784 free(transform_subcolumn);
1785 free(field_transform);
1787 buffer_free(sql_buf);
1794 buffer_add( sql_buf, " )" );
1797 buffer_fadd( sql_buf, "\"%s\".%s", class, osrfHashGet(field, "name"));
1800 if (transform_subcolumn)
1801 buffer_fadd( sql_buf, ").\"%s\"", transform_subcolumn );
1803 if (field_transform) free(field_transform);
1804 if (transform_subcolumn) free(transform_subcolumn);
1806 return buffer_release(sql_buf);
1809 static char* searchFieldTransformPredicate (const char* class, osrfHash* field, jsonObject* node, const char* node_key) {
1810 char* field_transform = searchFieldTransform( class, field, node );
1813 if (!jsonObjectGetKeyConst( node, "value" )) {
1814 value = searchWHERE( node, osrfHashGet( oilsIDL(), class ), AND_OP_JOIN, NULL );
1815 } else if (jsonObjectGetKeyConst( node, "value" )->type == JSON_ARRAY) {
1816 value = searchValueTransform(jsonObjectGetKeyConst( node, "value" ));
1817 } else if (jsonObjectGetKeyConst( node, "value" )->type == JSON_HASH) {
1818 value = searchWHERE( jsonObjectGetKeyConst( node, "value" ), osrfHashGet( oilsIDL(), class ), AND_OP_JOIN, NULL );
1819 } else if (jsonObjectGetKeyConst( node, "value" )->type != JSON_NULL) {
1820 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1821 value = jsonNumberToDBString( field, jsonObjectGetKeyConst( node, "value" ) );
1823 value = jsonObjectToSimpleString(jsonObjectGetKeyConst( node, "value" ));
1824 if ( !dbi_conn_quote_string(dbhandle, &value) ) {
1825 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, value);
1827 free(field_transform);
1833 growing_buffer* sql_buf = buffer_init(32);
1844 free(field_transform);
1846 return buffer_release(sql_buf);
1849 static char* searchSimplePredicate (const char* orig_op, const char* class,
1850 osrfHash* field, const jsonObject* node) {
1854 if (node->type != JSON_NULL) {
1855 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1856 val = jsonNumberToDBString( field, node );
1858 val = jsonObjectToSimpleString(node);
1862 char* pred = searchWriteSimplePredicate( class, field, osrfHashGet(field, "name"), orig_op, val );
1869 static char* searchWriteSimplePredicate ( const char* class, osrfHash* field,
1870 const char* left, const char* orig_op, const char* right ) {
1874 if (right == NULL) {
1875 val = strdup("NULL");
1877 if (strcmp( orig_op, "=" ))
1878 op = strdup("IS NOT");
1882 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1883 val = strdup(right);
1884 op = strdup(orig_op);
1887 val = strdup(right);
1888 if ( !dbi_conn_quote_string(dbhandle, &val) ) {
1889 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1893 op = strdup(orig_op);
1896 growing_buffer* sql_buf = buffer_init(16);
1897 buffer_fadd( sql_buf, "\"%s\".%s %s %s", class, left, op, val );
1901 return buffer_release(sql_buf);
1904 static char* searchBETWEENPredicate (const char* class, osrfHash* field, jsonObject* node) {
1909 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1910 x_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,0));
1911 y_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,1));
1914 x_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,0));
1915 y_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,1));
1916 if ( !(dbi_conn_quote_string(dbhandle, &x_string) && dbi_conn_quote_string(dbhandle, &y_string)) ) {
1917 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key strings [%s] and [%s]", MODULENAME, x_string, y_string);
1924 growing_buffer* sql_buf = buffer_init(32);
1925 buffer_fadd( sql_buf, "%s BETWEEN %s AND %s", osrfHashGet(field, "name"), x_string, y_string );
1929 return buffer_release(sql_buf);
1932 static char* searchPredicate ( const char* class, osrfHash* field,
1933 jsonObject* node, osrfMethodContext* ctx ) {
1936 if (node->type == JSON_ARRAY) { // equality IN search
1937 pred = searchINPredicate( class, field, node, NULL, ctx );
1938 } else if (node->type == JSON_HASH) { // non-equality search
1939 jsonObject* pred_node;
1940 jsonIterator* pred_itr = jsonNewIterator( node );
1941 while ( (pred_node = jsonIteratorNext( pred_itr )) ) {
1942 if ( !(strcasecmp( pred_itr->key,"between" )) )
1943 pred = searchBETWEENPredicate( class, field, pred_node );
1944 else if ( !(strcasecmp( pred_itr->key,"in" )) || !(strcasecmp( pred_itr->key,"not in" )) )
1945 pred = searchINPredicate( class, field, pred_node, pred_itr->key, ctx );
1946 else if ( pred_node->type == JSON_ARRAY )
1947 pred = searchFunctionPredicate( class, field, pred_node, pred_itr->key );
1948 else if ( pred_node->type == JSON_HASH )
1949 pred = searchFieldTransformPredicate( class, field, pred_node, pred_itr->key );
1951 pred = searchSimplePredicate( pred_itr->key, class, field, pred_node );
1955 jsonIteratorFree(pred_itr);
1956 } else if (node->type == JSON_NULL) { // IS NULL search
1957 growing_buffer* _p = buffer_init(64);
1960 "\"%s\".%s IS NULL",
1962 osrfHashGet(field, "name")
1964 pred = buffer_release(_p);
1965 } else { // equality search
1966 pred = searchSimplePredicate( "=", class, field, node );
1985 field : call_number,
2001 static char* searchJOIN ( const jsonObject* join_hash, osrfHash* leftmeta ) {
2003 const jsonObject* working_hash;
2004 jsonObject* freeable_hash = NULL;
2006 if (join_hash->type == JSON_STRING) {
2007 // create a wrapper around a copy of the original
2008 char* _tmp = jsonObjectToSimpleString( join_hash );
2009 freeable_hash = jsonNewObjectType(JSON_HASH);
2010 jsonObjectSetKey(freeable_hash, _tmp, NULL);
2012 working_hash = freeable_hash;
2015 if( join_hash->type != JSON_HASH ) {
2018 "%s: JOIN failed; expected JSON object type not found",
2023 working_hash = join_hash;
2026 growing_buffer* join_buf = buffer_init(128);
2027 const char* leftclass = osrfHashGet(leftmeta, "classname");
2029 jsonObject* snode = NULL;
2030 jsonIterator* search_itr = jsonNewIterator( working_hash );
2032 jsonObjectFree(freeable_hash);
2034 while ( (snode = jsonIteratorNext( search_itr )) ) {
2035 osrfHash* idlClass = osrfHashGet( oilsIDL(), search_itr->key );
2037 const char* class = osrfHashGet(idlClass, "classname");
2039 char* fkey = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "fkey" ) );
2040 char* field = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "field" ) );
2042 if (field && !fkey) {
2043 fkey = (char*)oilsIDLFindPath("/%s/links/%s/key", class, field);
2047 "%s: JOIN failed. No link defined from %s.%s to %s",
2053 buffer_free(join_buf);
2055 jsonIteratorFree(search_itr);
2058 fkey = strdup( fkey );
2060 } else if (!field && fkey) {
2061 field = (char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, fkey );
2065 "%s: JOIN failed. No link defined from %s.%s to %s",
2071 buffer_free(join_buf);
2073 jsonIteratorFree(search_itr);
2076 field = strdup( field );
2078 } else if (!field && !fkey) {
2079 osrfHash* _links = oilsIDLFindPath("/%s/links", leftclass);
2082 const char* tmp_fkey;
2083 osrfStringArray* keys = osrfHashKeys( _links );
2084 while ( (tmp_fkey = osrfStringArrayGetString(keys, i++)) ) {
2085 if ( !strcmp( (char*)oilsIDLFindPath("/%s/links/%s/class", leftclass, tmp_fkey), class) ) {
2086 field = strdup( (char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, tmp_fkey) );
2087 fkey = strdup(tmp_fkey);
2091 osrfStringArrayFree(keys);
2093 if (!field && !fkey) {
2094 _links = oilsIDLFindPath("/%s/links", class);
2097 const char* tmp_fld;
2098 keys = osrfHashKeys( _links );
2099 while ( (tmp_fld = osrfStringArrayGetString(keys, i++)) ) {
2100 if ( !strcmp( (char*)oilsIDLFindPath("/%s/links/%s/class", class, tmp_fld), class) ) {
2101 fkey = strdup( (char*)oilsIDLFindPath("/%s/links/%s/key", class, tmp_fld) );
2102 field = strdup( tmp_fld );
2106 osrfStringArrayFree(keys);
2109 if (!field && !fkey) {
2112 "%s: JOIN failed. No link defined between %s and %s",
2117 buffer_free(join_buf);
2118 jsonIteratorFree(search_itr);
2124 char* type = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "type" ) );
2126 if ( !strcasecmp(type,"left") ) {
2127 buffer_add(join_buf, " LEFT JOIN");
2128 } else if ( !strcasecmp(type,"right") ) {
2129 buffer_add(join_buf, " RIGHT JOIN");
2130 } else if ( !strcasecmp(type,"full") ) {
2131 buffer_add(join_buf, " FULL JOIN");
2133 buffer_add(join_buf, " INNER JOIN");
2136 buffer_add(join_buf, " INNER JOIN");
2140 char* table = getSourceDefinition(idlClass);
2141 buffer_fadd(join_buf, " %s AS \"%s\" ON ( \"%s\".%s = \"%s\".%s",
2142 table, class, class, field, leftclass, fkey);
2145 const jsonObject* filter = jsonObjectGetKeyConst( snode, "filter" );
2147 char* filter_op = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "filter_op" ) );
2149 if (!strcasecmp("or",filter_op)) {
2150 buffer_add( join_buf, " OR " );
2152 buffer_add( join_buf, " AND " );
2155 buffer_add( join_buf, " AND " );
2158 char* jpred = searchWHERE( filter, idlClass, AND_OP_JOIN, NULL );
2159 OSRF_BUFFER_ADD_CHAR( join_buf, ' ' );
2160 OSRF_BUFFER_ADD( join_buf, jpred );
2165 buffer_add(join_buf, " ) ");
2167 const jsonObject* join_filter = jsonObjectGetKeyConst( snode, "join" );
2169 char* jpred = searchJOIN( join_filter, idlClass );
2170 OSRF_BUFFER_ADD_CHAR( join_buf, ' ' );
2171 OSRF_BUFFER_ADD( join_buf, jpred );
2179 jsonIteratorFree(search_itr);
2181 return buffer_release(join_buf);
2186 { +class : { -or|-and : { field : { op : value }, ... } ... }, ... }
2187 { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }
2188 [ { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }, ... ]
2192 static char* searchWHERE ( const jsonObject* search_hash, osrfHash* meta, int opjoin_type, osrfMethodContext* ctx ) {
2196 "%s: Entering searchWHERE; search_hash addr = %p, meta addr = %p, opjoin_type = %d, ctx addr = %p",
2204 growing_buffer* sql_buf = buffer_init(128);
2206 jsonObject* node = NULL;
2209 if ( search_hash->type == JSON_ARRAY ) {
2210 osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_ARRAY", MODULENAME);
2211 jsonIterator* search_itr = jsonNewIterator( search_hash );
2212 while ( (node = jsonIteratorNext( search_itr )) ) {
2216 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2217 else buffer_add(sql_buf, " AND ");
2220 char* subpred = searchWHERE( node, meta, opjoin_type, ctx );
2221 buffer_fadd(sql_buf, "( %s )", subpred);
2224 jsonIteratorFree(search_itr);
2226 } else if ( search_hash->type == JSON_HASH ) {
2227 osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_HASH", MODULENAME);
2228 jsonIterator* search_itr = jsonNewIterator( search_hash );
2229 while ( (node = jsonIteratorNext( search_itr )) ) {
2234 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2235 else buffer_add(sql_buf, " AND ");
2238 if ( !strncmp("+",search_itr->key,1) ) {
2239 if ( node->type == JSON_STRING ) {
2240 char* subpred = jsonObjectToSimpleString( node );
2241 buffer_fadd(sql_buf, " \"%s\".%s ", search_itr->key + 1, subpred);
2244 char* subpred = searchWHERE( node, osrfHashGet( oilsIDL(), search_itr->key + 1 ), AND_OP_JOIN, ctx );
2245 buffer_fadd(sql_buf, "( %s )", subpred);
2248 } else if ( !strcasecmp("-or",search_itr->key) ) {
2249 char* subpred = searchWHERE( node, meta, OR_OP_JOIN, ctx );
2250 buffer_fadd(sql_buf, "( %s )", subpred);
2252 } else if ( !strcasecmp("-and",search_itr->key) ) {
2253 char* subpred = searchWHERE( node, meta, AND_OP_JOIN, ctx );
2254 buffer_fadd(sql_buf, "( %s )", subpred);
2256 } else if ( !strcasecmp("-exists",search_itr->key) ) {
2257 char* subpred = SELECT(
2259 jsonObjectGetKey( node, "select" ),
2260 jsonObjectGetKey( node, "from" ),
2261 jsonObjectGetKey( node, "where" ),
2262 jsonObjectGetKey( node, "having" ),
2263 jsonObjectGetKey( node, "order_by" ),
2264 jsonObjectGetKey( node, "limit" ),
2265 jsonObjectGetKey( node, "offset" ),
2269 buffer_fadd(sql_buf, "EXISTS ( %s )", subpred);
2271 } else if ( !strcasecmp("-not-exists",search_itr->key) ) {
2272 char* subpred = SELECT(
2274 jsonObjectGetKey( node, "select" ),
2275 jsonObjectGetKey( node, "from" ),
2276 jsonObjectGetKey( node, "where" ),
2277 jsonObjectGetKey( node, "having" ),
2278 jsonObjectGetKey( node, "order_by" ),
2279 jsonObjectGetKey( node, "limit" ),
2280 jsonObjectGetKey( node, "offset" ),
2284 buffer_fadd(sql_buf, "NOT EXISTS ( %s )", subpred);
2288 char* class = osrfHashGet(meta, "classname");
2289 osrfHash* fields = osrfHashGet(meta, "fields");
2290 osrfHash* field = osrfHashGet( fields, search_itr->key );
2294 char* table = getSourceDefinition(meta);
2297 "%s: Attempt to reference non-existent column %s on %s (%s)",
2303 buffer_free(sql_buf);
2305 jsonIteratorFree(search_itr);
2309 char* subpred = searchPredicate( class, field, node, ctx );
2310 buffer_add( sql_buf, subpred );
2314 jsonIteratorFree(search_itr);
2317 // ERROR ... only hash and array allowed at this level
2318 char* predicate_string = jsonObjectToJSON( search_hash );
2321 "%s: Invalid predicate structure: %s",
2325 buffer_free(sql_buf);
2326 free(predicate_string);
2331 return buffer_release(sql_buf);
2335 /* method context */ osrfMethodContext* ctx,
2337 /* SELECT */ jsonObject* selhash,
2338 /* FROM */ jsonObject* join_hash,
2339 /* WHERE */ jsonObject* search_hash,
2340 /* HAVING */ jsonObject* having_hash,
2341 /* ORDER BY */ jsonObject* order_hash,
2342 /* LIMIT */ jsonObject* limit,
2343 /* OFFSET */ jsonObject* offset,
2344 /* flags */ int flags
2346 const char* locale = osrf_message_get_last_locale();
2348 // in case we don't get a select list
2349 jsonObject* defaultselhash = NULL;
2351 // general tmp objects
2352 const jsonObject* tmp_const;
2353 jsonObject* selclass = NULL;
2354 jsonObject* selfield = NULL;
2355 jsonObject* snode = NULL;
2356 jsonObject* onode = NULL;
2358 char* string = NULL;
2359 int from_function = 0;
2364 // the core search class
2365 char* core_class = NULL;
2367 // metadata about the core search class
2368 osrfHash* core_meta = NULL;
2370 // punt if there's no core class
2371 if (!join_hash || ( join_hash->type == JSON_HASH && !join_hash->size ))
2374 // get the core class -- the only key of the top level FROM clause, or a string
2375 if (join_hash->type == JSON_HASH) {
2376 jsonIterator* tmp_itr = jsonNewIterator( join_hash );
2377 snode = jsonIteratorNext( tmp_itr );
2379 core_class = strdup( tmp_itr->key );
2382 jsonObject* extra = jsonIteratorNext( tmp_itr );
2384 jsonIteratorFree( tmp_itr );
2387 // There shouldn't be more than one entry in join_hash
2389 return NULL; // Malformed join_hash; extra entry
2391 } else if (join_hash->type == JSON_ARRAY) {
2393 core_class = jsonObjectToSimpleString( jsonObjectGetIndex(join_hash, 0) );
2396 } else if (join_hash->type == JSON_STRING) {
2397 core_class = jsonObjectToSimpleString( join_hash );
2403 // punt if we don't know about the core class (and it's not a function)
2404 if (!from_function && !(core_meta = osrfHashGet( oilsIDL(), core_class ))) {
2409 // if the select list is empty, or the core class field list is '*',
2410 // build the default select list ...
2412 selhash = defaultselhash = jsonNewObjectType(JSON_HASH);
2413 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2414 } else if ( (tmp_const = jsonObjectGetKeyConst( selhash, core_class )) && tmp_const->type == JSON_STRING ) {
2415 char* _x = jsonObjectToSimpleString( tmp_const );
2416 if (!strncmp( "*", _x, 1 )) {
2417 jsonObjectRemoveKey( selhash, core_class );
2418 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2424 growing_buffer* sql_buf = buffer_init(128);
2426 // temp buffer for the SELECT list
2427 growing_buffer* select_buf = buffer_init(128);
2428 growing_buffer* order_buf = buffer_init(128);
2429 growing_buffer* group_buf = buffer_init(128);
2430 growing_buffer* having_buf = buffer_init(128);
2432 // Build a select list
2433 if(from_function) // From a function we select everything
2434 OSRF_BUFFER_ADD_CHAR( select_buf, '*' );
2437 // If we need to build a default list, do so
2438 jsonObject* _tmp = jsonObjectGetKey( selhash, core_class );
2439 if ( _tmp && !_tmp->size ) {
2443 osrfHash* core_fields = osrfHashGet( core_meta, "fields" );
2445 osrfStringArray* keys = osrfHashKeys( core_fields );
2446 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
2447 if( ! str_is_true( osrfHashGet( osrfHashGet( core_fields, field ), "virtual" ) ) )
2448 jsonObjectPush( _tmp, jsonNewObject( field ) ); // not virtual; use it
2450 osrfStringArrayFree(keys);
2453 // Now build the actual select list
2455 jsonObject* is_agg = jsonObjectFindPath(selhash, "//aggregate");
2458 jsonIterator* selclass_itr = jsonNewIterator( selhash );
2459 while ( (selclass = jsonIteratorNext( selclass_itr )) ) { // For each class
2461 // round trip through the idl, just to be safe
2462 const char* cname = selclass_itr->key;
2463 osrfHash* idlClass = osrfHashGet( oilsIDL(), cname );
2465 // No such class. Skip it.
2468 // Make sure the target relation is in the join tree.
2470 // At this point join_hash is a step down from the join_hash we
2471 // received as a parameter. If the original was a JSON_STRING,
2472 // then json_hash is now NULL. If the original was a JSON_HASH,
2473 // then json_hash is now the first (and only) entry in it,
2474 // denoting the core class. We've already excluded the
2475 // possibility that the original was a JSON_ARRAY, because in
2476 // that case from_function would be non-NULL, and we wouldn't
2479 if ( strcmp( core_class, cname )) {
2481 // There's only one class in the FROM clause,
2482 // and this isn't it. Skip it.
2485 if (join_hash->type == JSON_STRING) {
2486 string = jsonObjectToSimpleString(join_hash);
2487 int different = strcmp( string, cname );
2490 // There's only one class in the FROM clause,
2491 // and this isn't it. Skip it.
2494 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", cname);
2495 unsigned long size = found->size;
2496 jsonObjectFree( found );
2498 // No such class anywhere in the join tree. Skip it.
2503 // Look up some attributes of the current class, so that we
2504 // don't have to look them up again for each field
2505 osrfHash* class_field_set = osrfHashGet( idlClass, "fields" );
2506 char* class_pkey = osrfHashGet( idlClass, "primarykey" );
2507 char* class_tname = osrfHashGet( idlClass, "tablename" );
2509 // stitch together the column list ...
2510 jsonIterator* select_itr = jsonNewIterator( selclass );
2511 while ( (selfield = jsonIteratorNext( select_itr )) ) { // for each SELECT column
2513 // If we need a separator comma, add one
2517 OSRF_BUFFER_ADD_CHAR( select_buf, ',' );
2520 // ... if it's a string, just toss it on the pile
2521 if (selfield->type == JSON_STRING) {
2523 // again, just to be safe
2524 const char* _requested_col = selfield->value.s;
2525 osrfHash* field = osrfHashGet( class_field_set, _requested_col );
2526 if (!field) continue; // No such field in current class; skip it
2528 const char* col_name = osrfHashGet(field, "name");
2532 if (flags & DISABLE_I18N)
2535 i18n = osrfHashGet(field, "i18n");
2537 if( str_is_true( i18n ) ) {
2538 buffer_fadd( select_buf,
2539 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2540 class_tname, cname, col_name, class_pkey, cname, class_pkey, locale, col_name );
2542 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2545 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2548 // ... but it could be an object, in which case we check for a Field Transform
2551 char* _column = jsonObjectToSimpleString( jsonObjectGetKeyConst( selfield, "column" ) );
2553 // Get the field definition from the IDL
2554 osrfHash* field = osrfHashGet( class_field_set, _column );
2555 if (!field) continue; // No such field defined in IDL. Skip it.
2557 // Decide what to use as a column alias
2559 if ((tmp_const = jsonObjectGetKeyConst( selfield, "alias" ))) {
2560 _alias = jsonObjectToSimpleString( tmp_const );
2562 } else { // Use column name as its own alias
2565 _column = NULL; // To emphasize that we're through with _column
2567 if (jsonObjectGetKeyConst( selfield, "transform" )) {
2568 char* transform_str = searchFieldTransform(cname, field, selfield);
2569 buffer_fadd(select_buf, " %s AS \"%s\"", transform_str, _alias);
2570 free(transform_str);
2573 const char* fname = osrfHashGet(field, "name");
2577 if (flags & DISABLE_I18N)
2580 i18n = osrfHashGet(field, "i18n");
2582 if( str_is_true( i18n ) ) {
2583 buffer_fadd( select_buf,
2584 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2585 class_tname, cname, fname, class_pkey, cname, class_pkey, locale, _alias);
2587 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, fname, _alias);
2590 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, fname, _alias);
2597 if (is_agg->size || (flags & SELECT_DISTINCT)) {
2599 const jsonObject* aggregate_obj = jsonObjectGetKey( selfield, "aggregate" );
2600 if ( ! obj_is_true( aggregate_obj ) ) {
2604 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
2607 buffer_fadd(group_buf, " %d", sel_pos);
2609 } else if (is_agg = jsonObjectGetKey( selfield, "having" )) {
2613 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
2616 _column = searchFieldTransform(cname, field, selfield);
2617 OSRF_BUFFER_ADD_CHAR(group_buf, ' ');
2618 OSRF_BUFFER_ADD(group_buf, _column);
2619 _column = searchFieldTransform(cname, field, selfield);
2625 } // end while -- iterating across SELECT columns
2627 jsonIteratorFree(select_itr);
2628 } // end while -- iterating across classes
2630 jsonIteratorFree(selclass_itr);
2632 if (is_agg) jsonObjectFree(is_agg);
2636 char* col_list = buffer_release(select_buf);
2638 if (from_function) table = searchValueTransform(join_hash);
2639 else table = getSourceDefinition(core_meta);
2641 // Put it all together
2642 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\" ", col_list, table, core_class );
2646 if (!from_function) {
2647 // Now, walk the join tree and add that clause
2649 char* join_clause = searchJOIN( join_hash, core_meta );
2650 buffer_add(sql_buf, join_clause);
2654 // Build a WHERE clause, if there is one
2655 if ( search_hash ) {
2656 buffer_add(sql_buf, " WHERE ");
2658 // and it's on the WHERE clause
2659 char* pred = searchWHERE( search_hash, core_meta, AND_OP_JOIN, ctx );
2662 buffer_add(sql_buf, pred);
2666 osrfAppSessionStatus(
2668 OSRF_STATUS_INTERNALSERVERERROR,
2669 "osrfMethodException",
2671 "Severe query error in WHERE predicate -- see error log for more details"
2675 buffer_free(having_buf);
2676 buffer_free(group_buf);
2677 buffer_free(order_buf);
2678 buffer_free(sql_buf);
2679 if (defaultselhash) jsonObjectFree(defaultselhash);
2684 // Build a HAVING clause, if there is one
2685 if ( having_hash ) {
2686 buffer_add(sql_buf, " HAVING ");
2688 // and it's on the the WHERE clause
2689 char* pred = searchWHERE( having_hash, core_meta, AND_OP_JOIN, ctx );
2692 buffer_add(sql_buf, pred);
2696 osrfAppSessionStatus(
2698 OSRF_STATUS_INTERNALSERVERERROR,
2699 "osrfMethodException",
2701 "Severe query error in HAVING predicate -- see error log for more details"
2705 buffer_free(having_buf);
2706 buffer_free(group_buf);
2707 buffer_free(order_buf);
2708 buffer_free(sql_buf);
2709 if (defaultselhash) jsonObjectFree(defaultselhash);
2714 // Build an ORDER BY clause, if there is one
2716 jsonIterator* class_itr = jsonNewIterator( order_hash );
2717 while ( (snode = jsonIteratorNext( class_itr )) ) {
2719 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
2722 if ( snode->type == JSON_HASH ) {
2724 jsonIterator* order_itr = jsonNewIterator( snode );
2725 while ( (onode = jsonIteratorNext( order_itr )) ) {
2727 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
2730 char* direction = NULL;
2731 if ( onode->type == JSON_HASH ) {
2732 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
2733 string = searchFieldTransform(
2735 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
2739 growing_buffer* field_buf = buffer_init(16);
2740 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
2741 string = buffer_release(field_buf);
2744 if ( (tmp_const = jsonObjectGetKeyConst( onode, "direction" )) ) {
2745 direction = jsonObjectToSimpleString(tmp_const);
2746 if (!strncasecmp(direction, "d", 1)) {
2748 direction = " DESC";
2756 string = strdup(order_itr->key);
2757 direction = jsonObjectToSimpleString(onode);
2758 if (!strncasecmp(direction, "d", 1)) {
2760 direction = " DESC";
2770 buffer_add(order_buf, ", ");
2773 buffer_add(order_buf, string);
2777 buffer_add(order_buf, direction);
2781 // jsonIteratorFree(order_itr);
2783 } else if ( snode->type == JSON_ARRAY ) {
2785 jsonIterator* order_itr = jsonNewIterator( snode );
2786 while ( (onode = jsonIteratorNext( order_itr )) ) {
2788 char* _f = jsonObjectToSimpleString( onode );
2790 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, _f))
2796 buffer_add(order_buf, ", ");
2799 buffer_add(order_buf, _f);
2803 // jsonIteratorFree(order_itr);
2806 // IT'S THE OOOOOOOOOOOLD STYLE!
2808 osrfLogError(OSRF_LOG_MARK, "%s: Possible SQL injection attempt; direct order by is not allowed", MODULENAME);
2810 osrfAppSessionStatus(
2812 OSRF_STATUS_INTERNALSERVERERROR,
2813 "osrfMethodException",
2815 "Severe query error -- see error log for more details"
2820 buffer_free(having_buf);
2821 buffer_free(group_buf);
2822 buffer_free(order_buf);
2823 buffer_free(sql_buf);
2824 if (defaultselhash) jsonObjectFree(defaultselhash);
2825 jsonIteratorFree(class_itr);
2830 // jsonIteratorFree(class_itr);
2834 string = buffer_release(group_buf);
2836 if (strlen(string)) {
2837 OSRF_BUFFER_ADD( sql_buf, " GROUP BY " );
2838 OSRF_BUFFER_ADD( sql_buf, string );
2843 string = buffer_release(having_buf);
2845 if (strlen(string)) {
2846 OSRF_BUFFER_ADD( sql_buf, " HAVING " );
2847 OSRF_BUFFER_ADD( sql_buf, string );
2852 string = buffer_release(order_buf);
2854 if (strlen(string)) {
2855 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
2856 OSRF_BUFFER_ADD( sql_buf, string );
2862 string = jsonObjectToSimpleString(limit);
2863 buffer_fadd( sql_buf, " LIMIT %d", atoi(string) );
2868 string = jsonObjectToSimpleString(offset);
2869 buffer_fadd( sql_buf, " OFFSET %d", atoi(string) );
2873 if (!(flags & SUBSELECT)) OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
2876 if (defaultselhash) jsonObjectFree(defaultselhash);
2878 return buffer_release(sql_buf);
2882 static char* buildSELECT ( jsonObject* search_hash, jsonObject* order_hash, osrfHash* meta, osrfMethodContext* ctx ) {
2884 const char* locale = osrf_message_get_last_locale();
2886 osrfHash* fields = osrfHashGet(meta, "fields");
2887 char* core_class = osrfHashGet(meta, "classname");
2889 const jsonObject* join_hash = jsonObjectGetKeyConst( order_hash, "join" );
2891 jsonObject* node = NULL;
2892 jsonObject* snode = NULL;
2893 jsonObject* onode = NULL;
2894 const jsonObject* _tmp = NULL;
2895 jsonObject* selhash = NULL;
2896 jsonObject* defaultselhash = NULL;
2898 growing_buffer* sql_buf = buffer_init(128);
2899 growing_buffer* select_buf = buffer_init(128);
2901 if ( !(selhash = jsonObjectGetKey( order_hash, "select" )) ) {
2902 defaultselhash = jsonNewObjectType(JSON_HASH);
2903 selhash = defaultselhash;
2906 if ( !jsonObjectGetKeyConst(selhash,core_class) ) {
2907 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2908 jsonObject* flist = jsonObjectGetKey( selhash, core_class );
2913 osrfStringArray* keys = osrfHashKeys( fields );
2914 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
2915 if( ! str_is_true( osrfHashGet( osrfHashGet( fields, field ), "virtual" ) ) )
2916 jsonObjectPush( flist, jsonNewObject( field ) );
2918 osrfStringArrayFree(keys);
2922 jsonIterator* class_itr = jsonNewIterator( selhash );
2923 while ( (snode = jsonIteratorNext( class_itr )) ) {
2925 osrfHash* idlClass = osrfHashGet( oilsIDL(), class_itr->key );
2926 if (!idlClass) continue;
2927 char* cname = osrfHashGet(idlClass, "classname");
2929 if (strcmp(core_class,class_itr->key)) {
2930 if (!join_hash) continue;
2932 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", class_itr->key);
2934 jsonObjectFree(found);
2938 jsonObjectFree(found);
2941 jsonIterator* select_itr = jsonNewIterator( snode );
2942 while ( (node = jsonIteratorNext( select_itr )) ) {
2943 char* item_str = jsonObjectToSimpleString(node);
2944 osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), item_str );
2946 char* fname = osrfHashGet(field, "name");
2948 if (!field) continue;
2953 OSRF_BUFFER_ADD_CHAR(select_buf, ',');
2958 const jsonObject* no_i18n_obj = jsonObjectGetKey( order_hash, "no_i18n" );
2959 if ( obj_is_true( no_i18n_obj ) ) // Suppress internationalization?
2962 i18n = osrfHashGet(field, "i18n");
2964 if( str_is_true( i18n ) ) {
2965 char* pkey = osrfHashGet(idlClass, "primarykey");
2966 char* tname = osrfHashGet(idlClass, "tablename");
2968 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);
2970 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
2973 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
2977 jsonIteratorFree(select_itr);
2980 jsonIteratorFree(class_itr);
2982 char* col_list = buffer_release(select_buf);
2983 char* table = getSourceDefinition(meta);
2985 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\"", col_list, table, core_class );
2990 char* join_clause = searchJOIN( join_hash, meta );
2991 OSRF_BUFFER_ADD_CHAR(sql_buf, ' ');
2992 OSRF_BUFFER_ADD(sql_buf, join_clause);
2996 osrfLogDebug(OSRF_LOG_MARK, "%s pre-predicate SQL = %s",
2997 MODULENAME, OSRF_BUFFER_C_STR(sql_buf));
2999 buffer_add(sql_buf, " WHERE ");
3001 char* pred = searchWHERE( search_hash, meta, AND_OP_JOIN, ctx );
3003 osrfAppSessionStatus(
3005 OSRF_STATUS_INTERNALSERVERERROR,
3006 "osrfMethodException",
3008 "Severe query error -- see error log for more details"
3010 buffer_free(sql_buf);
3011 if(defaultselhash) jsonObjectFree(defaultselhash);
3014 buffer_add(sql_buf, pred);
3019 char* string = NULL;
3020 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "order_by" )) ){
3022 growing_buffer* order_buf = buffer_init(128);
3025 jsonIterator* class_itr = jsonNewIterator( _tmp );
3026 while ( (snode = jsonIteratorNext( class_itr )) ) {
3028 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
3031 if ( snode->type == JSON_HASH ) {
3033 jsonIterator* order_itr = jsonNewIterator( snode );
3034 while ( (onode = jsonIteratorNext( order_itr )) ) {
3036 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
3039 char* direction = NULL;
3040 if ( onode->type == JSON_HASH ) {
3041 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
3042 string = searchFieldTransform(
3044 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
3048 growing_buffer* field_buf = buffer_init(16);
3049 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
3050 string = buffer_release(field_buf);
3053 if ( (_tmp = jsonObjectGetKeyConst( onode, "direction" )) ) {
3054 direction = jsonObjectToSimpleString(_tmp);
3055 if (!strncasecmp(direction, "d", 1)) {
3057 direction = " DESC";
3065 string = strdup(order_itr->key);
3066 direction = jsonObjectToSimpleString(onode);
3067 if (!strncasecmp(direction, "d", 1)) {
3069 direction = " DESC";
3079 buffer_add(order_buf, ", ");
3082 buffer_add(order_buf, string);
3086 buffer_add(order_buf, direction);
3091 jsonIteratorFree(order_itr);
3094 string = jsonObjectToSimpleString(snode);
3095 buffer_add(order_buf, string);
3102 jsonIteratorFree(class_itr);
3104 string = buffer_release(order_buf);
3106 if (strlen(string)) {
3107 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
3108 OSRF_BUFFER_ADD( sql_buf, string );
3114 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "limit" )) ){
3115 string = jsonObjectToSimpleString(_tmp);
3124 _tmp = jsonObjectGetKeyConst( order_hash, "offset" );
3126 string = jsonObjectToSimpleString(_tmp);
3136 if (defaultselhash) jsonObjectFree(defaultselhash);
3138 OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
3139 return buffer_release(sql_buf);
3142 int doJSONSearch ( osrfMethodContext* ctx ) {
3143 if(osrfMethodVerifyContext( ctx )) {
3144 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
3148 osrfLogDebug(OSRF_LOG_MARK, "Recieved query request");
3153 dbhandle = writehandle;
3155 jsonObject* hash = jsonObjectGetIndex(ctx->params, 0);
3159 if ( obj_is_true( jsonObjectGetKey( hash, "distinct" ) ) )
3160 flags |= SELECT_DISTINCT;
3162 if ( obj_is_true( jsonObjectGetKey( hash, "no_i18n" ) ) )
3163 flags |= DISABLE_I18N;
3165 osrfLogDebug(OSRF_LOG_MARK, "Building SQL ...");
3168 jsonObjectGetKey( hash, "select" ),
3169 jsonObjectGetKey( hash, "from" ),
3170 jsonObjectGetKey( hash, "where" ),
3171 jsonObjectGetKey( hash, "having" ),
3172 jsonObjectGetKey( hash, "order_by" ),
3173 jsonObjectGetKey( hash, "limit" ),
3174 jsonObjectGetKey( hash, "offset" ),
3183 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3184 dbi_result result = dbi_conn_query(dbhandle, sql);
3187 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3189 if (dbi_result_first_row(result)) {
3190 /* JSONify the result */
3191 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3194 jsonObject* return_val = oilsMakeJSONFromResult( result );
3195 osrfAppRespond( ctx, return_val );
3196 jsonObjectFree( return_val );
3197 } while (dbi_result_next_row(result));
3200 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
3203 osrfAppRespondComplete( ctx, NULL );
3205 /* clean up the query */
3206 dbi_result_free(result);
3210 osrfLogError(OSRF_LOG_MARK, "%s: Error with query [%s]", MODULENAME, sql);
3211 osrfAppSessionStatus(
3213 OSRF_STATUS_INTERNALSERVERERROR,
3214 "osrfMethodException",
3216 "Severe query error -- see error log for more details"
3224 static jsonObject* doFieldmapperSearch ( osrfMethodContext* ctx, osrfHash* meta,
3225 const jsonObject* params, int* err ) {
3228 dbhandle = writehandle;
3230 osrfHash* links = osrfHashGet(meta, "links");
3231 osrfHash* fields = osrfHashGet(meta, "fields");
3232 char* core_class = osrfHashGet(meta, "classname");
3233 char* pkey = osrfHashGet(meta, "primarykey");
3235 const jsonObject* _tmp;
3237 jsonObject* search_hash = jsonObjectGetIndex(params, 0);
3238 jsonObject* order_hash = jsonObjectGetIndex(params, 1);
3240 char* sql = buildSELECT( search_hash, order_hash, meta, ctx );
3242 osrfLogDebug(OSRF_LOG_MARK, "Problem building query, returning NULL");
3247 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3249 dbi_result result = dbi_conn_query(dbhandle, sql);
3250 if( NULL == result ) {
3251 osrfLogError(OSRF_LOG_MARK, "%s: Error retrieving %s with query [%s]",
3252 MODULENAME, osrfHashGet(meta, "fieldmapper"), sql);
3253 osrfAppSessionStatus(
3255 OSRF_STATUS_INTERNALSERVERERROR,
3256 "osrfMethodException",
3258 "Severe query error -- see error log for more details"
3265 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3268 jsonObject* res_list = jsonNewObjectType(JSON_ARRAY);
3269 osrfHash* dedup = osrfNewHash();
3271 if (dbi_result_first_row(result)) {
3272 /* JSONify the result */
3273 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3275 obj = oilsMakeFieldmapperFromResult( result, meta );
3276 char* pkey_val = oilsFMGetString( obj, pkey );
3277 if ( osrfHashGet( dedup, pkey_val ) ) {
3278 jsonObjectFree(obj);
3281 osrfHashSet( dedup, pkey_val, pkey_val );
3282 jsonObjectPush(res_list, obj);
3284 } while (dbi_result_next_row(result));
3286 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s",
3290 osrfHashFree(dedup);
3291 /* clean up the query */
3292 dbi_result_free(result);
3295 if (res_list->size && order_hash) {
3296 _tmp = jsonObjectGetKeyConst( order_hash, "flesh" );
3298 int x = (int)jsonObjectGetNumber(_tmp);
3299 if (x == -1 || x > max_flesh_depth) x = max_flesh_depth;
3301 const jsonObject* temp_blob;
3302 if ((temp_blob = jsonObjectGetKeyConst( order_hash, "flesh_fields" )) && x > 0) {
3304 jsonObject* flesh_blob = jsonObjectClone( temp_blob );
3305 const jsonObject* flesh_fields = jsonObjectGetKeyConst( flesh_blob, core_class );
3307 osrfStringArray* link_fields = NULL;
3310 if (flesh_fields->size == 1) {
3311 char* _t = jsonObjectToSimpleString( jsonObjectGetIndex( flesh_fields, 0 ) );
3312 if (!strcmp(_t,"*")) link_fields = osrfHashKeys( links );
3318 link_fields = osrfNewStringArray(1);
3319 jsonIterator* _i = jsonNewIterator( flesh_fields );
3320 while ((_f = jsonIteratorNext( _i ))) {
3321 osrfStringArrayAdd( link_fields, jsonObjectToSimpleString( _f ) );
3323 jsonIteratorFree(_i);
3328 jsonIterator* itr = jsonNewIterator( res_list );
3329 while ((cur = jsonIteratorNext( itr ))) {
3334 while ( (link_field = osrfStringArrayGetString(link_fields, i++)) ) {
3336 osrfLogDebug(OSRF_LOG_MARK, "Starting to flesh %s", link_field);
3338 osrfHash* kid_link = osrfHashGet(links, link_field);
3339 if (!kid_link) continue;
3341 osrfHash* field = osrfHashGet(fields, link_field);
3342 if (!field) continue;
3344 osrfHash* value_field = field;
3346 osrfHash* kid_idl = osrfHashGet(oilsIDL(), osrfHashGet(kid_link, "class"));
3347 if (!kid_idl) continue;
3349 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3350 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3353 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) { // might_have
3354 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3357 osrfStringArray* link_map = osrfHashGet( kid_link, "map" );
3359 if (link_map->size > 0) {
3360 jsonObject* _kid_key = jsonNewObjectType(JSON_ARRAY);
3363 jsonNewObject( osrfStringArrayGetString( link_map, 0 ) )
3368 osrfHashGet(kid_link, "class"),
3375 "Link field: %s, remote class: %s, fkey: %s, reltype: %s",
3376 osrfHashGet(kid_link, "field"),
3377 osrfHashGet(kid_link, "class"),
3378 osrfHashGet(kid_link, "key"),
3379 osrfHashGet(kid_link, "reltype")
3382 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
3383 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // search hash
3384 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // order/flesh hash
3386 osrfLogDebug(OSRF_LOG_MARK, "Creating dummy params object...");
3389 jsonObjectToSimpleString(
3392 atoi( osrfHashGet(value_field, "array_position") )
3397 osrfLogDebug(OSRF_LOG_MARK, "Nothing to search for!");
3402 jsonObjectGetIndex(fake_params, 0),
3403 osrfHashGet(kid_link, "key"),
3404 jsonNewObject( search_key )
3411 jsonObjectGetIndex(fake_params, 1),
3413 jsonNewNumberObject( (double)(x - 1 + link_map->size) )
3417 jsonObjectSetKey( jsonObjectGetIndex(fake_params, 1), "flesh_fields", jsonObjectClone(flesh_blob) );
3419 if (jsonObjectGetKeyConst(order_hash, "order_by")) {
3421 jsonObjectGetIndex(fake_params, 1),
3423 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "order_by"))
3427 if (jsonObjectGetKeyConst(order_hash, "select")) {
3429 jsonObjectGetIndex(fake_params, 1),
3431 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "select"))
3435 jsonObject* kids = doFieldmapperSearch(ctx, kid_idl, fake_params, err);
3438 jsonObjectFree( fake_params );
3439 osrfStringArrayFree(link_fields);
3440 jsonIteratorFree(itr);
3441 jsonObjectFree(res_list);
3442 jsonObjectFree(flesh_blob);
3446 osrfLogDebug(OSRF_LOG_MARK, "Search for %s return %d linked objects", osrfHashGet(kid_link, "class"), kids->size);
3448 jsonObject* X = NULL;
3449 if ( link_map->size > 0 && kids->size > 0 ) {
3451 kids = jsonNewObjectType(JSON_ARRAY);
3453 jsonObject* _k_node;
3454 jsonIterator* _k = jsonNewIterator( X );
3455 while ((_k_node = jsonIteratorNext( _k ))) {
3461 (unsigned long)atoi(
3467 osrfHashGet(kid_link, "class")
3471 osrfStringArrayGetString( link_map, 0 )
3480 jsonIteratorFree(_k);
3483 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_a" )) || !(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) {
3484 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3487 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3488 jsonObjectClone( jsonObjectGetIndex(kids, 0) )
3492 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3493 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3496 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3497 jsonObjectClone( kids )
3502 jsonObjectFree(kids);
3506 jsonObjectFree( kids );
3507 jsonObjectFree( fake_params );
3509 osrfLogDebug(OSRF_LOG_MARK, "Fleshing of %s complete", osrfHashGet(kid_link, "field"));
3510 osrfLogDebug(OSRF_LOG_MARK, "%s", jsonObjectToJSON(cur));
3514 jsonObjectFree( flesh_blob );
3515 osrfStringArrayFree(link_fields);
3516 jsonIteratorFree(itr);
3525 static jsonObject* doUpdate(osrfMethodContext* ctx, int* err ) {
3527 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3529 jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
3531 jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
3534 if (!verifyObjectClass(ctx, target)) {
3539 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3540 osrfAppSessionStatus(
3542 OSRF_STATUS_BADREQUEST,
3543 "osrfMethodException",
3545 "No active transaction -- required for UPDATE"
3551 // The following test is harmless but redundant. If a class is
3552 // readonly, we don't register an update method for it.
3553 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
3554 osrfAppSessionStatus(
3556 OSRF_STATUS_BADREQUEST,
3557 "osrfMethodException",
3559 "Cannot UPDATE readonly class"
3565 dbhandle = writehandle;
3567 char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
3569 // Set the last_xact_id
3570 int index = oilsIDL_ntop( target->classname, "last_xact_id" );
3572 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
3573 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
3576 char* pkey = osrfHashGet(meta, "primarykey");
3577 osrfHash* fields = osrfHashGet(meta, "fields");
3579 char* id = oilsFMGetString( target, pkey );
3583 "%s updating %s object with %s = %s",
3585 osrfHashGet(meta, "fieldmapper"),
3590 growing_buffer* sql = buffer_init(128);
3591 buffer_fadd(sql,"UPDATE %s SET", osrfHashGet(meta, "tablename"));
3596 osrfStringArray* field_list = osrfHashKeys( fields );
3597 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
3599 osrfHash* field = osrfHashGet( fields, field_name );
3601 if(!( strcmp( field_name, pkey ) )) continue;
3602 if( str_is_true( osrfHashGet(osrfHashGet(fields,field_name), "virtual") ) )
3605 const jsonObject* field_object = oilsFMGetObject( target, field_name );
3608 if (field_object && field_object->classname) {
3609 value = oilsFMGetString(
3611 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
3614 value = jsonObjectToSimpleString( field_object );
3617 osrfLogDebug( OSRF_LOG_MARK, "Updating %s object with %s = %s", osrfHashGet(meta, "fieldmapper"), field_name, value);
3619 if (!field_object || field_object->type == JSON_NULL) {
3620 if ( !(!( strcmp( osrfHashGet(meta, "classname"), "au" ) ) && !( strcmp( field_name, "passwd" ) )) ) { // arg at the special case!
3621 if (first) first = 0;
3622 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3623 buffer_fadd( sql, " %s = NULL", field_name );
3626 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
3627 if (first) first = 0;
3628 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3630 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
3631 buffer_fadd( sql, " %s = %ld", field_name, atol(value) );
3632 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
3633 buffer_fadd( sql, " %s = %f", field_name, atof(value) );
3636 osrfLogDebug( OSRF_LOG_MARK, "%s is of type %s", field_name, osrfHashGet(field, "datatype"));
3639 if ( dbi_conn_quote_string(dbhandle, &value) ) {
3640 if (first) first = 0;
3641 else OSRF_BUFFER_ADD_CHAR(sql, ',');
3642 buffer_fadd( sql, " %s = %s", field_name, value );
3645 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
3646 osrfAppSessionStatus(
3648 OSRF_STATUS_INTERNALSERVERERROR,
3649 "osrfMethodException",
3651 "Error quoting string -- please see the error log for more details"
3665 jsonObject* obj = jsonNewObject(id);
3667 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
3668 dbi_conn_quote_string(dbhandle, &id);
3670 buffer_fadd( sql, " WHERE %s = %s;", pkey, id );
3672 char* query = buffer_release(sql);
3673 osrfLogDebug(OSRF_LOG_MARK, "%s: Update SQL [%s]", MODULENAME, query);
3675 dbi_result result = dbi_conn_query(dbhandle, query);
3679 jsonObjectFree(obj);
3680 obj = jsonNewObject(NULL);
3683 "%s ERROR updating %s object with %s = %s",
3685 osrfHashGet(meta, "fieldmapper"),
3696 static jsonObject* doDelete(osrfMethodContext* ctx, int* err ) {
3698 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3700 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3701 osrfAppSessionStatus(
3703 OSRF_STATUS_BADREQUEST,
3704 "osrfMethodException",
3706 "No active transaction -- required for DELETE"
3712 // The following test is harmless but redundant. If a class is
3713 // readonly, we don't register a delete method for it.
3714 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
3715 osrfAppSessionStatus(
3717 OSRF_STATUS_BADREQUEST,
3718 "osrfMethodException",
3720 "Cannot DELETE readonly class"
3726 dbhandle = writehandle;
3730 char* pkey = osrfHashGet(meta, "primarykey");
3738 if (jsonObjectGetIndex(ctx->params, _obj_pos)->classname) {
3739 if (!verifyObjectClass(ctx, jsonObjectGetIndex( ctx->params, _obj_pos ))) {
3744 id = oilsFMGetString( jsonObjectGetIndex(ctx->params, _obj_pos), pkey );
3747 if (!verifyObjectPCRUD( ctx, NULL )) {
3752 id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, _obj_pos));
3757 "%s deleting %s object with %s = %s",
3759 osrfHashGet(meta, "fieldmapper"),
3764 obj = jsonNewObject(id);
3766 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
3767 dbi_conn_quote_string(writehandle, &id);
3769 dbi_result result = dbi_conn_queryf(writehandle, "DELETE FROM %s WHERE %s = %s;", osrfHashGet(meta, "tablename"), pkey, id);
3772 jsonObjectFree(obj);
3773 obj = jsonNewObject(NULL);
3776 "%s ERROR deleting %s object with %s = %s",
3778 osrfHashGet(meta, "fieldmapper"),
3791 static jsonObject* oilsMakeFieldmapperFromResult( dbi_result result, osrfHash* meta) {
3792 if(!(result && meta)) return jsonNULL;
3794 jsonObject* object = jsonNewObject(NULL);
3795 jsonObjectSetClass(object, osrfHashGet(meta, "classname"));
3797 osrfHash* fields = osrfHashGet(meta, "fields");
3799 osrfLogInternal(OSRF_LOG_MARK, "Setting object class to %s ", object->classname);
3803 char dt_string[256];
3807 int columnIndex = 1;
3809 unsigned short type;
3810 const char* columnName;
3812 /* cycle through the column list */
3813 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
3815 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
3817 fmIndex = -1; // reset the position
3819 /* determine the field type and storage attributes */
3820 type = dbi_result_get_field_type(result, columnName);
3821 attr = dbi_result_get_field_attribs(result, columnName);
3823 /* fetch the fieldmapper index */
3824 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
3826 if ( str_is_true( osrfHashGet(_f, "virtual") ) )
3829 const char* pos = (char*)osrfHashGet(_f, "array_position");
3830 if ( !pos ) continue;
3832 fmIndex = atoi( pos );
3833 osrfLogInternal(OSRF_LOG_MARK, "... Found column at position [%s]...", pos);
3838 if (dbi_result_field_is_null(result, columnName)) {
3839 jsonObjectSetIndex( object, fmIndex, jsonNewObject(NULL) );
3844 case DBI_TYPE_INTEGER :
3846 if( attr & DBI_INTEGER_SIZE8 )
3847 jsonObjectSetIndex( object, fmIndex,
3848 jsonNewNumberObject(dbi_result_get_longlong(result, columnName)));
3850 jsonObjectSetIndex( object, fmIndex,
3851 jsonNewNumberObject(dbi_result_get_int(result, columnName)));
3855 case DBI_TYPE_DECIMAL :
3856 jsonObjectSetIndex( object, fmIndex,
3857 jsonNewNumberObject(dbi_result_get_double(result, columnName)));
3860 case DBI_TYPE_STRING :
3866 jsonNewObject( dbi_result_get_string(result, columnName) )
3871 case DBI_TYPE_DATETIME :
3873 memset(dt_string, '\0', sizeof(dt_string));
3874 memset(&gmdt, '\0', sizeof(gmdt));
3876 _tmp_dt = dbi_result_get_datetime(result, columnName);
3879 if (!(attr & DBI_DATETIME_DATE)) {
3880 gmtime_r( &_tmp_dt, &gmdt );
3881 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
3882 } else if (!(attr & DBI_DATETIME_TIME)) {
3883 localtime_r( &_tmp_dt, &gmdt );
3884 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
3886 localtime_r( &_tmp_dt, &gmdt );
3887 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
3890 jsonObjectSetIndex( object, fmIndex, jsonNewObject(dt_string) );
3894 case DBI_TYPE_BINARY :
3895 osrfLogError( OSRF_LOG_MARK,
3896 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
3904 static jsonObject* oilsMakeJSONFromResult( dbi_result result ) {
3905 if(!result) return jsonNULL;
3907 jsonObject* object = jsonNewObject(NULL);
3910 char dt_string[256];
3914 int columnIndex = 1;
3916 unsigned short type;
3917 const char* columnName;
3919 /* cycle through the column list */
3920 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
3922 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
3924 fmIndex = -1; // reset the position
3926 /* determine the field type and storage attributes */
3927 type = dbi_result_get_field_type(result, columnName);
3928 attr = dbi_result_get_field_attribs(result, columnName);
3930 if (dbi_result_field_is_null(result, columnName)) {
3931 jsonObjectSetKey( object, columnName, jsonNewObject(NULL) );
3936 case DBI_TYPE_INTEGER :
3938 if( attr & DBI_INTEGER_SIZE8 )
3939 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_longlong(result, columnName)) );
3941 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_int(result, columnName)) );
3944 case DBI_TYPE_DECIMAL :
3945 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_double(result, columnName)) );
3948 case DBI_TYPE_STRING :
3949 jsonObjectSetKey( object, columnName, jsonNewObject(dbi_result_get_string(result, columnName)) );
3952 case DBI_TYPE_DATETIME :
3954 memset(dt_string, '\0', sizeof(dt_string));
3955 memset(&gmdt, '\0', sizeof(gmdt));
3957 _tmp_dt = dbi_result_get_datetime(result, columnName);
3960 if (!(attr & DBI_DATETIME_DATE)) {
3961 gmtime_r( &_tmp_dt, &gmdt );
3962 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
3963 } else if (!(attr & DBI_DATETIME_TIME)) {
3964 localtime_r( &_tmp_dt, &gmdt );
3965 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
3967 localtime_r( &_tmp_dt, &gmdt );
3968 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
3971 jsonObjectSetKey( object, columnName, jsonNewObject(dt_string) );
3974 case DBI_TYPE_BINARY :
3975 osrfLogError( OSRF_LOG_MARK,
3976 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
3984 // Interpret a string as true or false
3985 static int str_is_true( const char* str ) {
3986 if( NULL == str || strcasecmp( str, "true" ) )
3992 // Interpret a jsonObject as true or false
3993 static int obj_is_true( const jsonObject* obj ) {
3996 else switch( obj->type )
4004 if( strcasecmp( obj->value.s, "true" ) )
4008 case JSON_NUMBER : // Support 1/0 for perl's sake
4009 if( jsonObjectGetNumber( obj ) == 1.0 )