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* searchSimplePredicate ( const char* op, const char* class,
58 osrfHash* field, const jsonObject* node );
59 static char* searchFunctionPredicate ( const char*, osrfHash*, const jsonObject*, const char* );
60 static char* searchFieldTransform ( const char*, osrfHash*, const jsonObject*);
61 static char* searchFieldTransformPredicate ( const char*, osrfHash*, jsonObject*, const char* );
62 static char* searchBETWEENPredicate ( const char*, osrfHash*, jsonObject* );
63 static char* searchINPredicate ( const char*, osrfHash*,
64 jsonObject*, const char*, osrfMethodContext* );
65 static char* searchPredicate ( const char*, osrfHash*, jsonObject*, osrfMethodContext* );
66 static char* searchJOIN ( const jsonObject*, osrfHash* );
67 static char* searchWHERE ( const jsonObject*, osrfHash*, int, osrfMethodContext* );
68 static char* buildSELECT ( jsonObject*, jsonObject*, osrfHash*, osrfMethodContext* );
70 char* SELECT ( osrfMethodContext*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, int );
72 void userDataFree( void* );
73 static void sessionDataFree( char*, void* );
74 static char* getSourceDefinition( osrfHash* );
75 static int str_is_true( const char* str );
76 static int obj_is_true( const jsonObject* obj );
77 static const char* json_type( int code );
78 static const char* get_primitive( osrfHash* field );
79 static const char* get_datatype( osrfHash* field );
82 static jsonObject* verifyUserPCRUD( osrfMethodContext* );
83 static int verifyObjectPCRUD( osrfMethodContext*, const jsonObject* );
86 static int child_initialized = 0; /* boolean */
88 static dbi_conn writehandle; /* our MASTER db connection */
89 static dbi_conn dbhandle; /* our CURRENT db connection */
90 //static osrfHash * readHandles;
91 static jsonObject* jsonNULL = NULL; //
92 static int max_flesh_depth = 100;
94 /* called when this process is about to exit */
95 void osrfAppChildExit() {
96 osrfLogDebug(OSRF_LOG_MARK, "Child is exiting, disconnecting from database...");
99 if (writehandle == dbhandle) same = 1;
101 dbi_conn_query(writehandle, "ROLLBACK;");
102 dbi_conn_close(writehandle);
105 if (dbhandle && !same)
106 dbi_conn_close(dbhandle);
108 // XXX add cleanup of readHandles whenever that gets used
113 int osrfAppInitialize() {
115 osrfLogInfo(OSRF_LOG_MARK, "Initializing the CStore Server...");
116 osrfLogInfo(OSRF_LOG_MARK, "Finding XML file...");
118 if (!oilsIDLInit( osrf_settings_host_value("/IDL") )) return 1; /* return non-zero to indicate error */
120 growing_buffer* method_name = buffer_init(64);
122 // Generic search thingy
123 buffer_add(method_name, MODULENAME);
124 buffer_add(method_name, ".json_query");
125 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
126 "doJSONSearch", "", 1, OSRF_METHOD_STREAMING );
129 // first we register all the transaction and savepoint methods
130 buffer_reset(method_name);
131 OSRF_BUFFER_ADD(method_name, MODULENAME);
132 OSRF_BUFFER_ADD(method_name, ".transaction.begin");
133 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
134 "beginTransaction", "", 0, 0 );
136 buffer_reset(method_name);
137 OSRF_BUFFER_ADD(method_name, MODULENAME);
138 OSRF_BUFFER_ADD(method_name, ".transaction.commit");
139 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
140 "commitTransaction", "", 0, 0 );
142 buffer_reset(method_name);
143 OSRF_BUFFER_ADD(method_name, MODULENAME);
144 OSRF_BUFFER_ADD(method_name, ".transaction.rollback");
145 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
146 "rollbackTransaction", "", 0, 0 );
148 buffer_reset(method_name);
149 OSRF_BUFFER_ADD(method_name, MODULENAME);
150 OSRF_BUFFER_ADD(method_name, ".savepoint.set");
151 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
152 "setSavepoint", "", 1, 0 );
154 buffer_reset(method_name);
155 OSRF_BUFFER_ADD(method_name, MODULENAME);
156 OSRF_BUFFER_ADD(method_name, ".savepoint.release");
157 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
158 "releaseSavepoint", "", 1, 0 );
160 buffer_reset(method_name);
161 OSRF_BUFFER_ADD(method_name, MODULENAME);
162 OSRF_BUFFER_ADD(method_name, ".savepoint.rollback");
163 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
164 "rollbackSavepoint", "", 1, 0 );
166 buffer_free(method_name);
168 static const char* global_method[] = {
176 const int global_method_count
177 = sizeof( global_method ) / sizeof ( global_method[0] );
181 osrfStringArray* classes = osrfHashKeys( oilsIDL() );
182 osrfLogDebug(OSRF_LOG_MARK, "%d classes loaded", classes->size );
183 osrfLogDebug(OSRF_LOG_MARK,
184 "At least %d methods will be generated", classes->size * global_method_count);
186 while ( (classname = osrfStringArrayGetString(classes, c_index++)) ) {
187 osrfLogInfo(OSRF_LOG_MARK, "Generating class methods for %s", classname);
189 osrfHash* idlClass = osrfHashGet(oilsIDL(), classname);
191 if (!osrfStringArrayContains( osrfHashGet(idlClass, "controller"), MODULENAME )) {
192 osrfLogInfo(OSRF_LOG_MARK, "%s is not listed as a controller for %s, moving on", MODULENAME, classname);
196 if ( str_is_true( osrfHashGet(idlClass, "virtual") ) ) {
197 osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
201 // Look up some other attributes of the current class
202 const char* idlClass_fieldmapper = osrfHashGet(idlClass, "fieldmapper");
203 const char* readonly = osrfHashGet(idlClass, "readonly");
205 osrfHash* idlClass_permacrud = osrfHashGet(idlClass, "permacrud");
209 for( i = 0; i < global_method_count; ++i ) {
210 const char* method_type = global_method[ i ];
211 osrfLogDebug(OSRF_LOG_MARK,
212 "Using files to build %s class methods for %s", method_type, classname);
214 if (!idlClass_fieldmapper) continue;
217 if (!idlClass_permacrud) continue;
219 const char* tmp_method = method_type;
220 if ( *tmp_method == 'i' || *tmp_method == 's') {
221 tmp_method = "retrieve";
223 if (!osrfHashGet( idlClass_permacrud, tmp_method )) continue;
226 if ( str_is_true( readonly ) &&
227 ( *method_type == 'c' || *method_type == 'u' || *method_type == 'd')
230 osrfHash* method_meta = osrfNewHash();
231 osrfHashSet(method_meta, idlClass, "class");
233 method_name = buffer_init(64);
235 buffer_fadd(method_name, "%s.%s.%s", MODULENAME, method_type, classname);
239 char* _fm = strdup( idlClass_fieldmapper );
240 part = strtok_r(_fm, ":", &st_tmp);
242 buffer_fadd(method_name, "%s.direct.%s", MODULENAME, part);
244 while ((part = strtok_r(NULL, ":", &st_tmp))) {
245 OSRF_BUFFER_ADD_CHAR(method_name, '.');
246 OSRF_BUFFER_ADD(method_name, part);
248 OSRF_BUFFER_ADD_CHAR(method_name, '.');
249 OSRF_BUFFER_ADD(method_name, method_type);
253 char* method = buffer_release(method_name);
255 osrfHashSet( method_meta, method, "methodname" );
256 osrfHashSet( method_meta, strdup(method_type), "methodtype" );
259 if (*method_type == 'i' || *method_type == 's') {
260 flags = flags | OSRF_METHOD_STREAMING;
263 osrfAppRegisterExtendedMethod(
266 "dispatchCRUDMethod",
280 static char* getSourceDefinition( osrfHash* class ) {
282 char* tabledef = osrfHashGet(class, "tablename");
285 tabledef = strdup(tabledef);
287 tabledef = osrfHashGet(class, "source_definition");
289 growing_buffer* tablebuf = buffer_init(128);
290 buffer_fadd( tablebuf, "(%s)", tabledef );
291 tabledef = buffer_release(tablebuf);
293 const char* classname = osrfHashGet( class, "classname" );
298 "%s ERROR No tablename or source_definition for class \"%s\"",
309 * Connects to the database
311 int osrfAppChildInit() {
313 osrfLogDebug(OSRF_LOG_MARK, "Attempting to initialize libdbi...");
314 dbi_initialize(NULL);
315 osrfLogDebug(OSRF_LOG_MARK, "... libdbi initialized.");
317 char* driver = osrf_settings_host_value("/apps/%s/app_settings/driver", MODULENAME);
318 char* user = osrf_settings_host_value("/apps/%s/app_settings/database/user", MODULENAME);
319 char* host = osrf_settings_host_value("/apps/%s/app_settings/database/host", MODULENAME);
320 char* port = osrf_settings_host_value("/apps/%s/app_settings/database/port", MODULENAME);
321 char* db = osrf_settings_host_value("/apps/%s/app_settings/database/db", MODULENAME);
322 char* pw = osrf_settings_host_value("/apps/%s/app_settings/database/pw", MODULENAME);
323 char* md = osrf_settings_host_value("/apps/%s/app_settings/max_query_recursion", MODULENAME);
325 osrfLogDebug(OSRF_LOG_MARK, "Attempting to load the database driver [%s]...", driver);
326 writehandle = dbi_conn_new(driver);
329 osrfLogError(OSRF_LOG_MARK, "Error loading database driver [%s]", driver);
332 osrfLogDebug(OSRF_LOG_MARK, "Database driver [%s] seems OK", driver);
334 osrfLogInfo(OSRF_LOG_MARK, "%s connecting to database. host=%s, "
335 "port=%s, user=%s, pw=%s, db=%s", MODULENAME, host, port, user, pw, db );
337 if(host) dbi_conn_set_option(writehandle, "host", host );
338 if(port) dbi_conn_set_option_numeric( writehandle, "port", atoi(port) );
339 if(user) dbi_conn_set_option(writehandle, "username", user);
340 if(pw) dbi_conn_set_option(writehandle, "password", pw );
341 if(db) dbi_conn_set_option(writehandle, "dbname", db );
343 if(md) max_flesh_depth = atoi(md);
344 if(max_flesh_depth < 0) max_flesh_depth = 1;
345 if(max_flesh_depth > 1000) max_flesh_depth = 1000;
354 if (dbi_conn_connect(writehandle) < 0) {
356 if (dbi_conn_connect(writehandle) < 0) {
357 dbi_conn_error(writehandle, &err);
358 osrfLogError( OSRF_LOG_MARK, "Error connecting to database: %s", err);
363 osrfLogInfo(OSRF_LOG_MARK, "%s successfully connected to the database", MODULENAME);
369 osrfStringArray* classes = osrfHashKeys( oilsIDL() );
371 while ( (classname = osrfStringArrayGetString(classes, i++)) ) {
372 osrfHash* class = osrfHashGet( oilsIDL(), classname );
373 osrfHash* fields = osrfHashGet( class, "fields" );
375 if( str_is_true( osrfHashGet(class, "virtual") ) ) {
376 osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
380 char* tabledef = getSourceDefinition(class);
382 tabledef = strdup( "(null)" );
384 growing_buffer* sql_buf = buffer_init(32);
385 buffer_fadd( sql_buf, "SELECT * FROM %s AS x WHERE 1=0;", tabledef );
389 char* sql = buffer_release(sql_buf);
390 osrfLogDebug(OSRF_LOG_MARK, "%s Investigatory SQL = %s", MODULENAME, sql);
392 dbi_result result = dbi_conn_query(writehandle, sql);
398 const char* columnName;
400 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
402 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
404 /* fetch the fieldmapper index */
405 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
407 osrfLogDebug(OSRF_LOG_MARK, "Found [%s] in IDL hash...", (char*)columnName);
409 /* determine the field type and storage attributes */
410 type = dbi_result_get_field_type(result, columnName);
411 attr = dbi_result_get_field_attribs(result, columnName);
415 case DBI_TYPE_INTEGER :
417 if ( !osrfHashGet(_f, "primitive") )
418 osrfHashSet(_f,"number", "primitive");
420 if( attr & DBI_INTEGER_SIZE8 )
421 osrfHashSet(_f,"INT8", "datatype");
423 osrfHashSet(_f,"INT", "datatype");
426 case DBI_TYPE_DECIMAL :
427 if ( !osrfHashGet(_f, "primitive") )
428 osrfHashSet(_f,"number", "primitive");
430 osrfHashSet(_f,"NUMERIC", "datatype");
433 case DBI_TYPE_STRING :
434 if ( !osrfHashGet(_f, "primitive") )
435 osrfHashSet(_f,"string", "primitive");
436 osrfHashSet(_f,"TEXT", "datatype");
439 case DBI_TYPE_DATETIME :
440 if ( !osrfHashGet(_f, "primitive") )
441 osrfHashSet(_f,"string", "primitive");
443 osrfHashSet(_f,"TIMESTAMP", "datatype");
446 case DBI_TYPE_BINARY :
447 if ( !osrfHashGet(_f, "primitive") )
448 osrfHashSet(_f,"string", "primitive");
450 osrfHashSet(_f,"BYTEA", "datatype");
455 "Setting [%s] to primitive [%s] and datatype [%s]...",
457 osrfHashGet(_f, "primitive"),
458 osrfHashGet(_f, "datatype")
462 dbi_result_free(result);
464 osrfLogDebug(OSRF_LOG_MARK, "No data found for class [%s]...", (char*)classname);
468 osrfStringArrayFree(classes);
470 child_initialized = 1;
475 This function is a sleazy hack intended *only* for testing and
476 debugging. Any real server process should initialize the
477 database connection by calling osrfAppChildInit().
479 void set_cstore_dbi_conn( dbi_conn conn ) {
480 dbhandle = writehandle = conn;
483 void userDataFree( void* blob ) {
484 osrfHashFree( (osrfHash*)blob );
488 static void sessionDataFree( char* key, void* item ) {
489 if (!(strcmp(key,"xact_id"))) {
491 dbi_conn_query(writehandle, "ROLLBACK;");
498 int beginTransaction ( osrfMethodContext* ctx ) {
499 if(osrfMethodVerifyContext( ctx )) {
500 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
505 jsonObject* user = verifyUserPCRUD( ctx );
506 if (!user) return -1;
507 jsonObjectFree(user);
510 dbi_result result = dbi_conn_query(writehandle, "START TRANSACTION;");
512 osrfLogError(OSRF_LOG_MARK, "%s: Error starting transaction", MODULENAME );
513 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error starting transaction" );
516 jsonObject* ret = jsonNewObject(ctx->session->session_id);
517 osrfAppRespondComplete( ctx, ret );
520 if (!ctx->session->userData) {
521 ctx->session->userData = osrfNewHash();
522 osrfHashSetCallback((osrfHash*)ctx->session->userData, &sessionDataFree);
525 osrfHashSet( (osrfHash*)ctx->session->userData, strdup( ctx->session->session_id ), "xact_id" );
526 ctx->session->userDataFree = &userDataFree;
532 int setSavepoint ( osrfMethodContext* ctx ) {
533 if(osrfMethodVerifyContext( ctx )) {
534 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
541 jsonObject* user = verifyUserPCRUD( ctx );
542 if (!user) return -1;
543 jsonObjectFree(user);
546 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
547 osrfAppSessionStatus(
549 OSRF_STATUS_INTERNALSERVERERROR,
550 "osrfMethodException",
552 "No active transaction -- required for savepoints"
557 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
559 dbi_result result = dbi_conn_queryf(writehandle, "SAVEPOINT \"%s\";", spName);
563 "%s: Error creating savepoint %s in transaction %s",
566 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
568 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error creating savepoint" );
572 jsonObject* ret = jsonNewObject(spName);
573 osrfAppRespondComplete( ctx, ret );
580 int releaseSavepoint ( osrfMethodContext* ctx ) {
581 if(osrfMethodVerifyContext( ctx )) {
582 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
589 jsonObject* user = verifyUserPCRUD( ctx );
590 if (!user) return -1;
591 jsonObjectFree(user);
594 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
595 osrfAppSessionStatus(
597 OSRF_STATUS_INTERNALSERVERERROR,
598 "osrfMethodException",
600 "No active transaction -- required for savepoints"
605 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
607 dbi_result result = dbi_conn_queryf(writehandle, "RELEASE SAVEPOINT \"%s\";", spName);
611 "%s: Error releasing savepoint %s in transaction %s",
614 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
616 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error releasing savepoint" );
620 jsonObject* ret = jsonNewObject(spName);
621 osrfAppRespondComplete( ctx, ret );
628 int rollbackSavepoint ( osrfMethodContext* ctx ) {
629 if(osrfMethodVerifyContext( ctx )) {
630 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
637 jsonObject* user = verifyUserPCRUD( ctx );
638 if (!user) return -1;
639 jsonObjectFree(user);
642 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
643 osrfAppSessionStatus(
645 OSRF_STATUS_INTERNALSERVERERROR,
646 "osrfMethodException",
648 "No active transaction -- required for savepoints"
653 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
655 dbi_result result = dbi_conn_queryf(writehandle, "ROLLBACK TO SAVEPOINT \"%s\";", spName);
659 "%s: Error rolling back savepoint %s in transaction %s",
662 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
664 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back savepoint" );
668 jsonObject* ret = jsonNewObject(spName);
669 osrfAppRespondComplete( ctx, ret );
676 int commitTransaction ( osrfMethodContext* ctx ) {
677 if(osrfMethodVerifyContext( ctx )) {
678 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
683 jsonObject* user = verifyUserPCRUD( ctx );
684 if (!user) return -1;
685 jsonObjectFree(user);
688 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
689 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to commit" );
693 dbi_result result = dbi_conn_query(writehandle, "COMMIT;");
695 osrfLogError(OSRF_LOG_MARK, "%s: Error committing transaction", MODULENAME );
696 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error committing transaction" );
699 osrfHashRemove(ctx->session->userData, "xact_id");
700 jsonObject* ret = jsonNewObject(ctx->session->session_id);
701 osrfAppRespondComplete( ctx, ret );
707 int rollbackTransaction ( osrfMethodContext* ctx ) {
708 if(osrfMethodVerifyContext( ctx )) {
709 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
714 jsonObject* user = verifyUserPCRUD( ctx );
715 if (!user) return -1;
716 jsonObjectFree(user);
719 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
720 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to roll back" );
724 dbi_result result = dbi_conn_query(writehandle, "ROLLBACK;");
726 osrfLogError(OSRF_LOG_MARK, "%s: Error rolling back transaction", MODULENAME );
727 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back transaction" );
730 osrfHashRemove(ctx->session->userData, "xact_id");
731 jsonObject* ret = jsonNewObject(ctx->session->session_id);
732 osrfAppRespondComplete( ctx, ret );
738 int dispatchCRUDMethod ( osrfMethodContext* ctx ) {
739 if(osrfMethodVerifyContext( ctx )) {
740 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
744 osrfHash* meta = (osrfHash*) ctx->method->userData;
745 osrfHash* class_obj = osrfHashGet( meta, "class" );
749 const char* methodtype = osrfHashGet(meta, "methodtype");
750 jsonObject * obj = NULL;
752 if (!strcmp(methodtype, "create")) {
753 obj = doCreate(ctx, &err);
754 osrfAppRespondComplete( ctx, obj );
756 else if (!strcmp(methodtype, "retrieve")) {
757 obj = doRetrieve(ctx, &err);
758 osrfAppRespondComplete( ctx, obj );
760 else if (!strcmp(methodtype, "update")) {
761 obj = doUpdate(ctx, &err);
762 osrfAppRespondComplete( ctx, obj );
764 else if (!strcmp(methodtype, "delete")) {
765 obj = doDelete(ctx, &err);
766 osrfAppRespondComplete( ctx, obj );
768 else if (!strcmp(methodtype, "search")) {
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 obj = doFieldmapperSearch(ctx, class_obj, _p, &err);
784 jsonIterator* itr = jsonNewIterator( obj );
785 while ((cur = jsonIteratorNext( itr ))) {
787 if(!verifyObjectPCRUD(ctx, cur)) continue;
789 osrfAppRespond( ctx, cur );
791 jsonIteratorFree(itr);
792 osrfAppRespondComplete( ctx, NULL );
794 } else if (!strcmp(methodtype, "id_list")) {
796 jsonObject* _p = jsonObjectClone( ctx->params );
799 _p = jsonParseString("[]");
800 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 1)));
801 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 2)));
804 if (jsonObjectGetIndex( _p, 1 )) {
805 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "select" );
806 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "no_i18n" );
807 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh" );
808 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh_columns" );
810 jsonObjectSetIndex( _p, 1, jsonNewObjectType(JSON_HASH) );
813 jsonObjectSetKey( jsonObjectGetIndex( _p, 1 ), "no_i18n", jsonNewBoolObject( 1 ) );
816 jsonObjectGetIndex( _p, 1 ),
819 "{ \"%s\":[\"%s\"] }",
820 osrfHashGet( class_obj, "classname" ),
821 osrfHashGet( class_obj, "primarykey" )
825 obj = doFieldmapperSearch(ctx, class_obj, _p, &err);
831 jsonIterator* itr = jsonNewIterator( obj );
832 while ((cur = jsonIteratorNext( itr ))) {
834 if(!verifyObjectPCRUD(ctx, cur)) continue;
838 oilsFMGetObject( cur, osrfHashGet( class_obj, "primarykey" ) )
841 jsonIteratorFree(itr);
842 osrfAppRespondComplete( ctx, NULL );
845 osrfAppRespondComplete( ctx, obj );
853 static int verifyObjectClass ( osrfMethodContext* ctx, const jsonObject* param ) {
856 osrfHash* meta = (osrfHash*) ctx->method->userData;
857 osrfHash* class = osrfHashGet( meta, "class" );
859 if (!param->classname || (strcmp( osrfHashGet(class, "classname"), param->classname ))) {
861 growing_buffer* msg = buffer_init(128);
864 "%s: %s method for type %s was passed a %s",
866 osrfHashGet(meta, "methodtype"),
867 osrfHashGet(class, "classname"),
871 char* m = buffer_release(msg);
872 osrfAppSessionStatus( ctx->session, OSRF_STATUS_BADREQUEST, "osrfMethodException", ctx->request, m );
880 ret = verifyObjectPCRUD( ctx, param );
888 static jsonObject* verifyUserPCRUD( osrfMethodContext* ctx ) {
889 char* auth = jsonObjectToSimpleString( jsonObjectGetIndex( ctx->params, 0 ) );
890 jsonObject* auth_object = jsonNewObject(auth);
891 jsonObject* user = oilsUtilsQuickReq("open-ils.auth","open-ils.auth.session.retrieve", auth_object);
892 jsonObjectFree(auth_object);
894 if (!user->classname || strcmp(user->classname, "au")) {
896 growing_buffer* msg = buffer_init(128);
899 "%s: permacrud received a bad auth token: %s",
904 char* m = buffer_release(msg);
905 osrfAppSessionStatus( ctx->session, OSRF_STATUS_UNAUTHORIZED, "osrfMethodException", ctx->request, m );
908 jsonObjectFree(user);
917 static int verifyObjectPCRUD ( osrfMethodContext* ctx, const jsonObject* obj ) {
919 dbhandle = writehandle;
921 osrfHash* meta = (osrfHash*) ctx->method->userData;
922 osrfHash* class = osrfHashGet( meta, "class" );
923 char* method_type = strdup( osrfHashGet(meta, "methodtype") );
926 if ( ( *method_type == 's' || *method_type == 'i' ) ) {
928 method_type = strdup("retrieve"); // search and id_list are equivelant to retrieve for this
929 } else if ( *method_type == 'u' || *method_type == 'd' ) {
930 fetch = 1; // MUST go to the db for the object for update and delete
933 osrfHash* pcrud = osrfHashGet( osrfHashGet(class, "permacrud"), method_type );
937 // No permacrud for this method type on this class
939 growing_buffer* msg = buffer_init(128);
942 "%s: %s on class %s has no permacrud IDL entry",
944 osrfHashGet(meta, "methodtype"),
945 osrfHashGet(class, "classname")
948 char* m = buffer_release(msg);
949 osrfAppSessionStatus( ctx->session, OSRF_STATUS_FORBIDDEN, "osrfMethodException", ctx->request, m );
956 jsonObject* user = verifyUserPCRUD( ctx );
959 int userid = atoi( oilsFMGetString( user, "id" ) );
960 jsonObjectFree(user);
962 osrfStringArray* permission = osrfHashGet(pcrud, "permission");
963 osrfStringArray* local_context = osrfHashGet(pcrud, "local_context");
964 osrfHash* foreign_context = osrfHashGet(pcrud, "foreign_context");
966 osrfStringArray* context_org_array = osrfNewStringArray(1);
969 char* pkey_value = NULL;
970 if ( str_is_true( osrfHashGet(pcrud, "global_required") ) ) {
971 osrfLogDebug( OSRF_LOG_MARK, "global-level permissions required, fetching top of the org tree" );
973 // check for perm at top of org tree
974 jsonObject* _tmp_params = jsonParseString("[{\"parent_ou\":null}]");
975 jsonObject* _list = doFieldmapperSearch(ctx, osrfHashGet( oilsIDL(), "aou" ), _tmp_params, &err);
977 jsonObject* _tree_top = jsonObjectGetIndex(_list, 0);
980 jsonObjectFree(_tmp_params);
981 jsonObjectFree(_list);
983 growing_buffer* msg = buffer_init(128);
984 OSRF_BUFFER_ADD( msg, MODULENAME );
985 OSRF_BUFFER_ADD( msg,
986 ": Internal error, could not find the top of the org tree (parent_ou = NULL)" );
988 char* m = buffer_release(msg);
989 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, m );
995 osrfStringArrayAdd( context_org_array, oilsFMGetString( _tree_top, "id" ) );
996 osrfLogDebug( OSRF_LOG_MARK, "top of the org tree is %s", osrfStringArrayGetString(context_org_array, 0) );
998 jsonObjectFree(_tmp_params);
999 jsonObjectFree(_list);
1002 osrfLogDebug( OSRF_LOG_MARK, "global-level permissions not required, fetching context org ids" );
1003 char* pkey = osrfHashGet(class, "primarykey");
1004 jsonObject *param = NULL;
1006 if (obj->classname) {
1007 pkey_value = oilsFMGetString( obj, pkey );
1008 if (!fetch) param = jsonObjectClone(obj);
1009 osrfLogDebug( OSRF_LOG_MARK, "Object supplied, using primary key value of %s", pkey_value );
1011 pkey_value = jsonObjectToSimpleString( obj );
1013 osrfLogDebug( OSRF_LOG_MARK, "Object not supplied, using primary key value of %s and retrieving from the database", pkey_value );
1017 jsonObject* _tmp_params = jsonParseStringFmt("[{\"%s\":\"%s\"}]", pkey, pkey_value);
1018 jsonObject* _list = doFieldmapperSearch(
1025 param = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1027 jsonObjectFree(_tmp_params);
1028 jsonObjectFree(_list);
1032 osrfLogDebug( OSRF_LOG_MARK, "Object not found in the database with primary key %s of %s", pkey, pkey_value );
1034 growing_buffer* msg = buffer_init(128);
1037 "%s: no object found with primary key %s of %s",
1043 char* m = buffer_release(msg);
1044 osrfAppSessionStatus(
1046 OSRF_STATUS_INTERNALSERVERERROR,
1047 "osrfMethodException",
1053 if (pkey_value) free(pkey_value);
1058 if (local_context->size > 0) {
1059 osrfLogDebug( OSRF_LOG_MARK, "%d class-local context field(s) specified", local_context->size);
1061 char* lcontext = NULL;
1062 while ( (lcontext = osrfStringArrayGetString(local_context, i++)) ) {
1063 osrfStringArrayAdd( context_org_array, oilsFMGetString( param, lcontext ) );
1066 "adding class-local field %s (value: %s) to the context org list",
1068 osrfStringArrayGetString(context_org_array, context_org_array->size - 1)
1073 osrfStringArray* class_list;
1075 if (foreign_context) {
1076 class_list = osrfHashKeys( foreign_context );
1077 osrfLogDebug( OSRF_LOG_MARK, "%d foreign context classes(s) specified", class_list->size);
1079 if (class_list->size > 0) {
1082 char* class_name = NULL;
1083 while ( (class_name = osrfStringArrayGetString(class_list, i++)) ) {
1084 osrfHash* fcontext = osrfHashGet(foreign_context, class_name);
1088 "%d foreign context fields(s) specified for class %s",
1089 ((osrfStringArray*)osrfHashGet(fcontext,"context"))->size,
1093 char* foreign_pkey = osrfHashGet(fcontext, "field");
1094 char* foreign_pkey_value = oilsFMGetString(param, osrfHashGet(fcontext, "fkey"));
1096 jsonObject* _tmp_params = jsonParseStringFmt(
1097 "[{\"%s\":\"%s\"}]",
1102 jsonObject* _list = doFieldmapperSearch(
1104 osrfHashGet( oilsIDL(), class_name ),
1109 jsonObject* _fparam = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1110 jsonObjectFree(_tmp_params);
1111 jsonObjectFree(_list);
1113 osrfStringArray* jump_list = osrfHashGet(fcontext, "jump");
1115 if (_fparam && jump_list) {
1118 while ( (flink = osrfStringArrayGetString(jump_list, k++)) && _fparam ) {
1119 free(foreign_pkey_value);
1121 osrfHash* foreign_link_hash = oilsIDLFindPath( "/%s/links/%s", _fparam->classname, flink );
1123 foreign_pkey_value = oilsFMGetString(_fparam, flink);
1124 foreign_pkey = osrfHashGet( foreign_link_hash, "key" );
1126 _tmp_params = jsonParseStringFmt(
1127 "[{\"%s\":\"%s\"}]",
1132 _list = doFieldmapperSearch(
1134 osrfHashGet( oilsIDL(), osrfHashGet( foreign_link_hash, "class" ) ),
1139 _fparam = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1140 jsonObjectFree(_tmp_params);
1141 jsonObjectFree(_list);
1148 growing_buffer* msg = buffer_init(128);
1151 "%s: no object found with primary key %s of %s",
1157 char* m = buffer_release(msg);
1158 osrfAppSessionStatus(
1160 OSRF_STATUS_INTERNALSERVERERROR,
1161 "osrfMethodException",
1167 osrfStringArrayFree(class_list);
1168 free(foreign_pkey_value);
1169 jsonObjectFree(param);
1174 free(foreign_pkey_value);
1177 char* foreign_field = NULL;
1178 while ( (foreign_field = osrfStringArrayGetString(osrfHashGet(fcontext,"context"), j++)) ) {
1179 osrfStringArrayAdd( context_org_array, oilsFMGetString( _fparam, foreign_field ) );
1182 "adding foreign class %s field %s (value: %s) to the context org list",
1185 osrfStringArrayGetString(context_org_array, context_org_array->size - 1)
1189 jsonObjectFree(_fparam);
1192 osrfStringArrayFree(class_list);
1196 jsonObjectFree(param);
1199 char* context_org = NULL;
1203 if (permission->size == 0) {
1204 osrfLogDebug( OSRF_LOG_MARK, "No permission specified for this action, passing through" );
1209 while ( (perm = osrfStringArrayGetString(permission, i++)) ) {
1211 while ( (context_org = osrfStringArrayGetString(context_org_array, j++)) ) {
1217 "Checking object permission [%s] for user %d on object %s (class %s) at org %d",
1221 osrfHashGet(class, "classname"),
1225 result = dbi_conn_queryf(
1227 "SELECT permission.usr_has_object_perm(%d, '%s', '%s', '%s', %d) AS has_perm;",
1230 osrfHashGet(class, "classname"),
1238 "Recieved a result for object permission [%s] for user %d on object %s (class %s) at org %d",
1242 osrfHashGet(class, "classname"),
1246 if (dbi_result_first_row(result)) {
1247 jsonObject* return_val = oilsMakeJSONFromResult( result );
1248 char* has_perm = jsonObjectToSimpleString( jsonObjectGetKeyConst(return_val, "has_perm") );
1252 "Status of object permission [%s] for user %d on object %s (class %s) at org %d is %s",
1256 osrfHashGet(class, "classname"),
1261 if ( *has_perm == 't' ) OK = 1;
1263 jsonObjectFree(return_val);
1266 dbi_result_free(result);
1271 osrfLogDebug( OSRF_LOG_MARK, "Checking non-object permission [%s] for user %d at org %d", perm, userid, atoi(context_org) );
1272 result = dbi_conn_queryf(
1274 "SELECT permission.usr_has_perm(%d, '%s', %d) AS has_perm;",
1281 osrfLogDebug( OSRF_LOG_MARK, "Received a result for permission [%s] for user %d at org %d", perm, userid, atoi(context_org) );
1282 if (dbi_result_first_row(result)) {
1283 jsonObject* return_val = oilsMakeJSONFromResult( result );
1284 char* has_perm = jsonObjectToSimpleString( jsonObjectGetKeyConst(return_val, "has_perm") );
1285 osrfLogDebug( OSRF_LOG_MARK, "Status of permission [%s] for user %d at org %d is [%s]", perm, userid, atoi(context_org), has_perm );
1286 if ( *has_perm == 't' ) OK = 1;
1288 jsonObjectFree(return_val);
1291 dbi_result_free(result);
1299 if (pkey_value) free(pkey_value);
1300 osrfStringArrayFree(context_org_array);
1307 static jsonObject* doCreate(osrfMethodContext* ctx, int* err ) {
1309 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1311 jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
1312 jsonObject* options = jsonObjectGetIndex( ctx->params, 2 );
1314 jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
1315 jsonObject* options = jsonObjectGetIndex( ctx->params, 1 );
1318 if (!verifyObjectClass(ctx, target)) {
1323 osrfLogDebug( OSRF_LOG_MARK, "Object seems to be of the correct type" );
1325 char* trans_id = NULL;
1326 if( ctx->session && ctx->session->userData )
1327 trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
1330 osrfLogError( OSRF_LOG_MARK, "No active transaction -- required for CREATE" );
1332 osrfAppSessionStatus(
1334 OSRF_STATUS_BADREQUEST,
1335 "osrfMethodException",
1337 "No active transaction -- required for CREATE"
1343 // The following test is harmless but redundant. If a class is
1344 // readonly, we don't register a create method for it.
1345 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
1346 osrfAppSessionStatus(
1348 OSRF_STATUS_BADREQUEST,
1349 "osrfMethodException",
1351 "Cannot INSERT readonly class"
1357 // Set the last_xact_id
1358 int index = oilsIDL_ntop( target->classname, "last_xact_id" );
1360 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
1361 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
1364 osrfLogDebug( OSRF_LOG_MARK, "There is a transaction running..." );
1366 dbhandle = writehandle;
1368 osrfHash* fields = osrfHashGet(meta, "fields");
1369 char* pkey = osrfHashGet(meta, "primarykey");
1370 char* seq = osrfHashGet(meta, "sequence");
1372 growing_buffer* table_buf = buffer_init(128);
1373 growing_buffer* col_buf = buffer_init(128);
1374 growing_buffer* val_buf = buffer_init(128);
1376 OSRF_BUFFER_ADD(table_buf, "INSERT INTO ");
1377 OSRF_BUFFER_ADD(table_buf, osrfHashGet(meta, "tablename"));
1378 OSRF_BUFFER_ADD_CHAR( col_buf, '(' );
1379 buffer_add(val_buf,"VALUES (");
1385 osrfStringArray* field_list = osrfHashKeys( fields );
1386 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
1388 osrfHash* field = osrfHashGet( fields, field_name );
1390 if( str_is_true( osrfHashGet( field, "virtual" ) ) )
1393 const jsonObject* field_object = oilsFMGetObject( target, field_name );
1396 if (field_object && field_object->classname) {
1397 value = oilsFMGetString(
1399 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
1402 value = jsonObjectToSimpleString( field_object );
1409 OSRF_BUFFER_ADD_CHAR( col_buf, ',' );
1410 OSRF_BUFFER_ADD_CHAR( val_buf, ',' );
1413 buffer_add(col_buf, field_name);
1415 if (!field_object || field_object->type == JSON_NULL) {
1416 buffer_add( val_buf, "DEFAULT" );
1418 } else if ( !strcmp(get_primitive( field ), "number") ) {
1419 const char* numtype = get_datatype( field );
1420 if ( !strcmp( numtype, "INT8") ) {
1421 buffer_fadd( val_buf, "%lld", atoll(value) );
1423 } else if ( !strcmp( numtype, "INT") ) {
1424 buffer_fadd( val_buf, "%d", atoi(value) );
1426 } else if ( !strcmp( numtype, "NUMERIC") ) {
1427 buffer_fadd( val_buf, "%f", atof(value) );
1430 if ( dbi_conn_quote_string(writehandle, &value) ) {
1431 OSRF_BUFFER_ADD( val_buf, value );
1434 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
1435 osrfAppSessionStatus(
1437 OSRF_STATUS_INTERNALSERVERERROR,
1438 "osrfMethodException",
1440 "Error quoting string -- please see the error log for more details"
1443 buffer_free(table_buf);
1444 buffer_free(col_buf);
1445 buffer_free(val_buf);
1456 OSRF_BUFFER_ADD_CHAR( col_buf, ')' );
1457 OSRF_BUFFER_ADD_CHAR( val_buf, ')' );
1459 char* table_str = buffer_release(table_buf);
1460 char* col_str = buffer_release(col_buf);
1461 char* val_str = buffer_release(val_buf);
1462 growing_buffer* sql = buffer_init(128);
1463 buffer_fadd( sql, "%s %s %s;", table_str, col_str, val_str );
1468 char* query = buffer_release(sql);
1470 osrfLogDebug(OSRF_LOG_MARK, "%s: Insert SQL [%s]", MODULENAME, query);
1473 dbi_result result = dbi_conn_query(writehandle, query);
1475 jsonObject* obj = NULL;
1478 obj = jsonNewObject(NULL);
1481 "%s ERROR inserting %s object using query [%s]",
1483 osrfHashGet(meta, "fieldmapper"),
1486 osrfAppSessionStatus(
1488 OSRF_STATUS_INTERNALSERVERERROR,
1489 "osrfMethodException",
1491 "INSERT error -- please see the error log for more details"
1496 char* id = oilsFMGetString(target, pkey);
1498 unsigned long long new_id = dbi_conn_sequence_last(writehandle, seq);
1499 growing_buffer* _id = buffer_init(10);
1500 buffer_fadd(_id, "%lld", new_id);
1501 id = buffer_release(_id);
1504 // Find quietness specification, if present
1505 char* quiet_str = NULL;
1507 const jsonObject* quiet_obj = jsonObjectGetKeyConst( options, "quiet" );
1509 quiet_str = jsonObjectToSimpleString( quiet_obj );
1512 if( str_is_true( quiet_str ) ) { // if quietness is specified
1513 obj = jsonNewObject(id);
1517 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
1518 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH));
1521 jsonObjectGetIndex(fake_params, 0),
1526 jsonObject* list = doFieldmapperSearch( ctx,meta, fake_params, err);
1529 jsonObjectFree( fake_params );
1532 obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
1535 jsonObjectFree( list );
1536 jsonObjectFree( fake_params );
1539 if(quiet_str) free(quiet_str);
1550 static jsonObject* doRetrieve(osrfMethodContext* ctx, int* err ) {
1560 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1562 char* id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, id_pos));
1563 jsonObject* order_hash = jsonObjectGetIndex(ctx->params, order_pos);
1567 "%s retrieving %s object with primary key value of %s",
1569 osrfHashGet(meta, "fieldmapper"),
1574 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
1575 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH));
1578 jsonObjectGetIndex(fake_params, 0),
1579 osrfHashGet(meta, "primarykey"),
1580 jsonObjectClone(jsonObjectGetIndex(ctx->params, id_pos))
1584 if (order_hash) jsonObjectPush(fake_params, jsonObjectClone(order_hash) );
1586 jsonObject* list = doFieldmapperSearch( ctx,meta, fake_params, err);
1589 jsonObjectFree( fake_params );
1593 jsonObject* obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
1595 jsonObjectFree( list );
1596 jsonObjectFree( fake_params );
1599 if(!verifyObjectPCRUD(ctx, obj)) {
1600 jsonObjectFree(obj);
1603 growing_buffer* msg = buffer_init(128);
1604 OSRF_BUFFER_ADD( msg, MODULENAME );
1605 OSRF_BUFFER_ADD( msg, ": Insufficient permissions to retrieve object" );
1607 char* m = buffer_release(msg);
1608 osrfAppSessionStatus( ctx->session, OSRF_STATUS_NOTALLOWED, "osrfMethodException", ctx->request, m );
1619 static char* jsonNumberToDBString ( osrfHash* field, const jsonObject* value ) {
1620 growing_buffer* val_buf = buffer_init(32);
1621 const char* numtype = get_datatype( field );
1623 if ( !strncmp( numtype, "INT", 3 ) ) {
1624 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%ld", (long)jsonObjectGetNumber(value) );
1626 char* val_str = jsonObjectToSimpleString(value);
1627 buffer_fadd( val_buf, "%ld", atol(val_str) );
1631 } else if ( !strcmp( numtype, "NUMERIC" ) ) {
1632 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%f", jsonObjectGetNumber(value) );
1634 char* val_str = jsonObjectToSimpleString(value);
1635 buffer_fadd( val_buf, "%f", atof(val_str) );
1640 return buffer_release(val_buf);
1643 static char* searchINPredicate (const char* class, osrfHash* field,
1644 jsonObject* node, const char* op, osrfMethodContext* ctx ) {
1645 growing_buffer* sql_buf = buffer_init(32);
1651 osrfHashGet(field, "name")
1655 buffer_add(sql_buf, "IN (");
1656 } else if (!(strcasecmp(op,"not in"))) {
1657 buffer_add(sql_buf, "NOT IN (");
1659 buffer_add(sql_buf, "IN (");
1662 if (node->type == JSON_HASH) {
1663 // subquery predicate
1664 char* subpred = SELECT(
1666 jsonObjectGetKey( node, "select" ),
1667 jsonObjectGetKey( node, "from" ),
1668 jsonObjectGetKey( node, "where" ),
1669 jsonObjectGetKey( node, "having" ),
1670 jsonObjectGetKey( node, "order_by" ),
1671 jsonObjectGetKey( node, "limit" ),
1672 jsonObjectGetKey( node, "offset" ),
1676 buffer_add(sql_buf, subpred);
1679 } else if (node->type == JSON_ARRAY) {
1680 // literal value list
1681 int in_item_index = 0;
1682 int in_item_first = 1;
1683 const jsonObject* in_item;
1684 while ( (in_item = jsonObjectGetIndex(node, in_item_index++)) ) {
1689 buffer_add(sql_buf, ", ");
1691 // Append the literal value -- quoted if not a number
1692 if ( JSON_NUMBER == in_item->type ) {
1693 char* val = jsonNumberToDBString( field, in_item );
1694 OSRF_BUFFER_ADD( sql_buf, val );
1697 } else if ( !strcmp( get_primitive( field ), "number") ) {
1698 char* val = jsonNumberToDBString( field, in_item );
1699 OSRF_BUFFER_ADD( sql_buf, val );
1703 char* key_string = jsonObjectToSimpleString(in_item);
1704 if ( dbi_conn_quote_string(dbhandle, &key_string) ) {
1705 OSRF_BUFFER_ADD( sql_buf, key_string );
1708 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, key_string);
1710 buffer_free(sql_buf);
1717 OSRF_BUFFER_ADD_CHAR( sql_buf, ')' );
1719 return buffer_release(sql_buf);
1722 // Receive a JSON_ARRAY representing a function call. The first
1723 // entry in the array is the function name. The rest are parameters.
1724 static char* searchValueTransform( const jsonObject* array ) {
1725 growing_buffer* sql_buf = buffer_init(32);
1728 jsonObject* func_item;
1730 // Get the function name
1731 if( array->size > 0 ) {
1732 func_item = jsonObjectGetIndex( array, 0 );
1733 val = jsonObjectToSimpleString( func_item );
1734 OSRF_BUFFER_ADD( sql_buf, val );
1735 OSRF_BUFFER_ADD( sql_buf, "( " );
1739 // Get the parameters
1740 int func_item_index = 1; // We already grabbed the zeroth entry
1741 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1743 // Add a separator comma, if we need one
1744 if( func_item_index > 2 )
1745 buffer_add( sql_buf, ", " );
1747 // Add the current parameter
1748 if (func_item->type == JSON_NULL) {
1749 buffer_add( sql_buf, "NULL" );
1751 val = jsonObjectToSimpleString(func_item);
1752 if ( dbi_conn_quote_string(dbhandle, &val) ) {
1753 OSRF_BUFFER_ADD( sql_buf, val );
1756 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1757 buffer_free(sql_buf);
1764 buffer_add( sql_buf, " )" );
1766 return buffer_release(sql_buf);
1769 static char* searchFunctionPredicate (const char* class, osrfHash* field,
1770 const jsonObject* node, const char* node_key) {
1771 growing_buffer* sql_buf = buffer_init(32);
1773 char* val = searchValueTransform(node);
1779 osrfHashGet(field, "name"),
1786 return buffer_release(sql_buf);
1789 // class is a class name
1790 // field is a field definition as stored in the IDL
1791 // node comes from the method parameter, and represents an entry in the SELECT list
1792 static char* searchFieldTransform (const char* class, osrfHash* field, const jsonObject* node) {
1793 growing_buffer* sql_buf = buffer_init(32);
1795 char* field_transform = jsonObjectToSimpleString( jsonObjectGetKeyConst( node, "transform" ) );
1796 char* transform_subcolumn = jsonObjectToSimpleString( jsonObjectGetKeyConst( node, "result_field" ) );
1798 if(transform_subcolumn)
1799 OSRF_BUFFER_ADD_CHAR( sql_buf, '(' ); // enclose transform in parentheses
1801 if (field_transform) {
1802 buffer_fadd( sql_buf, "%s(\"%s\".%s", field_transform, class, osrfHashGet(field, "name"));
1803 const jsonObject* array = jsonObjectGetKeyConst( node, "params" );
1806 if( array->type != JSON_ARRAY ) {
1807 osrfLogError( OSRF_LOG_MARK,
1808 "%s: Expected JSON_ARRAY for function params; found %s",
1809 MODULENAME, json_type( array->type ) );
1810 free( transform_subcolumn );
1811 free( field_transform );
1812 buffer_free( sql_buf );
1815 int func_item_index = 0;
1816 jsonObject* func_item;
1817 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1819 char* val = jsonObjectToSimpleString(func_item);
1822 buffer_add( sql_buf, ",NULL" );
1823 } else if ( dbi_conn_quote_string(dbhandle, &val) ) {
1824 OSRF_BUFFER_ADD_CHAR( sql_buf, ',' );
1825 OSRF_BUFFER_ADD( sql_buf, val );
1827 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1828 free(transform_subcolumn);
1829 free(field_transform);
1831 buffer_free(sql_buf);
1838 buffer_add( sql_buf, " )" );
1841 buffer_fadd( sql_buf, "\"%s\".%s", class, osrfHashGet(field, "name"));
1844 if (transform_subcolumn)
1845 buffer_fadd( sql_buf, ").\"%s\"", transform_subcolumn );
1847 if (field_transform) free(field_transform);
1848 if (transform_subcolumn) free(transform_subcolumn);
1850 return buffer_release(sql_buf);
1853 static char* searchFieldTransformPredicate (const char* class, osrfHash* field, jsonObject* node, const char* node_key) {
1854 char* field_transform = searchFieldTransform( class, field, node );
1857 const jsonObject* value_obj = jsonObjectGetKeyConst( node, "value" );
1858 if ( ! value_obj ) {
1859 value = searchWHERE( node, osrfHashGet( oilsIDL(), class ), AND_OP_JOIN, NULL );
1860 } else if ( value_obj->type == JSON_ARRAY ) {
1861 value = searchValueTransform( value_obj );
1862 } else if ( value_obj->type == JSON_HASH ) {
1863 value = searchWHERE( value_obj, osrfHashGet( oilsIDL(), class ), AND_OP_JOIN, NULL );
1864 } else if ( value_obj->type == JSON_NUMBER ) {
1865 value = jsonNumberToDBString( field, value_obj );
1866 } else if ( value_obj->type != JSON_NULL ) {
1867 if ( !strcmp( get_primitive( field ), "number") ) {
1868 value = jsonNumberToDBString( field, value_obj );
1870 value = jsonObjectToSimpleString( value_obj );
1871 if ( !dbi_conn_quote_string(dbhandle, &value) ) {
1872 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, value);
1874 free(field_transform);
1880 growing_buffer* sql_buf = buffer_init(32);
1891 free(field_transform);
1893 return buffer_release(sql_buf);
1896 static char* searchSimplePredicate (const char* op, const char* class,
1897 osrfHash* field, const jsonObject* node) {
1901 // Get the value to which we are comparing the specified column
1902 if (node->type != JSON_NULL) {
1903 if ( node->type == JSON_NUMBER ) {
1904 val = jsonNumberToDBString( field, node );
1905 } else if ( !strcmp( get_primitive( field ), "number" ) ) {
1906 val = jsonNumberToDBString( field, node );
1908 val = jsonObjectToSimpleString(node);
1913 if( JSON_NUMBER != node->type && strcmp( get_primitive( field ), "number") ) {
1914 // Value is not numeric; enclose it in quotes
1915 if ( !dbi_conn_quote_string( dbhandle, &val ) ) {
1916 osrfLogError( OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val );
1922 // Compare to a null value
1923 val = strdup( "NULL" );
1924 if (strcmp( op, "=" ))
1930 growing_buffer* sql_buf = buffer_init(32);
1931 buffer_fadd( sql_buf, "\"%s\".%s %s %s", class, osrfHashGet(field, "name"), op, val );
1932 char* pred = buffer_release( sql_buf );
1939 static char* searchBETWEENPredicate (const char* class, osrfHash* field, jsonObject* node) {
1944 if ( !strcmp( get_primitive( field ), "number") ) {
1945 x_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,0));
1946 y_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,1));
1949 x_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,0));
1950 y_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,1));
1951 if ( !(dbi_conn_quote_string(dbhandle, &x_string) && dbi_conn_quote_string(dbhandle, &y_string)) ) {
1952 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key strings [%s] and [%s]", MODULENAME, x_string, y_string);
1959 growing_buffer* sql_buf = buffer_init(32);
1960 buffer_fadd( sql_buf, "%s BETWEEN %s AND %s", osrfHashGet(field, "name"), x_string, y_string );
1964 return buffer_release(sql_buf);
1967 static char* searchPredicate ( const char* class, osrfHash* field,
1968 jsonObject* node, osrfMethodContext* ctx ) {
1971 if (node->type == JSON_ARRAY) { // equality IN search
1972 pred = searchINPredicate( class, field, node, NULL, ctx );
1973 } else if (node->type == JSON_HASH) { // non-equality search
1974 jsonObject* pred_node;
1975 jsonIterator* pred_itr = jsonNewIterator( node );
1976 while ( (pred_node = jsonIteratorNext( pred_itr )) ) {
1977 if ( !(strcasecmp( pred_itr->key,"between" )) )
1978 pred = searchBETWEENPredicate( class, field, pred_node );
1979 else if ( !(strcasecmp( pred_itr->key,"in" )) || !(strcasecmp( pred_itr->key,"not in" )) )
1980 pred = searchINPredicate( class, field, pred_node, pred_itr->key, ctx );
1981 else if ( pred_node->type == JSON_ARRAY )
1982 pred = searchFunctionPredicate( class, field, pred_node, pred_itr->key );
1983 else if ( pred_node->type == JSON_HASH )
1984 pred = searchFieldTransformPredicate( class, field, pred_node, pred_itr->key );
1986 pred = searchSimplePredicate( pred_itr->key, class, field, pred_node );
1990 jsonIteratorFree(pred_itr);
1991 } else if (node->type == JSON_NULL) { // IS NULL search
1992 growing_buffer* _p = buffer_init(64);
1995 "\"%s\".%s IS NULL",
1997 osrfHashGet(field, "name")
1999 pred = buffer_release(_p);
2000 } else { // equality search
2001 pred = searchSimplePredicate( "=", class, field, node );
2020 field : call_number,
2036 static char* searchJOIN ( const jsonObject* join_hash, osrfHash* leftmeta ) {
2038 const jsonObject* working_hash;
2039 jsonObject* freeable_hash = NULL;
2041 if (join_hash->type == JSON_STRING) {
2042 // create a wrapper around a copy of the original
2043 char* _tmp = jsonObjectToSimpleString( join_hash );
2044 freeable_hash = jsonNewObjectType(JSON_HASH);
2045 jsonObjectSetKey(freeable_hash, _tmp, NULL);
2047 working_hash = freeable_hash;
2050 if( join_hash->type != JSON_HASH ) {
2053 "%s: JOIN failed; expected JSON object type not found",
2058 working_hash = join_hash;
2061 growing_buffer* join_buf = buffer_init(128);
2062 const char* leftclass = osrfHashGet(leftmeta, "classname");
2064 jsonObject* snode = NULL;
2065 jsonIterator* search_itr = jsonNewIterator( working_hash );
2067 while ( (snode = jsonIteratorNext( search_itr )) ) {
2068 const char* class = search_itr->key;
2069 osrfHash* idlClass = osrfHashGet( oilsIDL(), class );
2073 "%s: JOIN failed. No class \"%s\" defined in IDL",
2077 jsonIteratorFree( search_itr );
2078 buffer_free( join_buf );
2080 jsonObjectFree( freeable_hash );
2084 char* fkey = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "fkey" ) );
2085 char* field = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "field" ) );
2087 if (field && !fkey) {
2088 fkey = (char*)oilsIDLFindPath("/%s/links/%s/key", class, field);
2092 "%s: JOIN failed. No link defined from %s.%s to %s",
2098 buffer_free(join_buf);
2100 jsonObjectFree(freeable_hash);
2102 jsonIteratorFree(search_itr);
2105 fkey = strdup( fkey );
2107 } else if (!field && fkey) {
2108 field = (char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, fkey );
2112 "%s: JOIN failed. No link defined from %s.%s to %s",
2118 buffer_free(join_buf);
2120 jsonObjectFree(freeable_hash);
2122 jsonIteratorFree(search_itr);
2125 field = strdup( field );
2127 } else if (!field && !fkey) {
2128 osrfHash* _links = oilsIDL_links( leftclass );
2130 // For each link defined for the left class:
2131 // see if the link references the joined class
2132 osrfHashIterator* itr = osrfNewHashIterator( _links );
2133 osrfHash* curr_link = NULL;
2134 while( (curr_link = osrfHashIteratorNext( itr ) ) ) {
2135 const char* other_class = osrfHashGet( curr_link, "class" );
2136 if( other_class && !strcmp( other_class, class ) ) {
2138 // Found a link between the classes
2139 fkey = strdup( osrfHashIteratorKey( itr ) );
2140 const char* other_key = osrfHashGet( curr_link, "key" );
2141 field = other_key ? strdup( other_key ) : NULL;
2145 osrfHashIteratorFree( itr );
2147 if (!field || !fkey) {
2148 // Do another such search, with the classes reversed
2149 _links = oilsIDL_links( class );
2151 // For each link defined for the joined class:
2152 // see if the link references the left class
2153 osrfHashIterator* itr = osrfNewHashIterator( _links );
2154 osrfHash* curr_link = NULL;
2155 while( (curr_link = osrfHashIteratorNext( itr ) ) ) {
2156 const char* other_class = osrfHashGet( curr_link, "class" );
2157 if( other_class && !strcmp( other_class, leftclass ) ) {
2159 // Found a link between the classes
2160 fkey = strdup( osrfHashIteratorKey( itr ) );
2161 const char* other_key = osrfHashGet( curr_link, "key" );
2162 field = other_key ? strdup( other_key ) : NULL;
2166 osrfHashIteratorFree( itr );
2169 if (!field || !fkey) {
2172 "%s: JOIN failed. No link defined between %s and %s",
2179 buffer_free(join_buf);
2181 jsonObjectFree(freeable_hash);
2182 jsonIteratorFree(search_itr);
2188 char* type = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "type" ) );
2190 if ( !strcasecmp(type,"left") ) {
2191 buffer_add(join_buf, " LEFT JOIN");
2192 } else if ( !strcasecmp(type,"right") ) {
2193 buffer_add(join_buf, " RIGHT JOIN");
2194 } else if ( !strcasecmp(type,"full") ) {
2195 buffer_add(join_buf, " FULL JOIN");
2197 buffer_add(join_buf, " INNER JOIN");
2200 buffer_add(join_buf, " INNER JOIN");
2204 char* table = getSourceDefinition(idlClass);
2208 jsonIteratorFree( search_itr );
2209 buffer_free( join_buf );
2211 jsonObjectFree( freeable_hash );
2215 buffer_fadd(join_buf, " %s AS \"%s\" ON ( \"%s\".%s = \"%s\".%s",
2216 table, class, class, field, leftclass, fkey);
2219 const jsonObject* filter = jsonObjectGetKeyConst( snode, "filter" );
2221 char* filter_op = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "filter_op" ) );
2223 if (!strcasecmp("or",filter_op)) {
2224 buffer_add( join_buf, " OR " );
2226 buffer_add( join_buf, " AND " );
2229 buffer_add( join_buf, " AND " );
2232 char* jpred = searchWHERE( filter, idlClass, AND_OP_JOIN, NULL );
2233 OSRF_BUFFER_ADD_CHAR( join_buf, ' ' );
2234 OSRF_BUFFER_ADD( join_buf, jpred );
2239 buffer_add(join_buf, " ) ");
2241 const jsonObject* join_filter = jsonObjectGetKeyConst( snode, "join" );
2243 char* jpred = searchJOIN( join_filter, idlClass );
2244 OSRF_BUFFER_ADD_CHAR( join_buf, ' ' );
2245 OSRF_BUFFER_ADD( join_buf, jpred );
2254 jsonObjectFree(freeable_hash);
2255 jsonIteratorFree(search_itr);
2257 return buffer_release(join_buf);
2262 { +class : { -or|-and : { field : { op : value }, ... } ... }, ... }
2263 { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }
2264 [ { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }, ... ]
2268 static char* searchWHERE ( const jsonObject* search_hash, osrfHash* meta, int opjoin_type, osrfMethodContext* ctx ) {
2272 "%s: Entering searchWHERE; search_hash addr = %p, meta addr = %p, opjoin_type = %d, ctx addr = %p",
2280 growing_buffer* sql_buf = buffer_init(128);
2282 jsonObject* node = NULL;
2285 if ( search_hash->type == JSON_ARRAY ) {
2286 osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_ARRAY", MODULENAME);
2287 jsonIterator* search_itr = jsonNewIterator( search_hash );
2288 while ( (node = jsonIteratorNext( search_itr )) ) {
2292 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2293 else buffer_add(sql_buf, " AND ");
2296 char* subpred = searchWHERE( node, meta, opjoin_type, ctx );
2297 buffer_fadd(sql_buf, "( %s )", subpred);
2300 jsonIteratorFree(search_itr);
2302 } else if ( search_hash->type == JSON_HASH ) {
2303 osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_HASH", MODULENAME);
2304 jsonIterator* search_itr = jsonNewIterator( search_hash );
2305 while ( (node = jsonIteratorNext( search_itr )) ) {
2310 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2311 else buffer_add(sql_buf, " AND ");
2314 if ( !strncmp("+",search_itr->key,1) ) {
2315 if ( node->type == JSON_STRING ) {
2316 char* subpred = jsonObjectToSimpleString( node );
2317 buffer_fadd(sql_buf, " \"%s\".%s ", search_itr->key + 1, subpred);
2320 char* subpred = searchWHERE( node, osrfHashGet( oilsIDL(), search_itr->key + 1 ), AND_OP_JOIN, ctx );
2321 buffer_fadd(sql_buf, "( %s )", subpred);
2324 } else if ( !strcasecmp("-or",search_itr->key) ) {
2325 char* subpred = searchWHERE( node, meta, OR_OP_JOIN, ctx );
2326 buffer_fadd(sql_buf, "( %s )", subpred);
2328 } else if ( !strcasecmp("-and",search_itr->key) ) {
2329 char* subpred = searchWHERE( node, meta, AND_OP_JOIN, ctx );
2330 buffer_fadd(sql_buf, "( %s )", subpred);
2332 } else if ( !strcasecmp("-exists",search_itr->key) ) {
2333 char* subpred = SELECT(
2335 jsonObjectGetKey( node, "select" ),
2336 jsonObjectGetKey( node, "from" ),
2337 jsonObjectGetKey( node, "where" ),
2338 jsonObjectGetKey( node, "having" ),
2339 jsonObjectGetKey( node, "order_by" ),
2340 jsonObjectGetKey( node, "limit" ),
2341 jsonObjectGetKey( node, "offset" ),
2345 buffer_fadd(sql_buf, "EXISTS ( %s )", subpred);
2347 } else if ( !strcasecmp("-not-exists",search_itr->key) ) {
2348 char* subpred = SELECT(
2350 jsonObjectGetKey( node, "select" ),
2351 jsonObjectGetKey( node, "from" ),
2352 jsonObjectGetKey( node, "where" ),
2353 jsonObjectGetKey( node, "having" ),
2354 jsonObjectGetKey( node, "order_by" ),
2355 jsonObjectGetKey( node, "limit" ),
2356 jsonObjectGetKey( node, "offset" ),
2360 buffer_fadd(sql_buf, "NOT EXISTS ( %s )", subpred);
2364 char* class = osrfHashGet(meta, "classname");
2365 osrfHash* fields = osrfHashGet(meta, "fields");
2366 osrfHash* field = osrfHashGet( fields, search_itr->key );
2370 char* table = getSourceDefinition(meta);
2372 table = strdup( "(?)" );
2375 "%s: Attempt to reference non-existent column %s on %s (%s)",
2381 buffer_free(sql_buf);
2383 jsonIteratorFree(search_itr);
2387 char* subpred = searchPredicate( class, field, node, ctx );
2388 buffer_add( sql_buf, subpred );
2392 jsonIteratorFree(search_itr);
2395 // ERROR ... only hash and array allowed at this level
2396 char* predicate_string = jsonObjectToJSON( search_hash );
2399 "%s: Invalid predicate structure: %s",
2403 buffer_free(sql_buf);
2404 free(predicate_string);
2409 return buffer_release(sql_buf);
2413 /* method context */ osrfMethodContext* ctx,
2415 /* SELECT */ jsonObject* selhash,
2416 /* FROM */ jsonObject* join_hash,
2417 /* WHERE */ jsonObject* search_hash,
2418 /* HAVING */ jsonObject* having_hash,
2419 /* ORDER BY */ jsonObject* order_hash,
2420 /* LIMIT */ jsonObject* limit,
2421 /* OFFSET */ jsonObject* offset,
2422 /* flags */ int flags
2424 const char* locale = osrf_message_get_last_locale();
2426 // in case we don't get a select list
2427 jsonObject* defaultselhash = NULL;
2429 // general tmp objects
2430 const jsonObject* tmp_const;
2431 jsonObject* selclass = NULL;
2432 jsonObject* selfield = NULL;
2433 jsonObject* snode = NULL;
2434 jsonObject* onode = NULL;
2436 char* string = NULL;
2437 int from_function = 0;
2442 // the core search class
2443 char* core_class = NULL;
2445 // metadata about the core search class
2446 osrfHash* core_meta = NULL;
2448 // punt if there's no core class
2449 if (!join_hash || ( join_hash->type == JSON_HASH && !join_hash->size )) {
2452 "%s: FROM clause is missing or empty",
2456 osrfAppSessionStatus(
2458 OSRF_STATUS_INTERNALSERVERERROR,
2459 "osrfMethodException",
2461 "FROM clause is missing or empty in JSON query"
2466 // get the core class -- the only key of the top level FROM clause, or a string
2467 if (join_hash->type == JSON_HASH) {
2468 jsonIterator* tmp_itr = jsonNewIterator( join_hash );
2469 snode = jsonIteratorNext( tmp_itr );
2471 core_class = strdup( tmp_itr->key );
2474 jsonObject* extra = jsonIteratorNext( tmp_itr );
2476 jsonIteratorFree( tmp_itr );
2479 // There shouldn't be more than one entry in join_hash
2483 "%s: Malformed FROM clause: extra entry in JSON_HASH",
2487 osrfAppSessionStatus(
2489 OSRF_STATUS_INTERNALSERVERERROR,
2490 "osrfMethodException",
2492 "Malformed FROM clause in JSON query"
2495 return NULL; // Malformed join_hash; extra entry
2497 } else if (join_hash->type == JSON_ARRAY) {
2499 core_class = jsonObjectToSimpleString( jsonObjectGetIndex(join_hash, 0) );
2502 } else if (join_hash->type == JSON_STRING) {
2503 core_class = jsonObjectToSimpleString( join_hash );
2509 "%s: FROM clause is unexpected JSON type: %s",
2511 json_type( join_hash->type )
2514 osrfAppSessionStatus(
2516 OSRF_STATUS_INTERNALSERVERERROR,
2517 "osrfMethodException",
2519 "Ill-formed FROM clause in JSON query"
2525 if (!from_function) {
2526 // Get the IDL class definition for the core class
2527 core_meta = osrfHashGet( oilsIDL(), core_class );
2528 if( !core_meta ) { // Didn't find it?
2531 "%s: SELECT clause references undefined class: \"%s\"",
2536 osrfAppSessionStatus(
2538 OSRF_STATUS_INTERNALSERVERERROR,
2539 "osrfMethodException",
2541 "SELECT clause references undefined class in JSON query"
2547 // Make sure the class isn't virtual
2548 if( str_is_true( osrfHashGet( core_meta, "virtual" ) ) ) {
2551 "%s: Core class is virtual: \"%s\"",
2556 osrfAppSessionStatus(
2558 OSRF_STATUS_INTERNALSERVERERROR,
2559 "osrfMethodException",
2561 "FROM clause references virtual class in JSON query"
2568 // if the select list is empty, or the core class field list is '*',
2569 // build the default select list ...
2571 selhash = defaultselhash = jsonNewObjectType(JSON_HASH);
2572 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2573 } else if( selhash->type != JSON_HASH ) {
2576 "%s: Expected JSON_HASH for SELECT clause; found %s",
2578 json_type( selhash->type )
2582 osrfAppSessionStatus(
2584 OSRF_STATUS_INTERNALSERVERERROR,
2585 "osrfMethodException",
2587 "Malformed SELECT clause in JSON query"
2591 } else if ( (tmp_const = jsonObjectGetKeyConst( selhash, core_class )) && tmp_const->type == JSON_STRING ) {
2592 char* _x = jsonObjectToSimpleString( tmp_const );
2593 if (!strncmp( "*", _x, 1 )) {
2594 jsonObjectRemoveKey( selhash, core_class );
2595 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2601 growing_buffer* sql_buf = buffer_init(128);
2603 // temp buffer for the SELECT list
2604 growing_buffer* select_buf = buffer_init(128);
2605 growing_buffer* order_buf = buffer_init(128);
2606 growing_buffer* group_buf = buffer_init(128);
2607 growing_buffer* having_buf = buffer_init(128);
2609 int aggregate_found = 0; // boolean
2611 // Build a select list
2612 if(from_function) // From a function we select everything
2613 OSRF_BUFFER_ADD_CHAR( select_buf, '*' );
2616 // If we need to build a default list, prepare to do so
2617 jsonObject* _tmp = jsonObjectGetKey( selhash, core_class );
2618 if ( _tmp && !_tmp->size ) {
2620 osrfHash* core_fields = osrfHashGet( core_meta, "fields" );
2622 osrfHashIterator* field_itr = osrfNewHashIterator( core_fields );
2623 osrfHash* field_def;
2624 while( ( field_def = osrfHashIteratorNext( field_itr ) ) ) {
2625 if( ! str_is_true( osrfHashGet( field_def, "virtual" ) ) ) {
2626 // This field is not virtual, so add it to the list
2627 jsonObjectPush( _tmp, jsonNewObject( osrfHashIteratorKey( field_itr ) ) );
2630 osrfHashIteratorFree( field_itr );
2633 // Now build the actual select list
2637 jsonIterator* selclass_itr = jsonNewIterator( selhash );
2638 while ( (selclass = jsonIteratorNext( selclass_itr )) ) { // For each class
2640 // Make sure the class is defined in the IDL
2641 const char* cname = selclass_itr->key;
2642 osrfHash* idlClass = osrfHashGet( oilsIDL(), cname );
2646 "%s: Selected class \"%s\" not defined in IDL",
2652 osrfAppSessionStatus(
2654 OSRF_STATUS_INTERNALSERVERERROR,
2655 "osrfMethodException",
2657 "Selected class is not defined"
2659 jsonIteratorFree( selclass_itr );
2660 buffer_free( sql_buf );
2661 buffer_free( select_buf );
2662 buffer_free( order_buf );
2663 buffer_free( group_buf );
2664 buffer_free( having_buf );
2665 if( defaultselhash ) jsonObjectFree( defaultselhash );
2670 // Make sure the target relation is in the join tree.
2672 // At this point join_hash is a step down from the join_hash we
2673 // received as a parameter. If the original was a JSON_STRING,
2674 // then json_hash is now NULL. If the original was a JSON_HASH,
2675 // then json_hash is now the first (and only) entry in it,
2676 // denoting the core class. We've already excluded the
2677 // possibility that the original was a JSON_ARRAY, because in
2678 // that case from_function would be non-NULL, and we wouldn't
2681 int class_in_from_clause; // boolean
2683 if ( ! strcmp( core_class, cname ))
2684 // This is the core class -- no problem
2685 class_in_from_clause = 1;
2688 // There's only one class in the FROM clause, and this isn't it
2689 class_in_from_clause = 0;
2690 else if (join_hash->type == JSON_STRING) {
2691 // There's only one class in the FROM clause
2692 string = jsonObjectToSimpleString(join_hash);
2693 if ( strcmp( string, cname ) )
2694 class_in_from_clause = 0; // This isn't it
2696 class_in_from_clause = 1; // This is it
2699 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", cname);
2700 if ( 0 == found->size )
2701 class_in_from_clause = 0; // Nowhere in the join tree
2703 class_in_from_clause = 1; // Found it
2704 jsonObjectFree( found );
2708 // If the class isn't in the FROM clause, bail out
2709 if( ! class_in_from_clause ) {
2712 "%s: SELECT clause references class not in FROM clause: \"%s\"",
2717 osrfAppSessionStatus(
2719 OSRF_STATUS_INTERNALSERVERERROR,
2720 "osrfMethodException",
2722 "Selected class not in FROM clause in JSON query"
2724 jsonIteratorFree( selclass_itr );
2725 buffer_free( sql_buf );
2726 buffer_free( select_buf );
2727 buffer_free( order_buf );
2728 buffer_free( group_buf );
2729 buffer_free( having_buf );
2730 if( defaultselhash ) jsonObjectFree( defaultselhash );
2735 // Look up some attributes of the current class, so that we
2736 // don't have to look them up again for each field
2737 osrfHash* class_field_set = osrfHashGet( idlClass, "fields" );
2738 const char* class_pkey = osrfHashGet( idlClass, "primarykey" );
2739 const char* class_tname = osrfHashGet( idlClass, "tablename" );
2741 // stitch together the column list ...
2742 jsonIterator* select_itr = jsonNewIterator( selclass );
2743 while ( (selfield = jsonIteratorNext( select_itr )) ) { // for each SELECT column
2745 // If we need a separator comma, add one
2749 OSRF_BUFFER_ADD_CHAR( select_buf, ',' );
2752 // ... if it's a string, just toss it on the pile
2753 if (selfield->type == JSON_STRING) {
2755 // Look up the field in the IDL
2756 const char* col_name = selfield->value.s;
2757 osrfHash* field_def = osrfHashGet( class_field_set, col_name );
2759 // No such field in current class
2762 "%s: Selected column \"%s\" not defined in IDL for class \"%s\"",
2768 osrfAppSessionStatus(
2770 OSRF_STATUS_INTERNALSERVERERROR,
2771 "osrfMethodException",
2773 "Selected column not defined in JSON query"
2775 jsonIteratorFree( select_itr );
2776 jsonIteratorFree( selclass_itr );
2777 buffer_free( sql_buf );
2778 buffer_free( select_buf );
2779 buffer_free( order_buf );
2780 buffer_free( group_buf );
2781 buffer_free( having_buf );
2782 if( defaultselhash ) jsonObjectFree( defaultselhash );
2785 } else if ( str_is_true( osrfHashGet( field_def, "virtual" ) ) ) {
2786 // Virtual field not allowed
2789 "%s: Selected column \"%s\" for class \"%s\" is virtual",
2795 osrfAppSessionStatus(
2797 OSRF_STATUS_INTERNALSERVERERROR,
2798 "osrfMethodException",
2800 "Selected column may not be virtual in JSON query"
2802 jsonIteratorFree( select_itr );
2803 jsonIteratorFree( selclass_itr );
2804 buffer_free( sql_buf );
2805 buffer_free( select_buf );
2806 buffer_free( order_buf );
2807 buffer_free( group_buf );
2808 buffer_free( having_buf );
2809 if( defaultselhash ) jsonObjectFree( defaultselhash );
2816 if (flags & DISABLE_I18N)
2819 i18n = osrfHashGet(field_def, "i18n");
2821 if( str_is_true( i18n ) ) {
2822 buffer_fadd( select_buf,
2823 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2824 class_tname, cname, col_name, class_pkey, cname, class_pkey, locale, col_name );
2826 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2829 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2832 // ... but it could be an object, in which case we check for a Field Transform
2833 } else if (selfield->type == JSON_HASH) {
2835 char* col_name = jsonObjectToSimpleString( jsonObjectGetKeyConst( selfield, "column" ) );
2837 // Get the field definition from the IDL
2838 osrfHash* field_def = osrfHashGet( class_field_set, col_name );
2840 // No such field in current class
2843 "%s: Selected column \"%s\" is not defined in IDL for class \"%s\"",
2849 osrfAppSessionStatus(
2851 OSRF_STATUS_INTERNALSERVERERROR,
2852 "osrfMethodException",
2854 "Selected column is not defined in JSON query"
2856 jsonIteratorFree( select_itr );
2857 jsonIteratorFree( selclass_itr );
2858 buffer_free( sql_buf );
2859 buffer_free( select_buf );
2860 buffer_free( order_buf );
2861 buffer_free( group_buf );
2862 buffer_free( having_buf );
2863 if( defaultselhash ) jsonObjectFree( defaultselhash );
2866 } else if ( str_is_true( osrfHashGet( field_def, "virtual" ) ) ) {
2867 // No such field in current class
2870 "%s: Selected column \"%s\" is virtual for class \"%s\"",
2876 osrfAppSessionStatus(
2878 OSRF_STATUS_INTERNALSERVERERROR,
2879 "osrfMethodException",
2881 "Selected column is virtual in JSON query"
2883 jsonIteratorFree( select_itr );
2884 jsonIteratorFree( selclass_itr );
2885 buffer_free( sql_buf );
2886 buffer_free( select_buf );
2887 buffer_free( order_buf );
2888 buffer_free( group_buf );
2889 buffer_free( having_buf );
2890 if( defaultselhash ) jsonObjectFree( defaultselhash );
2895 // Decide what to use as a column alias
2897 if ((tmp_const = jsonObjectGetKeyConst( selfield, "alias" ))) {
2898 _alias = jsonObjectToSimpleString( tmp_const );
2899 } else { // Use field name as the alias
2903 if (jsonObjectGetKeyConst( selfield, "transform" )) {
2904 char* transform_str = searchFieldTransform(cname, field_def, selfield);
2905 if( transform_str ) {
2906 buffer_fadd(select_buf, " %s AS \"%s\"", transform_str, _alias);
2907 free(transform_str);
2910 osrfAppSessionStatus(
2912 OSRF_STATUS_INTERNALSERVERERROR,
2913 "osrfMethodException",
2915 "Unable to generate transform function in JSON query"
2917 jsonIteratorFree( select_itr );
2918 jsonIteratorFree( selclass_itr );
2919 buffer_free( sql_buf );
2920 buffer_free( select_buf );
2921 buffer_free( order_buf );
2922 buffer_free( group_buf );
2923 buffer_free( having_buf );
2924 if( defaultselhash ) jsonObjectFree( defaultselhash );
2932 if (flags & DISABLE_I18N)
2935 i18n = osrfHashGet(field_def, "i18n");
2937 if( str_is_true( i18n ) ) {
2938 buffer_fadd( select_buf,
2939 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2940 class_tname, cname, col_name, class_pkey, cname, class_pkey, locale, _alias);
2942 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, _alias);
2945 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, _alias);
2949 if( _alias != col_name )
2956 "%s: Selected item is unexpected JSON type: %s",
2958 json_type( selfield->type )
2961 osrfAppSessionStatus(
2963 OSRF_STATUS_INTERNALSERVERERROR,
2964 "osrfMethodException",
2966 "Ill-formed SELECT item in JSON query"
2968 jsonIteratorFree( select_itr );
2969 jsonIteratorFree( selclass_itr );
2970 buffer_free( sql_buf );
2971 buffer_free( select_buf );
2972 buffer_free( order_buf );
2973 buffer_free( group_buf );
2974 buffer_free( having_buf );
2975 if( defaultselhash ) jsonObjectFree( defaultselhash );
2980 const jsonObject* agg_obj = jsonObjectGetKey( selfield, "aggregate" );
2981 if( obj_is_true( agg_obj ) )
2982 aggregate_found = 1;
2984 // Append a comma (except for the first one)
2985 // and add the column to a GROUP BY clause
2989 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
2991 buffer_fadd(group_buf, " %d", sel_pos);
2995 if (is_agg->size || (flags & SELECT_DISTINCT)) {
2997 const jsonObject* aggregate_obj = jsonObjectGetKey( selfield, "aggregate" );
2998 if ( ! obj_is_true( aggregate_obj ) ) {
3002 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
3005 buffer_fadd(group_buf, " %d", sel_pos);
3008 } else if (is_agg = jsonObjectGetKey( selfield, "having" )) {
3012 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
3015 _column = searchFieldTransform(cname, field, selfield);
3016 OSRF_BUFFER_ADD_CHAR(group_buf, ' ');
3017 OSRF_BUFFER_ADD(group_buf, _column);
3018 _column = searchFieldTransform(cname, field, selfield);
3025 } // end while -- iterating across SELECT columns
3027 jsonIteratorFree(select_itr);
3028 } // end while -- iterating across classes
3030 jsonIteratorFree(selclass_itr);
3034 char* col_list = buffer_release(select_buf);
3036 if (from_function) table = searchValueTransform(join_hash);
3037 else table = getSourceDefinition(core_meta);
3041 osrfAppSessionStatus(
3043 OSRF_STATUS_INTERNALSERVERERROR,
3044 "osrfMethodException",
3046 "Unable to identify table for core class"
3049 buffer_free( sql_buf );
3050 buffer_free( order_buf );
3051 buffer_free( group_buf );
3052 buffer_free( having_buf );
3053 if( defaultselhash ) jsonObjectFree( defaultselhash );
3058 // Put it all together
3059 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\" ", col_list, table, core_class );
3063 if (!from_function) {
3064 // Now, walk the join tree and add that clause
3066 char* join_clause = searchJOIN( join_hash, core_meta );
3068 buffer_add(sql_buf, join_clause);
3072 osrfAppSessionStatus(
3074 OSRF_STATUS_INTERNALSERVERERROR,
3075 "osrfMethodException",
3077 "Unable to construct JOIN clause(s)"
3079 buffer_free( sql_buf );
3080 buffer_free( order_buf );
3081 buffer_free( group_buf );
3082 buffer_free( having_buf );
3083 if( defaultselhash ) jsonObjectFree( defaultselhash );
3089 // Build a WHERE clause, if there is one
3090 if ( search_hash ) {
3091 buffer_add(sql_buf, " WHERE ");
3093 // and it's on the WHERE clause
3094 char* pred = searchWHERE( search_hash, core_meta, AND_OP_JOIN, ctx );
3097 buffer_add(sql_buf, pred);
3101 osrfAppSessionStatus(
3103 OSRF_STATUS_INTERNALSERVERERROR,
3104 "osrfMethodException",
3106 "Severe query error in WHERE predicate -- see error log for more details"
3110 buffer_free(having_buf);
3111 buffer_free(group_buf);
3112 buffer_free(order_buf);
3113 buffer_free(sql_buf);
3114 if (defaultselhash) jsonObjectFree(defaultselhash);
3119 // Build a HAVING clause, if there is one
3120 if ( having_hash ) {
3121 buffer_add(sql_buf, " HAVING ");
3123 // and it's on the the WHERE clause
3124 char* pred = searchWHERE( having_hash, core_meta, AND_OP_JOIN, ctx );
3127 buffer_add(sql_buf, pred);
3131 osrfAppSessionStatus(
3133 OSRF_STATUS_INTERNALSERVERERROR,
3134 "osrfMethodException",
3136 "Severe query error in HAVING predicate -- see error log for more details"
3140 buffer_free(having_buf);
3141 buffer_free(group_buf);
3142 buffer_free(order_buf);
3143 buffer_free(sql_buf);
3144 if (defaultselhash) jsonObjectFree(defaultselhash);
3149 // Build an ORDER BY clause, if there is one
3151 jsonIterator* class_itr = jsonNewIterator( order_hash );
3152 while ( (snode = jsonIteratorNext( class_itr )) ) {
3154 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
3157 if ( snode->type == JSON_HASH ) {
3159 jsonIterator* order_itr = jsonNewIterator( snode );
3160 while ( (onode = jsonIteratorNext( order_itr )) ) {
3162 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
3165 char* direction = NULL;
3166 if ( onode->type == JSON_HASH ) {
3167 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
3168 string = searchFieldTransform(
3170 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
3174 growing_buffer* field_buf = buffer_init(16);
3175 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
3176 string = buffer_release(field_buf);
3179 if ( (tmp_const = jsonObjectGetKeyConst( onode, "direction" )) ) {
3180 direction = jsonObjectToSimpleString(tmp_const);
3181 if (!strncasecmp(direction, "d", 1)) {
3183 direction = " DESC";
3191 string = strdup(order_itr->key);
3192 direction = jsonObjectToSimpleString(onode);
3193 if (!strncasecmp(direction, "d", 1)) {
3195 direction = " DESC";
3205 buffer_add(order_buf, ", ");
3208 buffer_add(order_buf, string);
3212 buffer_add(order_buf, direction);
3216 // jsonIteratorFree(order_itr);
3218 } else if ( snode->type == JSON_ARRAY ) {
3220 jsonIterator* order_itr = jsonNewIterator( snode );
3221 while ( (onode = jsonIteratorNext( order_itr )) ) {
3223 char* _f = jsonObjectToSimpleString( onode );
3225 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, _f))
3231 buffer_add(order_buf, ", ");
3234 buffer_add(order_buf, _f);
3238 // jsonIteratorFree(order_itr);
3241 // IT'S THE OOOOOOOOOOOLD STYLE!
3243 osrfLogError(OSRF_LOG_MARK, "%s: Possible SQL injection attempt; direct order by is not allowed", MODULENAME);
3245 osrfAppSessionStatus(
3247 OSRF_STATUS_INTERNALSERVERERROR,
3248 "osrfMethodException",
3250 "Severe query error -- see error log for more details"
3255 buffer_free(having_buf);
3256 buffer_free(group_buf);
3257 buffer_free(order_buf);
3258 buffer_free(sql_buf);
3259 if (defaultselhash) jsonObjectFree(defaultselhash);
3260 jsonIteratorFree(class_itr);
3265 // jsonIteratorFree(class_itr);
3269 string = buffer_release(group_buf);
3271 if ( *string && ( aggregate_found || (flags & SELECT_DISTINCT) ) ) {
3272 OSRF_BUFFER_ADD( sql_buf, " GROUP BY " );
3273 OSRF_BUFFER_ADD( sql_buf, string );
3278 string = buffer_release(having_buf);
3281 OSRF_BUFFER_ADD( sql_buf, " HAVING " );
3282 OSRF_BUFFER_ADD( sql_buf, string );
3287 string = buffer_release(order_buf);
3290 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
3291 OSRF_BUFFER_ADD( sql_buf, string );
3297 string = jsonObjectToSimpleString(limit);
3298 buffer_fadd( sql_buf, " LIMIT %d", atoi(string) );
3303 string = jsonObjectToSimpleString(offset);
3304 buffer_fadd( sql_buf, " OFFSET %d", atoi(string) );
3308 if (!(flags & SUBSELECT)) OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
3311 if (defaultselhash) jsonObjectFree(defaultselhash);
3313 return buffer_release(sql_buf);
3317 static char* buildSELECT ( jsonObject* search_hash, jsonObject* order_hash, osrfHash* meta, osrfMethodContext* ctx ) {
3319 const char* locale = osrf_message_get_last_locale();
3321 osrfHash* fields = osrfHashGet(meta, "fields");
3322 char* core_class = osrfHashGet(meta, "classname");
3324 const jsonObject* join_hash = jsonObjectGetKeyConst( order_hash, "join" );
3326 jsonObject* node = NULL;
3327 jsonObject* snode = NULL;
3328 jsonObject* onode = NULL;
3329 const jsonObject* _tmp = NULL;
3330 jsonObject* selhash = NULL;
3331 jsonObject* defaultselhash = NULL;
3333 growing_buffer* sql_buf = buffer_init(128);
3334 growing_buffer* select_buf = buffer_init(128);
3336 if ( !(selhash = jsonObjectGetKey( order_hash, "select" )) ) {
3337 defaultselhash = jsonNewObjectType(JSON_HASH);
3338 selhash = defaultselhash;
3341 if ( !jsonObjectGetKeyConst(selhash,core_class) ) {
3342 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
3343 jsonObject* flist = jsonObjectGetKey( selhash, core_class );
3348 osrfStringArray* keys = osrfHashKeys( fields );
3349 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
3350 if( ! str_is_true( osrfHashGet( osrfHashGet( fields, field ), "virtual" ) ) )
3351 jsonObjectPush( flist, jsonNewObject( field ) );
3353 osrfStringArrayFree(keys);
3357 jsonIterator* class_itr = jsonNewIterator( selhash );
3358 while ( (snode = jsonIteratorNext( class_itr )) ) {
3360 char* cname = class_itr->key;
3361 osrfHash* idlClass = osrfHashGet( oilsIDL(), cname );
3362 if (!idlClass) continue;
3364 if (strcmp(core_class,class_itr->key)) {
3365 if (!join_hash) continue;
3367 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", class_itr->key);
3369 jsonObjectFree(found);
3373 jsonObjectFree(found);
3376 jsonIterator* select_itr = jsonNewIterator( snode );
3377 while ( (node = jsonIteratorNext( select_itr )) ) {
3378 char* item_str = jsonObjectToSimpleString(node);
3379 osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), item_str );
3381 char* fname = osrfHashGet(field, "name");
3383 if (!field) continue;
3388 OSRF_BUFFER_ADD_CHAR(select_buf, ',');
3393 const jsonObject* no_i18n_obj = jsonObjectGetKey( order_hash, "no_i18n" );
3394 if ( obj_is_true( no_i18n_obj ) ) // Suppress internationalization?
3397 i18n = osrfHashGet(field, "i18n");
3399 if( str_is_true( i18n ) ) {
3400 char* pkey = osrfHashGet(idlClass, "primarykey");
3401 char* tname = osrfHashGet(idlClass, "tablename");
3403 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);
3405 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
3408 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
3412 jsonIteratorFree(select_itr);
3415 jsonIteratorFree(class_itr);
3417 char* col_list = buffer_release(select_buf);
3418 char* table = getSourceDefinition(meta);
3420 table = strdup( "(null)" );
3422 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\"", col_list, table, core_class );
3427 char* join_clause = searchJOIN( join_hash, meta );
3428 OSRF_BUFFER_ADD_CHAR(sql_buf, ' ');
3429 OSRF_BUFFER_ADD(sql_buf, join_clause);
3433 osrfLogDebug(OSRF_LOG_MARK, "%s pre-predicate SQL = %s",
3434 MODULENAME, OSRF_BUFFER_C_STR(sql_buf));
3436 buffer_add(sql_buf, " WHERE ");
3438 char* pred = searchWHERE( search_hash, meta, AND_OP_JOIN, ctx );
3440 osrfAppSessionStatus(
3442 OSRF_STATUS_INTERNALSERVERERROR,
3443 "osrfMethodException",
3445 "Severe query error -- see error log for more details"
3447 buffer_free(sql_buf);
3448 if(defaultselhash) jsonObjectFree(defaultselhash);
3451 buffer_add(sql_buf, pred);
3456 char* string = NULL;
3457 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "order_by" )) ){
3459 growing_buffer* order_buf = buffer_init(128);
3462 jsonIterator* class_itr = jsonNewIterator( _tmp );
3463 while ( (snode = jsonIteratorNext( class_itr )) ) {
3465 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
3468 if ( snode->type == JSON_HASH ) {
3470 jsonIterator* order_itr = jsonNewIterator( snode );
3471 while ( (onode = jsonIteratorNext( order_itr )) ) {
3473 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
3476 char* direction = NULL;
3477 if ( onode->type == JSON_HASH ) {
3478 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
3479 string = searchFieldTransform(
3481 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
3485 growing_buffer* field_buf = buffer_init(16);
3486 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
3487 string = buffer_release(field_buf);
3490 if ( (_tmp = jsonObjectGetKeyConst( onode, "direction" )) ) {
3491 direction = jsonObjectToSimpleString(_tmp);
3492 if (!strncasecmp(direction, "d", 1)) {
3494 direction = " DESC";
3502 string = strdup(order_itr->key);
3503 direction = jsonObjectToSimpleString(onode);
3504 if (!strncasecmp(direction, "d", 1)) {
3506 direction = " DESC";
3516 buffer_add(order_buf, ", ");
3519 buffer_add(order_buf, string);
3523 buffer_add(order_buf, direction);
3528 jsonIteratorFree(order_itr);
3531 string = jsonObjectToSimpleString(snode);
3532 buffer_add(order_buf, string);
3539 jsonIteratorFree(class_itr);
3541 string = buffer_release(order_buf);
3544 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
3545 OSRF_BUFFER_ADD( sql_buf, string );
3551 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "limit" )) ){
3552 string = jsonObjectToSimpleString(_tmp);
3561 _tmp = jsonObjectGetKeyConst( order_hash, "offset" );
3563 string = jsonObjectToSimpleString(_tmp);
3573 if (defaultselhash) jsonObjectFree(defaultselhash);
3575 OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
3576 return buffer_release(sql_buf);
3579 int doJSONSearch ( osrfMethodContext* ctx ) {
3580 if(osrfMethodVerifyContext( ctx )) {
3581 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
3585 osrfLogDebug(OSRF_LOG_MARK, "Recieved query request");
3590 dbhandle = writehandle;
3592 jsonObject* hash = jsonObjectGetIndex(ctx->params, 0);
3596 if ( obj_is_true( jsonObjectGetKey( hash, "distinct" ) ) )
3597 flags |= SELECT_DISTINCT;
3599 if ( obj_is_true( jsonObjectGetKey( hash, "no_i18n" ) ) )
3600 flags |= DISABLE_I18N;
3602 osrfLogDebug(OSRF_LOG_MARK, "Building SQL ...");
3605 jsonObjectGetKey( hash, "select" ),
3606 jsonObjectGetKey( hash, "from" ),
3607 jsonObjectGetKey( hash, "where" ),
3608 jsonObjectGetKey( hash, "having" ),
3609 jsonObjectGetKey( hash, "order_by" ),
3610 jsonObjectGetKey( hash, "limit" ),
3611 jsonObjectGetKey( hash, "offset" ),
3620 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3621 dbi_result result = dbi_conn_query(dbhandle, sql);
3624 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3626 if (dbi_result_first_row(result)) {
3627 /* JSONify the result */
3628 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3631 jsonObject* return_val = oilsMakeJSONFromResult( result );
3632 osrfAppRespond( ctx, return_val );
3633 jsonObjectFree( return_val );
3634 } while (dbi_result_next_row(result));
3637 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
3640 osrfAppRespondComplete( ctx, NULL );
3642 /* clean up the query */
3643 dbi_result_free(result);
3647 osrfLogError(OSRF_LOG_MARK, "%s: Error with query [%s]", MODULENAME, sql);
3648 osrfAppSessionStatus(
3650 OSRF_STATUS_INTERNALSERVERERROR,
3651 "osrfMethodException",
3653 "Severe query error -- see error log for more details"
3661 static jsonObject* doFieldmapperSearch ( osrfMethodContext* ctx, osrfHash* meta,
3662 const jsonObject* params, int* err ) {
3665 dbhandle = writehandle;
3667 osrfHash* links = osrfHashGet(meta, "links");
3668 osrfHash* fields = osrfHashGet(meta, "fields");
3669 char* core_class = osrfHashGet(meta, "classname");
3670 char* pkey = osrfHashGet(meta, "primarykey");
3672 const jsonObject* _tmp;
3674 jsonObject* search_hash = jsonObjectGetIndex(params, 0);
3675 jsonObject* order_hash = jsonObjectGetIndex(params, 1);
3677 char* sql = buildSELECT( search_hash, order_hash, meta, ctx );
3679 osrfLogDebug(OSRF_LOG_MARK, "Problem building query, returning NULL");
3684 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3686 dbi_result result = dbi_conn_query(dbhandle, sql);
3687 if( NULL == result ) {
3688 osrfLogError(OSRF_LOG_MARK, "%s: Error retrieving %s with query [%s]",
3689 MODULENAME, osrfHashGet(meta, "fieldmapper"), sql);
3690 osrfAppSessionStatus(
3692 OSRF_STATUS_INTERNALSERVERERROR,
3693 "osrfMethodException",
3695 "Severe query error -- see error log for more details"
3702 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3705 jsonObject* res_list = jsonNewObjectType(JSON_ARRAY);
3706 osrfHash* dedup = osrfNewHash();
3708 if (dbi_result_first_row(result)) {
3709 /* JSONify the result */
3710 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3712 obj = oilsMakeFieldmapperFromResult( result, meta );
3713 char* pkey_val = oilsFMGetString( obj, pkey );
3714 if ( osrfHashGet( dedup, pkey_val ) ) {
3715 jsonObjectFree(obj);
3718 osrfHashSet( dedup, pkey_val, pkey_val );
3719 jsonObjectPush(res_list, obj);
3721 } while (dbi_result_next_row(result));
3723 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s",
3727 osrfHashFree(dedup);
3728 /* clean up the query */
3729 dbi_result_free(result);
3732 if (res_list->size && order_hash) {
3733 _tmp = jsonObjectGetKeyConst( order_hash, "flesh" );
3735 int x = (int)jsonObjectGetNumber(_tmp);
3736 if (x == -1 || x > max_flesh_depth) x = max_flesh_depth;
3738 const jsonObject* temp_blob;
3739 if ((temp_blob = jsonObjectGetKeyConst( order_hash, "flesh_fields" )) && x > 0) {
3741 jsonObject* flesh_blob = jsonObjectClone( temp_blob );
3742 const jsonObject* flesh_fields = jsonObjectGetKeyConst( flesh_blob, core_class );
3744 osrfStringArray* link_fields = NULL;
3747 if (flesh_fields->size == 1) {
3748 char* _t = jsonObjectToSimpleString( jsonObjectGetIndex( flesh_fields, 0 ) );
3749 if (!strcmp(_t,"*")) link_fields = osrfHashKeys( links );
3755 link_fields = osrfNewStringArray(1);
3756 jsonIterator* _i = jsonNewIterator( flesh_fields );
3757 while ((_f = jsonIteratorNext( _i ))) {
3758 osrfStringArrayAdd( link_fields, jsonObjectToSimpleString( _f ) );
3760 jsonIteratorFree(_i);
3765 jsonIterator* itr = jsonNewIterator( res_list );
3766 while ((cur = jsonIteratorNext( itr ))) {
3771 while ( (link_field = osrfStringArrayGetString(link_fields, i++)) ) {
3773 osrfLogDebug(OSRF_LOG_MARK, "Starting to flesh %s", link_field);
3775 osrfHash* kid_link = osrfHashGet(links, link_field);
3776 if (!kid_link) continue;
3778 osrfHash* field = osrfHashGet(fields, link_field);
3779 if (!field) continue;
3781 osrfHash* value_field = field;
3783 osrfHash* kid_idl = osrfHashGet(oilsIDL(), osrfHashGet(kid_link, "class"));
3784 if (!kid_idl) continue;
3786 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3787 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3790 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) { // might_have
3791 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3794 osrfStringArray* link_map = osrfHashGet( kid_link, "map" );
3796 if (link_map->size > 0) {
3797 jsonObject* _kid_key = jsonNewObjectType(JSON_ARRAY);
3800 jsonNewObject( osrfStringArrayGetString( link_map, 0 ) )
3805 osrfHashGet(kid_link, "class"),
3812 "Link field: %s, remote class: %s, fkey: %s, reltype: %s",
3813 osrfHashGet(kid_link, "field"),
3814 osrfHashGet(kid_link, "class"),
3815 osrfHashGet(kid_link, "key"),
3816 osrfHashGet(kid_link, "reltype")
3819 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
3820 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // search hash
3821 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // order/flesh hash
3823 osrfLogDebug(OSRF_LOG_MARK, "Creating dummy params object...");
3826 jsonObjectToSimpleString(
3829 atoi( osrfHashGet(value_field, "array_position") )
3834 osrfLogDebug(OSRF_LOG_MARK, "Nothing to search for!");
3839 jsonObjectGetIndex(fake_params, 0),
3840 osrfHashGet(kid_link, "key"),
3841 jsonNewObject( search_key )
3848 jsonObjectGetIndex(fake_params, 1),
3850 jsonNewNumberObject( (double)(x - 1 + link_map->size) )
3854 jsonObjectSetKey( jsonObjectGetIndex(fake_params, 1), "flesh_fields", jsonObjectClone(flesh_blob) );
3856 if (jsonObjectGetKeyConst(order_hash, "order_by")) {
3858 jsonObjectGetIndex(fake_params, 1),
3860 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "order_by"))
3864 if (jsonObjectGetKeyConst(order_hash, "select")) {
3866 jsonObjectGetIndex(fake_params, 1),
3868 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "select"))
3872 jsonObject* kids = doFieldmapperSearch(ctx, kid_idl, fake_params, err);
3875 jsonObjectFree( fake_params );
3876 osrfStringArrayFree(link_fields);
3877 jsonIteratorFree(itr);
3878 jsonObjectFree(res_list);
3879 jsonObjectFree(flesh_blob);
3883 osrfLogDebug(OSRF_LOG_MARK, "Search for %s return %d linked objects", osrfHashGet(kid_link, "class"), kids->size);
3885 jsonObject* X = NULL;
3886 if ( link_map->size > 0 && kids->size > 0 ) {
3888 kids = jsonNewObjectType(JSON_ARRAY);
3890 jsonObject* _k_node;
3891 jsonIterator* _k = jsonNewIterator( X );
3892 while ((_k_node = jsonIteratorNext( _k ))) {
3898 (unsigned long)atoi(
3904 osrfHashGet(kid_link, "class")
3908 osrfStringArrayGetString( link_map, 0 )
3917 jsonIteratorFree(_k);
3920 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_a" )) || !(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) {
3921 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3924 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3925 jsonObjectClone( jsonObjectGetIndex(kids, 0) )
3929 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3930 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3933 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3934 jsonObjectClone( kids )
3939 jsonObjectFree(kids);
3943 jsonObjectFree( kids );
3944 jsonObjectFree( fake_params );
3946 osrfLogDebug(OSRF_LOG_MARK, "Fleshing of %s complete", osrfHashGet(kid_link, "field"));
3947 osrfLogDebug(OSRF_LOG_MARK, "%s", jsonObjectToJSON(cur));
3951 jsonObjectFree( flesh_blob );
3952 osrfStringArrayFree(link_fields);
3953 jsonIteratorFree(itr);
3962 static jsonObject* doUpdate(osrfMethodContext* ctx, int* err ) {
3964 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3966 jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
3968 jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
3971 if (!verifyObjectClass(ctx, target)) {
3976 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3977 osrfAppSessionStatus(
3979 OSRF_STATUS_BADREQUEST,
3980 "osrfMethodException",
3982 "No active transaction -- required for UPDATE"
3988 // The following test is harmless but redundant. If a class is
3989 // readonly, we don't register an update method for it.
3990 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
3991 osrfAppSessionStatus(
3993 OSRF_STATUS_BADREQUEST,
3994 "osrfMethodException",
3996 "Cannot UPDATE readonly class"
4002 dbhandle = writehandle;
4004 char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
4006 // Set the last_xact_id
4007 int index = oilsIDL_ntop( target->classname, "last_xact_id" );
4009 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
4010 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
4013 char* pkey = osrfHashGet(meta, "primarykey");
4014 osrfHash* fields = osrfHashGet(meta, "fields");
4016 char* id = oilsFMGetString( target, pkey );
4020 "%s updating %s object with %s = %s",
4022 osrfHashGet(meta, "fieldmapper"),
4027 growing_buffer* sql = buffer_init(128);
4028 buffer_fadd(sql,"UPDATE %s SET", osrfHashGet(meta, "tablename"));
4033 osrfStringArray* field_list = osrfHashKeys( fields );
4034 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
4036 osrfHash* field = osrfHashGet( fields, field_name );
4038 if(!( strcmp( field_name, pkey ) )) continue;
4039 if( str_is_true( osrfHashGet(osrfHashGet(fields,field_name), "virtual") ) )
4042 const jsonObject* field_object = oilsFMGetObject( target, field_name );
4044 int value_is_numeric = 0; // boolean
4046 if (field_object && field_object->classname) {
4047 value = oilsFMGetString(
4049 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
4052 value = jsonObjectToSimpleString( field_object );
4053 if( field_object && JSON_NUMBER == field_object->type )
4054 value_is_numeric = 1;
4057 osrfLogDebug( OSRF_LOG_MARK, "Updating %s object with %s = %s", osrfHashGet(meta, "fieldmapper"), field_name, value);
4059 if (!field_object || field_object->type == JSON_NULL) {
4060 if ( !(!( strcmp( osrfHashGet(meta, "classname"), "au" ) ) && !( strcmp( field_name, "passwd" ) )) ) { // arg at the special case!
4061 if (first) first = 0;
4062 else OSRF_BUFFER_ADD_CHAR(sql, ',');
4063 buffer_fadd( sql, " %s = NULL", field_name );
4066 } else if ( value_is_numeric || !strcmp( get_primitive( field ), "number") ) {
4067 if (first) first = 0;
4068 else OSRF_BUFFER_ADD_CHAR(sql, ',');
4070 const char* numtype = get_datatype( field );
4071 if ( !strncmp( numtype, "INT", 3 ) ) {
4072 buffer_fadd( sql, " %s = %ld", field_name, atol(value) );
4073 } else if ( !strcmp( numtype, "NUMERIC" ) ) {
4074 buffer_fadd( sql, " %s = %f", field_name, atof(value) );
4077 osrfLogDebug( OSRF_LOG_MARK, "%s is of type %s", field_name, numtype );
4080 if ( dbi_conn_quote_string(dbhandle, &value) ) {
4081 if (first) first = 0;
4082 else OSRF_BUFFER_ADD_CHAR(sql, ',');
4083 buffer_fadd( sql, " %s = %s", field_name, value );
4086 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
4087 osrfAppSessionStatus(
4089 OSRF_STATUS_INTERNALSERVERERROR,
4090 "osrfMethodException",
4092 "Error quoting string -- please see the error log for more details"
4106 jsonObject* obj = jsonNewObject(id);
4108 if ( strcmp( get_primitive( osrfHashGet( osrfHashGet(meta, "fields"), pkey ) ), "number" ) )
4109 dbi_conn_quote_string(dbhandle, &id);
4111 buffer_fadd( sql, " WHERE %s = %s;", pkey, id );
4113 char* query = buffer_release(sql);
4114 osrfLogDebug(OSRF_LOG_MARK, "%s: Update SQL [%s]", MODULENAME, query);
4116 dbi_result result = dbi_conn_query(dbhandle, query);
4120 jsonObjectFree(obj);
4121 obj = jsonNewObject(NULL);
4124 "%s ERROR updating %s object with %s = %s",
4126 osrfHashGet(meta, "fieldmapper"),
4137 static jsonObject* doDelete(osrfMethodContext* ctx, int* err ) {
4139 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
4141 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
4142 osrfAppSessionStatus(
4144 OSRF_STATUS_BADREQUEST,
4145 "osrfMethodException",
4147 "No active transaction -- required for DELETE"
4153 // The following test is harmless but redundant. If a class is
4154 // readonly, we don't register a delete method for it.
4155 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
4156 osrfAppSessionStatus(
4158 OSRF_STATUS_BADREQUEST,
4159 "osrfMethodException",
4161 "Cannot DELETE readonly class"
4167 dbhandle = writehandle;
4171 char* pkey = osrfHashGet(meta, "primarykey");
4179 if (jsonObjectGetIndex(ctx->params, _obj_pos)->classname) {
4180 if (!verifyObjectClass(ctx, jsonObjectGetIndex( ctx->params, _obj_pos ))) {
4185 id = oilsFMGetString( jsonObjectGetIndex(ctx->params, _obj_pos), pkey );
4188 if (!verifyObjectPCRUD( ctx, NULL )) {
4193 id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, _obj_pos));
4198 "%s deleting %s object with %s = %s",
4200 osrfHashGet(meta, "fieldmapper"),
4205 obj = jsonNewObject(id);
4207 if ( strcmp( get_primitive( osrfHashGet( osrfHashGet(meta, "fields"), pkey ) ), "number" ) )
4208 dbi_conn_quote_string(writehandle, &id);
4210 dbi_result result = dbi_conn_queryf(writehandle, "DELETE FROM %s WHERE %s = %s;", osrfHashGet(meta, "tablename"), pkey, id);
4213 jsonObjectFree(obj);
4214 obj = jsonNewObject(NULL);
4217 "%s ERROR deleting %s object with %s = %s",
4219 osrfHashGet(meta, "fieldmapper"),
4232 static jsonObject* oilsMakeFieldmapperFromResult( dbi_result result, osrfHash* meta) {
4233 if(!(result && meta)) return jsonNULL;
4235 jsonObject* object = jsonNewObject(NULL);
4236 jsonObjectSetClass(object, osrfHashGet(meta, "classname"));
4238 osrfHash* fields = osrfHashGet(meta, "fields");
4240 osrfLogInternal(OSRF_LOG_MARK, "Setting object class to %s ", object->classname);
4244 char dt_string[256];
4248 int columnIndex = 1;
4250 unsigned short type;
4251 const char* columnName;
4253 /* cycle through the column list */
4254 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
4256 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
4258 fmIndex = -1; // reset the position
4260 /* determine the field type and storage attributes */
4261 type = dbi_result_get_field_type(result, columnName);
4262 attr = dbi_result_get_field_attribs(result, columnName);
4264 /* fetch the fieldmapper index */
4265 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
4267 if ( str_is_true( osrfHashGet(_f, "virtual") ) )
4270 const char* pos = (char*)osrfHashGet(_f, "array_position");
4271 if ( !pos ) continue;
4273 fmIndex = atoi( pos );
4274 osrfLogInternal(OSRF_LOG_MARK, "... Found column at position [%s]...", pos);
4279 if (dbi_result_field_is_null(result, columnName)) {
4280 jsonObjectSetIndex( object, fmIndex, jsonNewObject(NULL) );
4285 case DBI_TYPE_INTEGER :
4287 if( attr & DBI_INTEGER_SIZE8 )
4288 jsonObjectSetIndex( object, fmIndex,
4289 jsonNewNumberObject(dbi_result_get_longlong(result, columnName)));
4291 jsonObjectSetIndex( object, fmIndex,
4292 jsonNewNumberObject(dbi_result_get_int(result, columnName)));
4296 case DBI_TYPE_DECIMAL :
4297 jsonObjectSetIndex( object, fmIndex,
4298 jsonNewNumberObject(dbi_result_get_double(result, columnName)));
4301 case DBI_TYPE_STRING :
4307 jsonNewObject( dbi_result_get_string(result, columnName) )
4312 case DBI_TYPE_DATETIME :
4314 memset(dt_string, '\0', sizeof(dt_string));
4315 memset(&gmdt, '\0', sizeof(gmdt));
4317 _tmp_dt = dbi_result_get_datetime(result, columnName);
4320 if (!(attr & DBI_DATETIME_DATE)) {
4321 gmtime_r( &_tmp_dt, &gmdt );
4322 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
4323 } else if (!(attr & DBI_DATETIME_TIME)) {
4324 localtime_r( &_tmp_dt, &gmdt );
4325 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
4327 localtime_r( &_tmp_dt, &gmdt );
4328 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
4331 jsonObjectSetIndex( object, fmIndex, jsonNewObject(dt_string) );
4335 case DBI_TYPE_BINARY :
4336 osrfLogError( OSRF_LOG_MARK,
4337 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
4345 static jsonObject* oilsMakeJSONFromResult( dbi_result result ) {
4346 if(!result) return jsonNULL;
4348 jsonObject* object = jsonNewObject(NULL);
4351 char dt_string[256];
4355 int columnIndex = 1;
4357 unsigned short type;
4358 const char* columnName;
4360 /* cycle through the column list */
4361 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
4363 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
4365 fmIndex = -1; // reset the position
4367 /* determine the field type and storage attributes */
4368 type = dbi_result_get_field_type(result, columnName);
4369 attr = dbi_result_get_field_attribs(result, columnName);
4371 if (dbi_result_field_is_null(result, columnName)) {
4372 jsonObjectSetKey( object, columnName, jsonNewObject(NULL) );
4377 case DBI_TYPE_INTEGER :
4379 if( attr & DBI_INTEGER_SIZE8 )
4380 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_longlong(result, columnName)) );
4382 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_int(result, columnName)) );
4385 case DBI_TYPE_DECIMAL :
4386 jsonObjectSetKey( object, columnName, jsonNewNumberObject(dbi_result_get_double(result, columnName)) );
4389 case DBI_TYPE_STRING :
4390 jsonObjectSetKey( object, columnName, jsonNewObject(dbi_result_get_string(result, columnName)) );
4393 case DBI_TYPE_DATETIME :
4395 memset(dt_string, '\0', sizeof(dt_string));
4396 memset(&gmdt, '\0', sizeof(gmdt));
4398 _tmp_dt = dbi_result_get_datetime(result, columnName);
4401 if (!(attr & DBI_DATETIME_DATE)) {
4402 gmtime_r( &_tmp_dt, &gmdt );
4403 strftime(dt_string, sizeof(dt_string), "%T", &gmdt);
4404 } else if (!(attr & DBI_DATETIME_TIME)) {
4405 localtime_r( &_tmp_dt, &gmdt );
4406 strftime(dt_string, sizeof(dt_string), "%F", &gmdt);
4408 localtime_r( &_tmp_dt, &gmdt );
4409 strftime(dt_string, sizeof(dt_string), "%FT%T%z", &gmdt);
4412 jsonObjectSetKey( object, columnName, jsonNewObject(dt_string) );
4415 case DBI_TYPE_BINARY :
4416 osrfLogError( OSRF_LOG_MARK,
4417 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);
4425 // Interpret a string as true or false
4426 static int str_is_true( const char* str ) {
4427 if( NULL == str || strcasecmp( str, "true" ) )
4433 // Interpret a jsonObject as true or false
4434 static int obj_is_true( const jsonObject* obj ) {
4437 else switch( obj->type )
4445 if( strcasecmp( obj->value.s, "true" ) )
4449 case JSON_NUMBER : // Support 1/0 for perl's sake
4450 if( jsonObjectGetNumber( obj ) == 1.0 )
4459 // Translate a numeric code into a text string identifying a type of
4460 // jsonObject. To be used for building error messages.
4461 static const char* json_type( int code ) {
4467 return "JSON_ARRAY";
4469 return "JSON_STRING";
4471 return "JSON_NUMBER";
4477 return "(unrecognized)";
4481 // Extract the "primitive" attribute from an IDL field definition.
4482 // If we haven't initialized the app, then we must be running in
4483 // some kind of testbed. In that case, default to "string".
4484 static const char* get_primitive( osrfHash* field ) {
4485 const char* s = osrfHashGet( field, "primitive" );
4487 if( child_initialized )
4490 "%s ERROR No \"datatype\" attribute for field \"%s\"",
4492 osrfHashGet( field, "name" )
4500 // Extract the "datatype" attribute from an IDL field definition.
4501 // If we haven't initialized the app, then we must be running in
4502 // some kind of testbed. In that case, default to to NUMERIC,
4503 // since we look at the datatype only for numbers.
4504 static const char* get_datatype( osrfHash* field ) {
4505 const char* s = osrfHashGet( field, "datatype" );
4507 if( child_initialized )
4510 "%s ERROR No \"datatype\" attribute for field \"%s\"",
4512 osrfHashGet( field, "name" )