1 #include "opensrf/osrf_application.h"
2 #include "opensrf/osrf_settings.h"
3 #include "opensrf/osrf_message.h"
4 #include "opensrf/utils.h"
5 #include "opensrf/osrf_json.h"
6 #include "opensrf/log.h"
7 #include "openils/oils_utils.h"
16 # define MODULENAME "open-ils.reporter-store"
19 # define MODULENAME "open-ils.pcrud"
21 # define MODULENAME "open-ils.cstore"
26 #define DISABLE_I18N 2
27 #define SELECT_DISTINCT 1
31 int osrfAppChildInit();
32 int osrfAppInitialize();
33 void osrfAppChildExit();
35 static int verifyObjectClass ( osrfMethodContext*, const jsonObject* );
37 int beginTransaction ( osrfMethodContext* );
38 int commitTransaction ( osrfMethodContext* );
39 int rollbackTransaction ( osrfMethodContext* );
41 int setSavepoint ( osrfMethodContext* );
42 int releaseSavepoint ( osrfMethodContext* );
43 int rollbackSavepoint ( osrfMethodContext* );
45 int doJSONSearch ( osrfMethodContext* );
47 int dispatchCRUDMethod ( osrfMethodContext* );
48 static jsonObject* doCreate ( osrfMethodContext*, int* );
49 static jsonObject* doRetrieve ( osrfMethodContext*, int* );
50 static jsonObject* doUpdate ( osrfMethodContext*, int* );
51 static jsonObject* doDelete ( osrfMethodContext*, int* );
52 static jsonObject* doFieldmapperSearch ( osrfMethodContext*, osrfHash*,
53 const jsonObject*, int* );
54 static jsonObject* oilsMakeFieldmapperFromResult( dbi_result, osrfHash* );
55 static jsonObject* oilsMakeJSONFromResult( dbi_result );
57 static char* searchWriteSimplePredicate ( const char*, osrfHash*,
58 const char*, const char*, const char* );
59 static char* searchSimplePredicate ( const char*, const char*, osrfHash*, const jsonObject* );
60 static char* searchFunctionPredicate ( const char*, osrfHash*, const jsonObject*, const char* );
61 static char* searchFieldTransform ( const char*, osrfHash*, const jsonObject*);
62 static char* searchFieldTransformPredicate ( const char*, osrfHash*, jsonObject*, const char* );
63 static char* searchBETWEENPredicate ( const char*, osrfHash*, jsonObject* );
64 static char* searchINPredicate ( const char*, osrfHash*,
65 jsonObject*, const char*, osrfMethodContext* );
66 static char* searchPredicate ( const char*, osrfHash*, jsonObject*, osrfMethodContext* );
67 static char* searchJOIN ( const jsonObject*, osrfHash* );
68 static char* searchWHERE ( const jsonObject*, osrfHash*, int, osrfMethodContext* );
69 static char* buildSELECT ( jsonObject*, jsonObject*, osrfHash*, osrfMethodContext* );
71 char* SELECT ( osrfMethodContext*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, jsonObject*, int );
73 void userDataFree( void* );
74 static void sessionDataFree( char*, void* );
75 static char* getSourceDefinition( osrfHash* );
76 static int str_is_true( const char* str );
77 static int obj_is_true( const jsonObject* obj );
78 static const char* json_type( int code );
79 static const char* get_primitive( osrfHash* field );
80 static const char* get_datatype( osrfHash* field );
83 static jsonObject* verifyUserPCRUD( osrfMethodContext* );
84 static int verifyObjectPCRUD( osrfMethodContext*, const jsonObject* );
87 static int child_initialized = 0; /* boolean */
89 static dbi_conn writehandle; /* our MASTER db connection */
90 static dbi_conn dbhandle; /* our CURRENT db connection */
91 //static osrfHash * readHandles;
92 static jsonObject* jsonNULL = NULL; //
93 static int max_flesh_depth = 100;
95 /* called when this process is about to exit */
96 void osrfAppChildExit() {
97 osrfLogDebug(OSRF_LOG_MARK, "Child is exiting, disconnecting from database...");
100 if (writehandle == dbhandle) same = 1;
102 dbi_conn_query(writehandle, "ROLLBACK;");
103 dbi_conn_close(writehandle);
106 if (dbhandle && !same)
107 dbi_conn_close(dbhandle);
109 // XXX add cleanup of readHandles whenever that gets used
114 int osrfAppInitialize() {
116 osrfLogInfo(OSRF_LOG_MARK, "Initializing the CStore Server...");
117 osrfLogInfo(OSRF_LOG_MARK, "Finding XML file...");
119 if (!oilsIDLInit( osrf_settings_host_value("/IDL") )) return 1; /* return non-zero to indicate error */
121 growing_buffer* method_name = buffer_init(64);
123 // Generic search thingy
124 buffer_add(method_name, MODULENAME);
125 buffer_add(method_name, ".json_query");
126 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
127 "doJSONSearch", "", 1, OSRF_METHOD_STREAMING );
130 // first we register all the transaction and savepoint methods
131 buffer_reset(method_name);
132 OSRF_BUFFER_ADD(method_name, MODULENAME);
133 OSRF_BUFFER_ADD(method_name, ".transaction.begin");
134 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
135 "beginTransaction", "", 0, 0 );
137 buffer_reset(method_name);
138 OSRF_BUFFER_ADD(method_name, MODULENAME);
139 OSRF_BUFFER_ADD(method_name, ".transaction.commit");
140 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
141 "commitTransaction", "", 0, 0 );
143 buffer_reset(method_name);
144 OSRF_BUFFER_ADD(method_name, MODULENAME);
145 OSRF_BUFFER_ADD(method_name, ".transaction.rollback");
146 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
147 "rollbackTransaction", "", 0, 0 );
149 buffer_reset(method_name);
150 OSRF_BUFFER_ADD(method_name, MODULENAME);
151 OSRF_BUFFER_ADD(method_name, ".savepoint.set");
152 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
153 "setSavepoint", "", 1, 0 );
155 buffer_reset(method_name);
156 OSRF_BUFFER_ADD(method_name, MODULENAME);
157 OSRF_BUFFER_ADD(method_name, ".savepoint.release");
158 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
159 "releaseSavepoint", "", 1, 0 );
161 buffer_reset(method_name);
162 OSRF_BUFFER_ADD(method_name, MODULENAME);
163 OSRF_BUFFER_ADD(method_name, ".savepoint.rollback");
164 osrfAppRegisterMethod( MODULENAME, OSRF_BUFFER_C_STR(method_name),
165 "rollbackSavepoint", "", 1, 0 );
167 buffer_free(method_name);
169 static const char* global_method[] = {
177 const int global_method_count
178 = sizeof( global_method ) / sizeof ( global_method[0] );
182 osrfStringArray* classes = osrfHashKeys( oilsIDL() );
183 osrfLogDebug(OSRF_LOG_MARK, "%d classes loaded", classes->size );
184 osrfLogDebug(OSRF_LOG_MARK,
185 "At least %d methods will be generated", classes->size * global_method_count);
187 while ( (classname = osrfStringArrayGetString(classes, c_index++)) ) {
188 osrfLogInfo(OSRF_LOG_MARK, "Generating class methods for %s", classname);
190 osrfHash* idlClass = osrfHashGet(oilsIDL(), classname);
192 if (!osrfStringArrayContains( osrfHashGet(idlClass, "controller"), MODULENAME )) {
193 osrfLogInfo(OSRF_LOG_MARK, "%s is not listed as a controller for %s, moving on", MODULENAME, classname);
197 if ( str_is_true( osrfHashGet(idlClass, "virtual") ) ) {
198 osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
202 // Look up some other attributes of the current class
203 const char* idlClass_fieldmapper = osrfHashGet(idlClass, "fieldmapper");
204 const char* readonly = osrfHashGet(idlClass, "readonly");
206 osrfHash* idlClass_permacrud = osrfHashGet(idlClass, "permacrud");
210 for( i = 0; i < global_method_count; ++i ) {
211 const char* method_type = global_method[ i ];
212 osrfLogDebug(OSRF_LOG_MARK,
213 "Using files to build %s class methods for %s", method_type, classname);
215 if (!idlClass_fieldmapper) continue;
218 if (!idlClass_permacrud) continue;
220 const char* tmp_method = method_type;
221 if ( *tmp_method == 'i' || *tmp_method == 's') {
222 tmp_method = "retrieve";
224 if (!osrfHashGet( idlClass_permacrud, tmp_method )) continue;
227 if ( str_is_true( readonly ) &&
228 ( *method_type == 'c' || *method_type == 'u' || *method_type == 'd')
231 osrfHash* method_meta = osrfNewHash();
232 osrfHashSet(method_meta, idlClass, "class");
234 method_name = buffer_init(64);
236 buffer_fadd(method_name, "%s.%s.%s", MODULENAME, method_type, classname);
240 char* _fm = strdup( idlClass_fieldmapper );
241 part = strtok_r(_fm, ":", &st_tmp);
243 buffer_fadd(method_name, "%s.direct.%s", MODULENAME, part);
245 while ((part = strtok_r(NULL, ":", &st_tmp))) {
246 OSRF_BUFFER_ADD_CHAR(method_name, '.');
247 OSRF_BUFFER_ADD(method_name, part);
249 OSRF_BUFFER_ADD_CHAR(method_name, '.');
250 OSRF_BUFFER_ADD(method_name, method_type);
254 char* method = buffer_release(method_name);
256 osrfHashSet( method_meta, method, "methodname" );
257 osrfHashSet( method_meta, strdup(method_type), "methodtype" );
260 if (*method_type == 'i' || *method_type == 's') {
261 flags = flags | OSRF_METHOD_STREAMING;
264 osrfAppRegisterExtendedMethod(
267 "dispatchCRUDMethod",
281 static char* getSourceDefinition( osrfHash* class ) {
283 char* tabledef = osrfHashGet(class, "tablename");
286 tabledef = strdup(tabledef);
288 tabledef = osrfHashGet(class, "source_definition");
290 growing_buffer* tablebuf = buffer_init(128);
291 buffer_fadd( tablebuf, "(%s)", tabledef );
292 tabledef = buffer_release(tablebuf);
294 const char* classname = osrfHashGet( class, "classname" );
299 "%s ERROR No tablename or source_definition for class \"%s\"",
310 * Connects to the database
312 int osrfAppChildInit() {
314 osrfLogDebug(OSRF_LOG_MARK, "Attempting to initialize libdbi...");
315 dbi_initialize(NULL);
316 osrfLogDebug(OSRF_LOG_MARK, "... libdbi initialized.");
318 char* driver = osrf_settings_host_value("/apps/%s/app_settings/driver", MODULENAME);
319 char* user = osrf_settings_host_value("/apps/%s/app_settings/database/user", MODULENAME);
320 char* host = osrf_settings_host_value("/apps/%s/app_settings/database/host", MODULENAME);
321 char* port = osrf_settings_host_value("/apps/%s/app_settings/database/port", MODULENAME);
322 char* db = osrf_settings_host_value("/apps/%s/app_settings/database/db", MODULENAME);
323 char* pw = osrf_settings_host_value("/apps/%s/app_settings/database/pw", MODULENAME);
324 char* md = osrf_settings_host_value("/apps/%s/app_settings/max_query_recursion", MODULENAME);
326 osrfLogDebug(OSRF_LOG_MARK, "Attempting to load the database driver [%s]...", driver);
327 writehandle = dbi_conn_new(driver);
330 osrfLogError(OSRF_LOG_MARK, "Error loading database driver [%s]", driver);
333 osrfLogDebug(OSRF_LOG_MARK, "Database driver [%s] seems OK", driver);
335 osrfLogInfo(OSRF_LOG_MARK, "%s connecting to database. host=%s, "
336 "port=%s, user=%s, pw=%s, db=%s", MODULENAME, host, port, user, pw, db );
338 if(host) dbi_conn_set_option(writehandle, "host", host );
339 if(port) dbi_conn_set_option_numeric( writehandle, "port", atoi(port) );
340 if(user) dbi_conn_set_option(writehandle, "username", user);
341 if(pw) dbi_conn_set_option(writehandle, "password", pw );
342 if(db) dbi_conn_set_option(writehandle, "dbname", db );
344 if(md) max_flesh_depth = atoi(md);
345 if(max_flesh_depth < 0) max_flesh_depth = 1;
346 if(max_flesh_depth > 1000) max_flesh_depth = 1000;
355 if (dbi_conn_connect(writehandle) < 0) {
357 if (dbi_conn_connect(writehandle) < 0) {
358 dbi_conn_error(writehandle, &err);
359 osrfLogError( OSRF_LOG_MARK, "Error connecting to database: %s", err);
364 osrfLogInfo(OSRF_LOG_MARK, "%s successfully connected to the database", MODULENAME);
370 osrfStringArray* classes = osrfHashKeys( oilsIDL() );
372 while ( (classname = osrfStringArrayGetString(classes, i++)) ) {
373 osrfHash* class = osrfHashGet( oilsIDL(), classname );
374 osrfHash* fields = osrfHashGet( class, "fields" );
376 if( str_is_true( osrfHashGet(class, "virtual") ) ) {
377 osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
381 char* tabledef = getSourceDefinition(class);
383 tabledef = strdup( "(null)" );
385 growing_buffer* sql_buf = buffer_init(32);
386 buffer_fadd( sql_buf, "SELECT * FROM %s AS x WHERE 1=0;", tabledef );
390 char* sql = buffer_release(sql_buf);
391 osrfLogDebug(OSRF_LOG_MARK, "%s Investigatory SQL = %s", MODULENAME, sql);
393 dbi_result result = dbi_conn_query(writehandle, sql);
399 const char* columnName;
401 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
403 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
405 /* fetch the fieldmapper index */
406 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
408 osrfLogDebug(OSRF_LOG_MARK, "Found [%s] in IDL hash...", (char*)columnName);
410 /* determine the field type and storage attributes */
411 type = dbi_result_get_field_type(result, columnName);
412 attr = dbi_result_get_field_attribs(result, columnName);
416 case DBI_TYPE_INTEGER :
418 if ( !osrfHashGet(_f, "primitive") )
419 osrfHashSet(_f,"number", "primitive");
421 if( attr & DBI_INTEGER_SIZE8 )
422 osrfHashSet(_f,"INT8", "datatype");
424 osrfHashSet(_f,"INT", "datatype");
427 case DBI_TYPE_DECIMAL :
428 if ( !osrfHashGet(_f, "primitive") )
429 osrfHashSet(_f,"number", "primitive");
431 osrfHashSet(_f,"NUMERIC", "datatype");
434 case DBI_TYPE_STRING :
435 if ( !osrfHashGet(_f, "primitive") )
436 osrfHashSet(_f,"string", "primitive");
437 osrfHashSet(_f,"TEXT", "datatype");
440 case DBI_TYPE_DATETIME :
441 if ( !osrfHashGet(_f, "primitive") )
442 osrfHashSet(_f,"string", "primitive");
444 osrfHashSet(_f,"TIMESTAMP", "datatype");
447 case DBI_TYPE_BINARY :
448 if ( !osrfHashGet(_f, "primitive") )
449 osrfHashSet(_f,"string", "primitive");
451 osrfHashSet(_f,"BYTEA", "datatype");
456 "Setting [%s] to primitive [%s] and datatype [%s]...",
458 osrfHashGet(_f, "primitive"),
459 osrfHashGet(_f, "datatype")
463 dbi_result_free(result);
465 osrfLogDebug(OSRF_LOG_MARK, "No data found for class [%s]...", (char*)classname);
469 osrfStringArrayFree(classes);
471 child_initialized = 1;
476 This function is a sleazy hack intended *only* for testing and
477 debugging. Any real server process should initialize the
478 database connection by calling osrfAppChildInit().
480 void set_cstore_dbi_conn( dbi_conn conn ) {
481 dbhandle = writehandle = conn;
484 void userDataFree( void* blob ) {
485 osrfHashFree( (osrfHash*)blob );
489 static void sessionDataFree( char* key, void* item ) {
490 if (!(strcmp(key,"xact_id"))) {
492 dbi_conn_query(writehandle, "ROLLBACK;");
499 int beginTransaction ( osrfMethodContext* ctx ) {
500 if(osrfMethodVerifyContext( ctx )) {
501 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
506 jsonObject* user = verifyUserPCRUD( ctx );
507 if (!user) return -1;
508 jsonObjectFree(user);
511 dbi_result result = dbi_conn_query(writehandle, "START TRANSACTION;");
513 osrfLogError(OSRF_LOG_MARK, "%s: Error starting transaction", MODULENAME );
514 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error starting transaction" );
517 jsonObject* ret = jsonNewObject(ctx->session->session_id);
518 osrfAppRespondComplete( ctx, ret );
521 if (!ctx->session->userData) {
522 ctx->session->userData = osrfNewHash();
523 osrfHashSetCallback((osrfHash*)ctx->session->userData, &sessionDataFree);
526 osrfHashSet( (osrfHash*)ctx->session->userData, strdup( ctx->session->session_id ), "xact_id" );
527 ctx->session->userDataFree = &userDataFree;
533 int setSavepoint ( osrfMethodContext* ctx ) {
534 if(osrfMethodVerifyContext( ctx )) {
535 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
542 jsonObject* user = verifyUserPCRUD( ctx );
543 if (!user) return -1;
544 jsonObjectFree(user);
547 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
548 osrfAppSessionStatus(
550 OSRF_STATUS_INTERNALSERVERERROR,
551 "osrfMethodException",
553 "No active transaction -- required for savepoints"
558 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
560 dbi_result result = dbi_conn_queryf(writehandle, "SAVEPOINT \"%s\";", spName);
564 "%s: Error creating savepoint %s in transaction %s",
567 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
569 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error creating savepoint" );
573 jsonObject* ret = jsonNewObject(spName);
574 osrfAppRespondComplete( ctx, ret );
581 int releaseSavepoint ( osrfMethodContext* ctx ) {
582 if(osrfMethodVerifyContext( ctx )) {
583 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
590 jsonObject* user = verifyUserPCRUD( ctx );
591 if (!user) return -1;
592 jsonObjectFree(user);
595 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
596 osrfAppSessionStatus(
598 OSRF_STATUS_INTERNALSERVERERROR,
599 "osrfMethodException",
601 "No active transaction -- required for savepoints"
606 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
608 dbi_result result = dbi_conn_queryf(writehandle, "RELEASE SAVEPOINT \"%s\";", spName);
612 "%s: Error releasing savepoint %s in transaction %s",
615 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
617 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error releasing savepoint" );
621 jsonObject* ret = jsonNewObject(spName);
622 osrfAppRespondComplete( ctx, ret );
629 int rollbackSavepoint ( osrfMethodContext* ctx ) {
630 if(osrfMethodVerifyContext( ctx )) {
631 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
638 jsonObject* user = verifyUserPCRUD( ctx );
639 if (!user) return -1;
640 jsonObjectFree(user);
643 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
644 osrfAppSessionStatus(
646 OSRF_STATUS_INTERNALSERVERERROR,
647 "osrfMethodException",
649 "No active transaction -- required for savepoints"
654 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, spNamePos));
656 dbi_result result = dbi_conn_queryf(writehandle, "ROLLBACK TO SAVEPOINT \"%s\";", spName);
660 "%s: Error rolling back savepoint %s in transaction %s",
663 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
665 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back savepoint" );
669 jsonObject* ret = jsonNewObject(spName);
670 osrfAppRespondComplete( ctx, ret );
677 int commitTransaction ( osrfMethodContext* ctx ) {
678 if(osrfMethodVerifyContext( ctx )) {
679 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
684 jsonObject* user = verifyUserPCRUD( ctx );
685 if (!user) return -1;
686 jsonObjectFree(user);
689 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
690 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to commit" );
694 dbi_result result = dbi_conn_query(writehandle, "COMMIT;");
696 osrfLogError(OSRF_LOG_MARK, "%s: Error committing transaction", MODULENAME );
697 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error committing transaction" );
700 osrfHashRemove(ctx->session->userData, "xact_id");
701 jsonObject* ret = jsonNewObject(ctx->session->session_id);
702 osrfAppRespondComplete( ctx, ret );
708 int rollbackTransaction ( osrfMethodContext* ctx ) {
709 if(osrfMethodVerifyContext( ctx )) {
710 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
715 jsonObject* user = verifyUserPCRUD( ctx );
716 if (!user) return -1;
717 jsonObjectFree(user);
720 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
721 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to roll back" );
725 dbi_result result = dbi_conn_query(writehandle, "ROLLBACK;");
727 osrfLogError(OSRF_LOG_MARK, "%s: Error rolling back transaction", MODULENAME );
728 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back transaction" );
731 osrfHashRemove(ctx->session->userData, "xact_id");
732 jsonObject* ret = jsonNewObject(ctx->session->session_id);
733 osrfAppRespondComplete( ctx, ret );
739 int dispatchCRUDMethod ( osrfMethodContext* ctx ) {
740 if(osrfMethodVerifyContext( ctx )) {
741 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
745 osrfHash* meta = (osrfHash*) ctx->method->userData;
746 osrfHash* class_obj = osrfHashGet( meta, "class" );
750 const char* methodtype = osrfHashGet(meta, "methodtype");
751 jsonObject * obj = NULL;
753 if (!strcmp(methodtype, "create")) {
754 obj = doCreate(ctx, &err);
755 osrfAppRespondComplete( ctx, obj );
757 else if (!strcmp(methodtype, "retrieve")) {
758 obj = doRetrieve(ctx, &err);
759 osrfAppRespondComplete( ctx, obj );
761 else if (!strcmp(methodtype, "update")) {
762 obj = doUpdate(ctx, &err);
763 osrfAppRespondComplete( ctx, obj );
765 else if (!strcmp(methodtype, "delete")) {
766 obj = doDelete(ctx, &err);
767 osrfAppRespondComplete( ctx, obj );
769 else if (!strcmp(methodtype, "search")) {
771 jsonObject* _p = jsonObjectClone( ctx->params );
774 _p = jsonParseString("[]");
775 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 1)));
776 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 2)));
779 obj = doFieldmapperSearch(ctx, class_obj, _p, &err);
785 jsonIterator* itr = jsonNewIterator( obj );
786 while ((cur = jsonIteratorNext( itr ))) {
788 if(!verifyObjectPCRUD(ctx, cur)) continue;
790 osrfAppRespond( ctx, cur );
792 jsonIteratorFree(itr);
793 osrfAppRespondComplete( ctx, NULL );
795 } else if (!strcmp(methodtype, "id_list")) {
797 jsonObject* _p = jsonObjectClone( ctx->params );
800 _p = jsonParseString("[]");
801 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 1)));
802 jsonObjectPush(_p, jsonObjectClone(jsonObjectGetIndex(ctx->params, 2)));
805 if (jsonObjectGetIndex( _p, 1 )) {
806 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "select" );
807 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "no_i18n" );
808 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh" );
809 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh_columns" );
811 jsonObjectSetIndex( _p, 1, jsonNewObjectType(JSON_HASH) );
814 jsonObjectSetKey( jsonObjectGetIndex( _p, 1 ), "no_i18n", jsonNewBoolObject( 1 ) );
817 jsonObjectGetIndex( _p, 1 ),
820 "{ \"%s\":[\"%s\"] }",
821 osrfHashGet( class_obj, "classname" ),
822 osrfHashGet( class_obj, "primarykey" )
826 obj = doFieldmapperSearch(ctx, class_obj, _p, &err);
832 jsonIterator* itr = jsonNewIterator( obj );
833 while ((cur = jsonIteratorNext( itr ))) {
835 if(!verifyObjectPCRUD(ctx, cur)) continue;
839 oilsFMGetObject( cur, osrfHashGet( class_obj, "primarykey" ) )
842 jsonIteratorFree(itr);
843 osrfAppRespondComplete( ctx, NULL );
846 osrfAppRespondComplete( ctx, obj );
854 static int verifyObjectClass ( osrfMethodContext* ctx, const jsonObject* param ) {
857 osrfHash* meta = (osrfHash*) ctx->method->userData;
858 osrfHash* class = osrfHashGet( meta, "class" );
860 if (!param->classname || (strcmp( osrfHashGet(class, "classname"), param->classname ))) {
862 growing_buffer* msg = buffer_init(128);
865 "%s: %s method for type %s was passed a %s",
867 osrfHashGet(meta, "methodtype"),
868 osrfHashGet(class, "classname"),
872 char* m = buffer_release(msg);
873 osrfAppSessionStatus( ctx->session, OSRF_STATUS_BADREQUEST, "osrfMethodException", ctx->request, m );
881 ret = verifyObjectPCRUD( ctx, param );
889 static jsonObject* verifyUserPCRUD( osrfMethodContext* ctx ) {
890 char* auth = jsonObjectToSimpleString( jsonObjectGetIndex( ctx->params, 0 ) );
891 jsonObject* auth_object = jsonNewObject(auth);
892 jsonObject* user = oilsUtilsQuickReq("open-ils.auth","open-ils.auth.session.retrieve", auth_object);
893 jsonObjectFree(auth_object);
895 if (!user->classname || strcmp(user->classname, "au")) {
897 growing_buffer* msg = buffer_init(128);
900 "%s: permacrud received a bad auth token: %s",
905 char* m = buffer_release(msg);
906 osrfAppSessionStatus( ctx->session, OSRF_STATUS_UNAUTHORIZED, "osrfMethodException", ctx->request, m );
909 jsonObjectFree(user);
918 static int verifyObjectPCRUD ( osrfMethodContext* ctx, const jsonObject* obj ) {
920 dbhandle = writehandle;
922 osrfHash* meta = (osrfHash*) ctx->method->userData;
923 osrfHash* class = osrfHashGet( meta, "class" );
924 char* method_type = strdup( osrfHashGet(meta, "methodtype") );
927 if ( ( *method_type == 's' || *method_type == 'i' ) ) {
929 method_type = strdup("retrieve"); // search and id_list are equivelant to retrieve for this
930 } else if ( *method_type == 'u' || *method_type == 'd' ) {
931 fetch = 1; // MUST go to the db for the object for update and delete
934 osrfHash* pcrud = osrfHashGet( osrfHashGet(class, "permacrud"), method_type );
938 // No permacrud for this method type on this class
940 growing_buffer* msg = buffer_init(128);
943 "%s: %s on class %s has no permacrud IDL entry",
945 osrfHashGet(meta, "methodtype"),
946 osrfHashGet(class, "classname")
949 char* m = buffer_release(msg);
950 osrfAppSessionStatus( ctx->session, OSRF_STATUS_FORBIDDEN, "osrfMethodException", ctx->request, m );
957 jsonObject* user = verifyUserPCRUD( ctx );
960 int userid = atoi( oilsFMGetString( user, "id" ) );
961 jsonObjectFree(user);
963 osrfStringArray* permission = osrfHashGet(pcrud, "permission");
964 osrfStringArray* local_context = osrfHashGet(pcrud, "local_context");
965 osrfHash* foreign_context = osrfHashGet(pcrud, "foreign_context");
967 osrfStringArray* context_org_array = osrfNewStringArray(1);
970 char* pkey_value = NULL;
971 if ( str_is_true( osrfHashGet(pcrud, "global_required") ) ) {
972 osrfLogDebug( OSRF_LOG_MARK, "global-level permissions required, fetching top of the org tree" );
974 // check for perm at top of org tree
975 jsonObject* _tmp_params = jsonParseString("[{\"parent_ou\":null}]");
976 jsonObject* _list = doFieldmapperSearch(ctx, osrfHashGet( oilsIDL(), "aou" ), _tmp_params, &err);
978 jsonObject* _tree_top = jsonObjectGetIndex(_list, 0);
981 jsonObjectFree(_tmp_params);
982 jsonObjectFree(_list);
984 growing_buffer* msg = buffer_init(128);
985 OSRF_BUFFER_ADD( msg, MODULENAME );
986 OSRF_BUFFER_ADD( msg,
987 ": Internal error, could not find the top of the org tree (parent_ou = NULL)" );
989 char* m = buffer_release(msg);
990 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, m );
996 osrfStringArrayAdd( context_org_array, oilsFMGetString( _tree_top, "id" ) );
997 osrfLogDebug( OSRF_LOG_MARK, "top of the org tree is %s", osrfStringArrayGetString(context_org_array, 0) );
999 jsonObjectFree(_tmp_params);
1000 jsonObjectFree(_list);
1003 osrfLogDebug( OSRF_LOG_MARK, "global-level permissions not required, fetching context org ids" );
1004 char* pkey = osrfHashGet(class, "primarykey");
1005 jsonObject *param = NULL;
1007 if (obj->classname) {
1008 pkey_value = oilsFMGetString( obj, pkey );
1009 if (!fetch) param = jsonObjectClone(obj);
1010 osrfLogDebug( OSRF_LOG_MARK, "Object supplied, using primary key value of %s", pkey_value );
1012 pkey_value = jsonObjectToSimpleString( obj );
1014 osrfLogDebug( OSRF_LOG_MARK, "Object not supplied, using primary key value of %s and retrieving from the database", pkey_value );
1018 jsonObject* _tmp_params = jsonParseStringFmt("[{\"%s\":\"%s\"}]", pkey, pkey_value);
1019 jsonObject* _list = doFieldmapperSearch(
1026 param = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1028 jsonObjectFree(_tmp_params);
1029 jsonObjectFree(_list);
1033 osrfLogDebug( OSRF_LOG_MARK, "Object not found in the database with primary key %s of %s", pkey, pkey_value );
1035 growing_buffer* msg = buffer_init(128);
1038 "%s: no object found with primary key %s of %s",
1044 char* m = buffer_release(msg);
1045 osrfAppSessionStatus(
1047 OSRF_STATUS_INTERNALSERVERERROR,
1048 "osrfMethodException",
1054 if (pkey_value) free(pkey_value);
1059 if (local_context->size > 0) {
1060 osrfLogDebug( OSRF_LOG_MARK, "%d class-local context field(s) specified", local_context->size);
1062 char* lcontext = NULL;
1063 while ( (lcontext = osrfStringArrayGetString(local_context, i++)) ) {
1064 osrfStringArrayAdd( context_org_array, oilsFMGetString( param, lcontext ) );
1067 "adding class-local field %s (value: %s) to the context org list",
1069 osrfStringArrayGetString(context_org_array, context_org_array->size - 1)
1074 osrfStringArray* class_list;
1076 if (foreign_context) {
1077 class_list = osrfHashKeys( foreign_context );
1078 osrfLogDebug( OSRF_LOG_MARK, "%d foreign context classes(s) specified", class_list->size);
1080 if (class_list->size > 0) {
1083 char* class_name = NULL;
1084 while ( (class_name = osrfStringArrayGetString(class_list, i++)) ) {
1085 osrfHash* fcontext = osrfHashGet(foreign_context, class_name);
1089 "%d foreign context fields(s) specified for class %s",
1090 ((osrfStringArray*)osrfHashGet(fcontext,"context"))->size,
1094 char* foreign_pkey = osrfHashGet(fcontext, "field");
1095 char* foreign_pkey_value = oilsFMGetString(param, osrfHashGet(fcontext, "fkey"));
1097 jsonObject* _tmp_params = jsonParseStringFmt(
1098 "[{\"%s\":\"%s\"}]",
1103 jsonObject* _list = doFieldmapperSearch(
1105 osrfHashGet( oilsIDL(), class_name ),
1110 jsonObject* _fparam = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1111 jsonObjectFree(_tmp_params);
1112 jsonObjectFree(_list);
1114 osrfStringArray* jump_list = osrfHashGet(fcontext, "jump");
1116 if (_fparam && jump_list) {
1119 while ( (flink = osrfStringArrayGetString(jump_list, k++)) && _fparam ) {
1120 free(foreign_pkey_value);
1122 osrfHash* foreign_link_hash = oilsIDLFindPath( "/%s/links/%s", _fparam->classname, flink );
1124 foreign_pkey_value = oilsFMGetString(_fparam, flink);
1125 foreign_pkey = osrfHashGet( foreign_link_hash, "key" );
1127 _tmp_params = jsonParseStringFmt(
1128 "[{\"%s\":\"%s\"}]",
1133 _list = doFieldmapperSearch(
1135 osrfHashGet( oilsIDL(), osrfHashGet( foreign_link_hash, "class" ) ),
1140 _fparam = jsonObjectClone(jsonObjectGetIndex(_list, 0));
1141 jsonObjectFree(_tmp_params);
1142 jsonObjectFree(_list);
1149 growing_buffer* msg = buffer_init(128);
1152 "%s: no object found with primary key %s of %s",
1158 char* m = buffer_release(msg);
1159 osrfAppSessionStatus(
1161 OSRF_STATUS_INTERNALSERVERERROR,
1162 "osrfMethodException",
1168 osrfStringArrayFree(class_list);
1169 free(foreign_pkey_value);
1170 jsonObjectFree(param);
1175 free(foreign_pkey_value);
1178 char* foreign_field = NULL;
1179 while ( (foreign_field = osrfStringArrayGetString(osrfHashGet(fcontext,"context"), j++)) ) {
1180 osrfStringArrayAdd( context_org_array, oilsFMGetString( _fparam, foreign_field ) );
1183 "adding foreign class %s field %s (value: %s) to the context org list",
1186 osrfStringArrayGetString(context_org_array, context_org_array->size - 1)
1190 jsonObjectFree(_fparam);
1193 osrfStringArrayFree(class_list);
1197 jsonObjectFree(param);
1200 char* context_org = NULL;
1204 if (permission->size == 0) {
1205 osrfLogDebug( OSRF_LOG_MARK, "No permission specified for this action, passing through" );
1210 while ( (perm = osrfStringArrayGetString(permission, i++)) ) {
1212 while ( (context_org = osrfStringArrayGetString(context_org_array, j++)) ) {
1218 "Checking object permission [%s] for user %d on object %s (class %s) at org %d",
1222 osrfHashGet(class, "classname"),
1226 result = dbi_conn_queryf(
1228 "SELECT permission.usr_has_object_perm(%d, '%s', '%s', '%s', %d) AS has_perm;",
1231 osrfHashGet(class, "classname"),
1239 "Recieved a result for object permission [%s] for user %d on object %s (class %s) at org %d",
1243 osrfHashGet(class, "classname"),
1247 if (dbi_result_first_row(result)) {
1248 jsonObject* return_val = oilsMakeJSONFromResult( result );
1249 char* has_perm = jsonObjectToSimpleString( jsonObjectGetKeyConst(return_val, "has_perm") );
1253 "Status of object permission [%s] for user %d on object %s (class %s) at org %d is %s",
1257 osrfHashGet(class, "classname"),
1262 if ( *has_perm == 't' ) OK = 1;
1264 jsonObjectFree(return_val);
1267 dbi_result_free(result);
1272 osrfLogDebug( OSRF_LOG_MARK, "Checking non-object permission [%s] for user %d at org %d", perm, userid, atoi(context_org) );
1273 result = dbi_conn_queryf(
1275 "SELECT permission.usr_has_perm(%d, '%s', %d) AS has_perm;",
1282 osrfLogDebug( OSRF_LOG_MARK, "Received a result for permission [%s] for user %d at org %d", perm, userid, atoi(context_org) );
1283 if (dbi_result_first_row(result)) {
1284 jsonObject* return_val = oilsMakeJSONFromResult( result );
1285 char* has_perm = jsonObjectToSimpleString( jsonObjectGetKeyConst(return_val, "has_perm") );
1286 osrfLogDebug( OSRF_LOG_MARK, "Status of permission [%s] for user %d at org %d is [%s]", perm, userid, atoi(context_org), has_perm );
1287 if ( *has_perm == 't' ) OK = 1;
1289 jsonObjectFree(return_val);
1292 dbi_result_free(result);
1300 if (pkey_value) free(pkey_value);
1301 osrfStringArrayFree(context_org_array);
1308 static jsonObject* doCreate(osrfMethodContext* ctx, int* err ) {
1310 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1312 jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
1313 jsonObject* options = jsonObjectGetIndex( ctx->params, 2 );
1315 jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
1316 jsonObject* options = jsonObjectGetIndex( ctx->params, 1 );
1319 if (!verifyObjectClass(ctx, target)) {
1324 osrfLogDebug( OSRF_LOG_MARK, "Object seems to be of the correct type" );
1326 if (!ctx->session || !ctx->session->userData || !osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
1327 osrfLogError( OSRF_LOG_MARK, "No active transaction -- required for CREATE" );
1329 osrfAppSessionStatus(
1331 OSRF_STATUS_BADREQUEST,
1332 "osrfMethodException",
1334 "No active transaction -- required for CREATE"
1340 // The following test is harmless but redundant. If a class is
1341 // readonly, we don't register a create method for it.
1342 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
1343 osrfAppSessionStatus(
1345 OSRF_STATUS_BADREQUEST,
1346 "osrfMethodException",
1348 "Cannot INSERT readonly class"
1355 char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
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 // litteral value list
1681 int in_item_index = 0;
1682 int in_item_first = 1;
1683 jsonObject* in_item;
1684 while ( (in_item = jsonObjectGetIndex(node, in_item_index++)) ) {
1689 buffer_add(sql_buf, ", ");
1691 if ( !strcmp( get_primitive( field ), "number") ) {
1692 char* val = jsonNumberToDBString( field, in_item );
1693 OSRF_BUFFER_ADD( sql_buf, val );
1697 char* key_string = jsonObjectToSimpleString(in_item);
1698 if ( dbi_conn_quote_string(dbhandle, &key_string) ) {
1699 OSRF_BUFFER_ADD( sql_buf, key_string );
1702 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, key_string);
1704 buffer_free(sql_buf);
1711 OSRF_BUFFER_ADD_CHAR( sql_buf, ')' );
1713 return buffer_release(sql_buf);
1716 // Receive a JSON_ARRAY representing a function call. The first
1717 // entry in the array is the function name. The rest are parameters.
1718 static char* searchValueTransform( const jsonObject* array ) {
1719 growing_buffer* sql_buf = buffer_init(32);
1722 jsonObject* func_item;
1724 // Get the function name
1725 if( array->size > 0 ) {
1726 func_item = jsonObjectGetIndex( array, 0 );
1727 val = jsonObjectToSimpleString( func_item );
1728 OSRF_BUFFER_ADD( sql_buf, val );
1729 OSRF_BUFFER_ADD( sql_buf, "( " );
1733 // Get the parameters
1734 int func_item_index = 1; // We already grabbed the zeroth entry
1735 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1737 // Add a separator comma, if we need one
1738 if( func_item_index > 2 )
1739 buffer_add( sql_buf, ", " );
1741 // Add the current parameter
1742 if (func_item->type == JSON_NULL) {
1743 buffer_add( sql_buf, "NULL" );
1745 val = jsonObjectToSimpleString(func_item);
1746 if ( dbi_conn_quote_string(dbhandle, &val) ) {
1747 OSRF_BUFFER_ADD( sql_buf, val );
1750 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1751 buffer_free(sql_buf);
1758 buffer_add( sql_buf, " )" );
1760 return buffer_release(sql_buf);
1763 static char* searchFunctionPredicate (const char* class, osrfHash* field,
1764 const jsonObject* node, const char* node_key) {
1765 growing_buffer* sql_buf = buffer_init(32);
1767 char* val = searchValueTransform(node);
1773 osrfHashGet(field, "name"),
1780 return buffer_release(sql_buf);
1783 // class is a class name
1784 // field is a field definition as stored in the IDL
1785 // node comes from the method parameter, and represents an entry in the SELECT list
1786 static char* searchFieldTransform (const char* class, osrfHash* field, const jsonObject* node) {
1787 growing_buffer* sql_buf = buffer_init(32);
1789 char* field_transform = jsonObjectToSimpleString( jsonObjectGetKeyConst( node, "transform" ) );
1790 char* transform_subcolumn = jsonObjectToSimpleString( jsonObjectGetKeyConst( node, "result_field" ) );
1792 if(transform_subcolumn)
1793 OSRF_BUFFER_ADD_CHAR( sql_buf, '(' ); // enclose transform in parentheses
1795 if (field_transform) {
1796 buffer_fadd( sql_buf, "%s(\"%s\".%s", field_transform, class, osrfHashGet(field, "name"));
1797 const jsonObject* array = jsonObjectGetKeyConst( node, "params" );
1800 if( array->type != JSON_ARRAY ) {
1801 osrfLogError( OSRF_LOG_MARK,
1802 "%s: Expected JSON_ARRAY for function params; found %s",
1803 MODULENAME, json_type( array->type ) );
1804 free( transform_subcolumn );
1805 free( field_transform );
1806 buffer_free( sql_buf );
1809 int func_item_index = 0;
1810 jsonObject* func_item;
1811 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
1813 char* val = jsonObjectToSimpleString(func_item);
1816 buffer_add( sql_buf, ",NULL" );
1817 } else if ( dbi_conn_quote_string(dbhandle, &val) ) {
1818 OSRF_BUFFER_ADD_CHAR( sql_buf, ',' );
1819 OSRF_BUFFER_ADD( sql_buf, val );
1821 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1822 free(transform_subcolumn);
1823 free(field_transform);
1825 buffer_free(sql_buf);
1832 buffer_add( sql_buf, " )" );
1835 buffer_fadd( sql_buf, "\"%s\".%s", class, osrfHashGet(field, "name"));
1838 if (transform_subcolumn)
1839 buffer_fadd( sql_buf, ").\"%s\"", transform_subcolumn );
1841 if (field_transform) free(field_transform);
1842 if (transform_subcolumn) free(transform_subcolumn);
1844 return buffer_release(sql_buf);
1847 static char* searchFieldTransformPredicate (const char* class, osrfHash* field, jsonObject* node, const char* node_key) {
1848 char* field_transform = searchFieldTransform( class, field, node );
1851 if (!jsonObjectGetKeyConst( node, "value" )) {
1852 value = searchWHERE( node, osrfHashGet( oilsIDL(), class ), AND_OP_JOIN, NULL );
1853 } else if (jsonObjectGetKeyConst( node, "value" )->type == JSON_ARRAY) {
1854 value = searchValueTransform(jsonObjectGetKeyConst( node, "value" ));
1855 } else if (jsonObjectGetKeyConst( node, "value" )->type == JSON_HASH) {
1856 value = searchWHERE( jsonObjectGetKeyConst( node, "value" ), osrfHashGet( oilsIDL(), class ), AND_OP_JOIN, NULL );
1857 } else if (jsonObjectGetKeyConst( node, "value" )->type != JSON_NULL) {
1858 if ( !strcmp( get_primitive( field ), "number") ) {
1859 value = jsonNumberToDBString( field, jsonObjectGetKeyConst( node, "value" ) );
1861 value = jsonObjectToSimpleString(jsonObjectGetKeyConst( node, "value" ));
1862 if ( !dbi_conn_quote_string(dbhandle, &value) ) {
1863 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, value);
1865 free(field_transform);
1871 growing_buffer* sql_buf = buffer_init(32);
1882 free(field_transform);
1884 return buffer_release(sql_buf);
1887 static char* searchSimplePredicate (const char* orig_op, const char* class,
1888 osrfHash* field, const jsonObject* node) {
1892 if (node->type != JSON_NULL) {
1893 if ( !strcmp( get_primitive( field ), "number") ) {
1894 val = jsonNumberToDBString( field, node );
1896 val = jsonObjectToSimpleString(node);
1900 char* pred = searchWriteSimplePredicate( class, field, osrfHashGet(field, "name"), orig_op, val );
1907 static char* searchWriteSimplePredicate ( const char* class, osrfHash* field,
1908 const char* left, const char* orig_op, const char* right ) {
1912 if (right == NULL) {
1913 val = strdup("NULL");
1915 if (strcmp( orig_op, "=" ))
1916 op = strdup("IS NOT");
1920 } else if ( !strcmp( get_primitive( field ), "number") ) {
1921 val = strdup(right);
1922 op = strdup(orig_op);
1925 val = strdup(right);
1926 if ( !dbi_conn_quote_string(dbhandle, &val) ) {
1927 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1931 op = strdup(orig_op);
1934 growing_buffer* sql_buf = buffer_init(16);
1935 buffer_fadd( sql_buf, "\"%s\".%s %s %s", class, left, op, val );
1939 return buffer_release(sql_buf);
1942 static char* searchBETWEENPredicate (const char* class, osrfHash* field, jsonObject* node) {
1947 if ( !strcmp( get_primitive( field ), "number") ) {
1948 x_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,0));
1949 y_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,1));
1952 x_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,0));
1953 y_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,1));
1954 if ( !(dbi_conn_quote_string(dbhandle, &x_string) && dbi_conn_quote_string(dbhandle, &y_string)) ) {
1955 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key strings [%s] and [%s]", MODULENAME, x_string, y_string);
1962 growing_buffer* sql_buf = buffer_init(32);
1963 buffer_fadd( sql_buf, "%s BETWEEN %s AND %s", osrfHashGet(field, "name"), x_string, y_string );
1967 return buffer_release(sql_buf);
1970 static char* searchPredicate ( const char* class, osrfHash* field,
1971 jsonObject* node, osrfMethodContext* ctx ) {
1974 if (node->type == JSON_ARRAY) { // equality IN search
1975 pred = searchINPredicate( class, field, node, NULL, ctx );
1976 } else if (node->type == JSON_HASH) { // non-equality search
1977 jsonObject* pred_node;
1978 jsonIterator* pred_itr = jsonNewIterator( node );
1979 while ( (pred_node = jsonIteratorNext( pred_itr )) ) {
1980 if ( !(strcasecmp( pred_itr->key,"between" )) )
1981 pred = searchBETWEENPredicate( class, field, pred_node );
1982 else if ( !(strcasecmp( pred_itr->key,"in" )) || !(strcasecmp( pred_itr->key,"not in" )) )
1983 pred = searchINPredicate( class, field, pred_node, pred_itr->key, ctx );
1984 else if ( pred_node->type == JSON_ARRAY )
1985 pred = searchFunctionPredicate( class, field, pred_node, pred_itr->key );
1986 else if ( pred_node->type == JSON_HASH )
1987 pred = searchFieldTransformPredicate( class, field, pred_node, pred_itr->key );
1989 pred = searchSimplePredicate( pred_itr->key, class, field, pred_node );
1993 jsonIteratorFree(pred_itr);
1994 } else if (node->type == JSON_NULL) { // IS NULL search
1995 growing_buffer* _p = buffer_init(64);
1998 "\"%s\".%s IS NULL",
2000 osrfHashGet(field, "name")
2002 pred = buffer_release(_p);
2003 } else { // equality search
2004 pred = searchSimplePredicate( "=", class, field, node );
2023 field : call_number,
2039 static char* searchJOIN ( const jsonObject* join_hash, osrfHash* leftmeta ) {
2041 const jsonObject* working_hash;
2042 jsonObject* freeable_hash = NULL;
2044 if (join_hash->type == JSON_STRING) {
2045 // create a wrapper around a copy of the original
2046 char* _tmp = jsonObjectToSimpleString( join_hash );
2047 freeable_hash = jsonNewObjectType(JSON_HASH);
2048 jsonObjectSetKey(freeable_hash, _tmp, NULL);
2050 working_hash = freeable_hash;
2053 if( join_hash->type != JSON_HASH ) {
2056 "%s: JOIN failed; expected JSON object type not found",
2061 working_hash = join_hash;
2064 growing_buffer* join_buf = buffer_init(128);
2065 const char* leftclass = osrfHashGet(leftmeta, "classname");
2067 jsonObject* snode = NULL;
2068 jsonIterator* search_itr = jsonNewIterator( working_hash );
2070 while ( (snode = jsonIteratorNext( search_itr )) ) {
2071 const char* class = search_itr->key;
2072 osrfHash* idlClass = osrfHashGet( oilsIDL(), class );
2076 "%s: JOIN failed. No class \"%s\" defined in IDL",
2080 jsonIteratorFree( search_itr );
2081 buffer_free( join_buf );
2083 jsonObjectFree( freeable_hash );
2087 char* fkey = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "fkey" ) );
2088 char* field = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "field" ) );
2090 if (field && !fkey) {
2091 fkey = (char*)oilsIDLFindPath("/%s/links/%s/key", class, field);
2095 "%s: JOIN failed. No link defined from %s.%s to %s",
2101 buffer_free(join_buf);
2103 jsonObjectFree(freeable_hash);
2105 jsonIteratorFree(search_itr);
2108 fkey = strdup( fkey );
2110 } else if (!field && fkey) {
2111 field = (char*)oilsIDLFindPath("/%s/links/%s/key", leftclass, fkey );
2115 "%s: JOIN failed. No link defined from %s.%s to %s",
2121 buffer_free(join_buf);
2123 jsonObjectFree(freeable_hash);
2125 jsonIteratorFree(search_itr);
2128 field = strdup( field );
2130 } else if (!field && !fkey) {
2131 osrfHash* _links = oilsIDL_links( leftclass );
2133 // For each link defined for the left class:
2134 // see if the link references the joined class
2135 osrfHashIterator* itr = osrfNewHashIterator( _links );
2136 osrfHash* curr_link = NULL;
2137 while( (curr_link = osrfHashIteratorNext( itr ) ) ) {
2138 const char* other_class = osrfHashGet( curr_link, "class" );
2139 if( other_class && !strcmp( other_class, class ) ) {
2141 // Found a link between the classes
2142 fkey = strdup( osrfHashIteratorKey( itr ) );
2143 const char* other_key = osrfHashGet( curr_link, "key" );
2144 field = other_key ? strdup( other_key ) : NULL;
2148 osrfHashIteratorFree( itr );
2150 if (!field || !fkey) {
2151 // Do another such search, with the classes reversed
2152 _links = oilsIDL_links( class );
2154 // For each link defined for the joined class:
2155 // see if the link references the left class
2156 osrfHashIterator* itr = osrfNewHashIterator( _links );
2157 osrfHash* curr_link = NULL;
2158 while( (curr_link = osrfHashIteratorNext( itr ) ) ) {
2159 const char* other_class = osrfHashGet( curr_link, "class" );
2160 if( other_class && !strcmp( other_class, leftclass ) ) {
2162 // Found a link between the classes
2163 fkey = strdup( osrfHashIteratorKey( itr ) );
2164 const char* other_key = osrfHashGet( curr_link, "key" );
2165 field = other_key ? strdup( other_key ) : NULL;
2169 osrfHashIteratorFree( itr );
2172 if (!field || !fkey) {
2175 "%s: JOIN failed. No link defined between %s and %s",
2182 buffer_free(join_buf);
2184 jsonObjectFree(freeable_hash);
2185 jsonIteratorFree(search_itr);
2191 char* type = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "type" ) );
2193 if ( !strcasecmp(type,"left") ) {
2194 buffer_add(join_buf, " LEFT JOIN");
2195 } else if ( !strcasecmp(type,"right") ) {
2196 buffer_add(join_buf, " RIGHT JOIN");
2197 } else if ( !strcasecmp(type,"full") ) {
2198 buffer_add(join_buf, " FULL JOIN");
2200 buffer_add(join_buf, " INNER JOIN");
2203 buffer_add(join_buf, " INNER JOIN");
2207 char* table = getSourceDefinition(idlClass);
2211 jsonIteratorFree( search_itr );
2212 buffer_free( join_buf );
2214 jsonObjectFree( freeable_hash );
2218 buffer_fadd(join_buf, " %s AS \"%s\" ON ( \"%s\".%s = \"%s\".%s",
2219 table, class, class, field, leftclass, fkey);
2222 const jsonObject* filter = jsonObjectGetKeyConst( snode, "filter" );
2224 char* filter_op = jsonObjectToSimpleString( jsonObjectGetKeyConst( snode, "filter_op" ) );
2226 if (!strcasecmp("or",filter_op)) {
2227 buffer_add( join_buf, " OR " );
2229 buffer_add( join_buf, " AND " );
2232 buffer_add( join_buf, " AND " );
2235 char* jpred = searchWHERE( filter, idlClass, AND_OP_JOIN, NULL );
2236 OSRF_BUFFER_ADD_CHAR( join_buf, ' ' );
2237 OSRF_BUFFER_ADD( join_buf, jpred );
2242 buffer_add(join_buf, " ) ");
2244 const jsonObject* join_filter = jsonObjectGetKeyConst( snode, "join" );
2246 char* jpred = searchJOIN( join_filter, idlClass );
2247 OSRF_BUFFER_ADD_CHAR( join_buf, ' ' );
2248 OSRF_BUFFER_ADD( join_buf, jpred );
2257 jsonObjectFree(freeable_hash);
2258 jsonIteratorFree(search_itr);
2260 return buffer_release(join_buf);
2265 { +class : { -or|-and : { field : { op : value }, ... } ... }, ... }
2266 { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }
2267 [ { +class : { -or|-and : [ { field : { op : value }, ... }, ...] ... }, ... }, ... ]
2271 static char* searchWHERE ( const jsonObject* search_hash, osrfHash* meta, int opjoin_type, osrfMethodContext* ctx ) {
2275 "%s: Entering searchWHERE; search_hash addr = %p, meta addr = %p, opjoin_type = %d, ctx addr = %p",
2283 growing_buffer* sql_buf = buffer_init(128);
2285 jsonObject* node = NULL;
2288 if ( search_hash->type == JSON_ARRAY ) {
2289 osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_ARRAY", MODULENAME);
2290 jsonIterator* search_itr = jsonNewIterator( search_hash );
2291 while ( (node = jsonIteratorNext( search_itr )) ) {
2295 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2296 else buffer_add(sql_buf, " AND ");
2299 char* subpred = searchWHERE( node, meta, opjoin_type, ctx );
2300 buffer_fadd(sql_buf, "( %s )", subpred);
2303 jsonIteratorFree(search_itr);
2305 } else if ( search_hash->type == JSON_HASH ) {
2306 osrfLogDebug(OSRF_LOG_MARK, "%s: In WHERE clause, condition type is JSON_HASH", MODULENAME);
2307 jsonIterator* search_itr = jsonNewIterator( search_hash );
2308 while ( (node = jsonIteratorNext( search_itr )) ) {
2313 if (opjoin_type == OR_OP_JOIN) buffer_add(sql_buf, " OR ");
2314 else buffer_add(sql_buf, " AND ");
2317 if ( !strncmp("+",search_itr->key,1) ) {
2318 if ( node->type == JSON_STRING ) {
2319 char* subpred = jsonObjectToSimpleString( node );
2320 buffer_fadd(sql_buf, " \"%s\".%s ", search_itr->key + 1, subpred);
2323 char* subpred = searchWHERE( node, osrfHashGet( oilsIDL(), search_itr->key + 1 ), AND_OP_JOIN, ctx );
2324 buffer_fadd(sql_buf, "( %s )", subpred);
2327 } else if ( !strcasecmp("-or",search_itr->key) ) {
2328 char* subpred = searchWHERE( node, meta, OR_OP_JOIN, ctx );
2329 buffer_fadd(sql_buf, "( %s )", subpred);
2331 } else if ( !strcasecmp("-and",search_itr->key) ) {
2332 char* subpred = searchWHERE( node, meta, AND_OP_JOIN, ctx );
2333 buffer_fadd(sql_buf, "( %s )", subpred);
2335 } else if ( !strcasecmp("-exists",search_itr->key) ) {
2336 char* subpred = SELECT(
2338 jsonObjectGetKey( node, "select" ),
2339 jsonObjectGetKey( node, "from" ),
2340 jsonObjectGetKey( node, "where" ),
2341 jsonObjectGetKey( node, "having" ),
2342 jsonObjectGetKey( node, "order_by" ),
2343 jsonObjectGetKey( node, "limit" ),
2344 jsonObjectGetKey( node, "offset" ),
2348 buffer_fadd(sql_buf, "EXISTS ( %s )", subpred);
2350 } else if ( !strcasecmp("-not-exists",search_itr->key) ) {
2351 char* subpred = SELECT(
2353 jsonObjectGetKey( node, "select" ),
2354 jsonObjectGetKey( node, "from" ),
2355 jsonObjectGetKey( node, "where" ),
2356 jsonObjectGetKey( node, "having" ),
2357 jsonObjectGetKey( node, "order_by" ),
2358 jsonObjectGetKey( node, "limit" ),
2359 jsonObjectGetKey( node, "offset" ),
2363 buffer_fadd(sql_buf, "NOT EXISTS ( %s )", subpred);
2367 char* class = osrfHashGet(meta, "classname");
2368 osrfHash* fields = osrfHashGet(meta, "fields");
2369 osrfHash* field = osrfHashGet( fields, search_itr->key );
2373 char* table = getSourceDefinition(meta);
2375 table = strdup( "(?)" );
2378 "%s: Attempt to reference non-existent column %s on %s (%s)",
2384 buffer_free(sql_buf);
2386 jsonIteratorFree(search_itr);
2390 char* subpred = searchPredicate( class, field, node, ctx );
2391 buffer_add( sql_buf, subpred );
2395 jsonIteratorFree(search_itr);
2398 // ERROR ... only hash and array allowed at this level
2399 char* predicate_string = jsonObjectToJSON( search_hash );
2402 "%s: Invalid predicate structure: %s",
2406 buffer_free(sql_buf);
2407 free(predicate_string);
2412 return buffer_release(sql_buf);
2416 /* method context */ osrfMethodContext* ctx,
2418 /* SELECT */ jsonObject* selhash,
2419 /* FROM */ jsonObject* join_hash,
2420 /* WHERE */ jsonObject* search_hash,
2421 /* HAVING */ jsonObject* having_hash,
2422 /* ORDER BY */ jsonObject* order_hash,
2423 /* LIMIT */ jsonObject* limit,
2424 /* OFFSET */ jsonObject* offset,
2425 /* flags */ int flags
2427 const char* locale = osrf_message_get_last_locale();
2429 // in case we don't get a select list
2430 jsonObject* defaultselhash = NULL;
2432 // general tmp objects
2433 const jsonObject* tmp_const;
2434 jsonObject* selclass = NULL;
2435 jsonObject* selfield = NULL;
2436 jsonObject* snode = NULL;
2437 jsonObject* onode = NULL;
2439 char* string = NULL;
2440 int from_function = 0;
2445 // the core search class
2446 char* core_class = NULL;
2448 // metadata about the core search class
2449 osrfHash* core_meta = NULL;
2451 // punt if there's no core class
2452 if (!join_hash || ( join_hash->type == JSON_HASH && !join_hash->size )) {
2455 "%s: FROM clause is missing or empty",
2459 osrfAppSessionStatus(
2461 OSRF_STATUS_INTERNALSERVERERROR,
2462 "osrfMethodException",
2464 "FROM clause is missing or empty in JSON query"
2469 // get the core class -- the only key of the top level FROM clause, or a string
2470 if (join_hash->type == JSON_HASH) {
2471 jsonIterator* tmp_itr = jsonNewIterator( join_hash );
2472 snode = jsonIteratorNext( tmp_itr );
2474 core_class = strdup( tmp_itr->key );
2477 jsonObject* extra = jsonIteratorNext( tmp_itr );
2479 jsonIteratorFree( tmp_itr );
2482 // There shouldn't be more than one entry in join_hash
2486 "%s: Malformed FROM clause: extra entry in JSON_HASH",
2490 osrfAppSessionStatus(
2492 OSRF_STATUS_INTERNALSERVERERROR,
2493 "osrfMethodException",
2495 "Malformed FROM clause in JSON query"
2498 return NULL; // Malformed join_hash; extra entry
2500 } else if (join_hash->type == JSON_ARRAY) {
2502 core_class = jsonObjectToSimpleString( jsonObjectGetIndex(join_hash, 0) );
2505 } else if (join_hash->type == JSON_STRING) {
2506 core_class = jsonObjectToSimpleString( join_hash );
2512 "%s: FROM clause is unexpected JSON type: %s",
2514 json_type( join_hash->type )
2517 osrfAppSessionStatus(
2519 OSRF_STATUS_INTERNALSERVERERROR,
2520 "osrfMethodException",
2522 "Ill-formed FROM clause in JSON query"
2528 if (!from_function) {
2529 // Get the IDL class definition for the core class
2530 core_meta = osrfHashGet( oilsIDL(), core_class );
2531 if( !core_meta ) { // Didn't find it?
2534 "%s: SELECT clause references undefined class: \"%s\"",
2539 osrfAppSessionStatus(
2541 OSRF_STATUS_INTERNALSERVERERROR,
2542 "osrfMethodException",
2544 "SELECT clause references undefined class in JSON query"
2550 // Make sure the class isn't virtual
2551 if( str_is_true( osrfHashGet( core_meta, "virtual" ) ) ) {
2554 "%s: Core class is virtual: \"%s\"",
2559 osrfAppSessionStatus(
2561 OSRF_STATUS_INTERNALSERVERERROR,
2562 "osrfMethodException",
2564 "FROM clause references virtual class in JSON query"
2571 // if the select list is empty, or the core class field list is '*',
2572 // build the default select list ...
2574 selhash = defaultselhash = jsonNewObjectType(JSON_HASH);
2575 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2576 } else if( selhash->type != JSON_HASH ) {
2579 "%s: Expected JSON_HASH for SELECT clause; found %s",
2581 json_type( selhash->type )
2585 osrfAppSessionStatus(
2587 OSRF_STATUS_INTERNALSERVERERROR,
2588 "osrfMethodException",
2590 "Malformed SELECT clause in JSON query"
2594 } else if ( (tmp_const = jsonObjectGetKeyConst( selhash, core_class )) && tmp_const->type == JSON_STRING ) {
2595 char* _x = jsonObjectToSimpleString( tmp_const );
2596 if (!strncmp( "*", _x, 1 )) {
2597 jsonObjectRemoveKey( selhash, core_class );
2598 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
2604 growing_buffer* sql_buf = buffer_init(128);
2606 // temp buffer for the SELECT list
2607 growing_buffer* select_buf = buffer_init(128);
2608 growing_buffer* order_buf = buffer_init(128);
2609 growing_buffer* group_buf = buffer_init(128);
2610 growing_buffer* having_buf = buffer_init(128);
2612 int aggregate_found = 0; // boolean
2614 // Build a select list
2615 if(from_function) // From a function we select everything
2616 OSRF_BUFFER_ADD_CHAR( select_buf, '*' );
2619 // If we need to build a default list, prepare to do so
2620 jsonObject* _tmp = jsonObjectGetKey( selhash, core_class );
2621 if ( _tmp && !_tmp->size ) {
2623 osrfHash* core_fields = osrfHashGet( core_meta, "fields" );
2625 osrfHashIterator* field_itr = osrfNewHashIterator( core_fields );
2626 osrfHash* field_def;
2627 while( ( field_def = osrfHashIteratorNext( field_itr ) ) ) {
2628 if( ! str_is_true( osrfHashGet( field_def, "virtual" ) ) ) {
2629 // This field is not virtual, so add it to the list
2630 jsonObjectPush( _tmp, jsonNewObject( osrfHashIteratorKey( field_itr ) ) );
2633 osrfHashIteratorFree( field_itr );
2636 // Now build the actual select list
2640 jsonIterator* selclass_itr = jsonNewIterator( selhash );
2641 while ( (selclass = jsonIteratorNext( selclass_itr )) ) { // For each class
2643 // Make sure the class is defined in the IDL
2644 const char* cname = selclass_itr->key;
2645 osrfHash* idlClass = osrfHashGet( oilsIDL(), cname );
2649 "%s: Selected class \"%s\" not defined in IDL",
2655 osrfAppSessionStatus(
2657 OSRF_STATUS_INTERNALSERVERERROR,
2658 "osrfMethodException",
2660 "Selected class is not defined"
2662 jsonIteratorFree( selclass_itr );
2663 buffer_free( sql_buf );
2664 buffer_free( select_buf );
2665 buffer_free( order_buf );
2666 buffer_free( group_buf );
2667 buffer_free( having_buf );
2668 if( defaultselhash ) jsonObjectFree( defaultselhash );
2673 // Make sure the target relation is in the join tree.
2675 // At this point join_hash is a step down from the join_hash we
2676 // received as a parameter. If the original was a JSON_STRING,
2677 // then json_hash is now NULL. If the original was a JSON_HASH,
2678 // then json_hash is now the first (and only) entry in it,
2679 // denoting the core class. We've already excluded the
2680 // possibility that the original was a JSON_ARRAY, because in
2681 // that case from_function would be non-NULL, and we wouldn't
2684 int class_in_from_clause; // boolean
2686 if ( ! strcmp( core_class, cname ))
2687 // This is the core class -- no problem
2688 class_in_from_clause = 1;
2691 // There's only one class in the FROM clause, and this isn't it
2692 class_in_from_clause = 0;
2693 else if (join_hash->type == JSON_STRING) {
2694 // There's only one class in the FROM clause
2695 string = jsonObjectToSimpleString(join_hash);
2696 if ( strcmp( string, cname ) )
2697 class_in_from_clause = 0; // This isn't it
2699 class_in_from_clause = 1; // This is it
2702 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", cname);
2703 if ( 0 == found->size )
2704 class_in_from_clause = 0; // Nowhere in the join tree
2706 class_in_from_clause = 1; // Found it
2707 jsonObjectFree( found );
2711 // If the class isn't in the FROM clause, bail out
2712 if( ! class_in_from_clause ) {
2715 "%s: SELECT clause references class not in FROM clause: \"%s\"",
2720 osrfAppSessionStatus(
2722 OSRF_STATUS_INTERNALSERVERERROR,
2723 "osrfMethodException",
2725 "Selected class not in FROM clause in JSON query"
2727 jsonIteratorFree( selclass_itr );
2728 buffer_free( sql_buf );
2729 buffer_free( select_buf );
2730 buffer_free( order_buf );
2731 buffer_free( group_buf );
2732 buffer_free( having_buf );
2733 if( defaultselhash ) jsonObjectFree( defaultselhash );
2738 // Look up some attributes of the current class, so that we
2739 // don't have to look them up again for each field
2740 osrfHash* class_field_set = osrfHashGet( idlClass, "fields" );
2741 const char* class_pkey = osrfHashGet( idlClass, "primarykey" );
2742 const char* class_tname = osrfHashGet( idlClass, "tablename" );
2744 // stitch together the column list ...
2745 jsonIterator* select_itr = jsonNewIterator( selclass );
2746 while ( (selfield = jsonIteratorNext( select_itr )) ) { // for each SELECT column
2748 // If we need a separator comma, add one
2752 OSRF_BUFFER_ADD_CHAR( select_buf, ',' );
2755 // ... if it's a string, just toss it on the pile
2756 if (selfield->type == JSON_STRING) {
2758 // Look up the field in the IDL
2759 const char* col_name = selfield->value.s;
2760 osrfHash* field_def = osrfHashGet( class_field_set, col_name );
2762 // No such field in current class
2765 "%s: Selected column \"%s\" not defined in IDL for class \"%s\"",
2771 osrfAppSessionStatus(
2773 OSRF_STATUS_INTERNALSERVERERROR,
2774 "osrfMethodException",
2776 "Selected column not defined in JSON query"
2778 jsonIteratorFree( select_itr );
2779 jsonIteratorFree( selclass_itr );
2780 buffer_free( sql_buf );
2781 buffer_free( select_buf );
2782 buffer_free( order_buf );
2783 buffer_free( group_buf );
2784 buffer_free( having_buf );
2785 if( defaultselhash ) jsonObjectFree( defaultselhash );
2788 } else if ( str_is_true( osrfHashGet( field_def, "virtual" ) ) ) {
2789 // Virtual field not allowed
2792 "%s: Selected column \"%s\" for class \"%s\" is virtual",
2798 osrfAppSessionStatus(
2800 OSRF_STATUS_INTERNALSERVERERROR,
2801 "osrfMethodException",
2803 "Selected column may not be virtual in JSON query"
2805 jsonIteratorFree( select_itr );
2806 jsonIteratorFree( selclass_itr );
2807 buffer_free( sql_buf );
2808 buffer_free( select_buf );
2809 buffer_free( order_buf );
2810 buffer_free( group_buf );
2811 buffer_free( having_buf );
2812 if( defaultselhash ) jsonObjectFree( defaultselhash );
2819 if (flags & DISABLE_I18N)
2822 i18n = osrfHashGet(field_def, "i18n");
2824 if( str_is_true( i18n ) ) {
2825 buffer_fadd( select_buf,
2826 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2827 class_tname, cname, col_name, class_pkey, cname, class_pkey, locale, col_name );
2829 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2832 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, col_name );
2835 // ... but it could be an object, in which case we check for a Field Transform
2836 } else if (selfield->type == JSON_HASH) {
2838 char* col_name = jsonObjectToSimpleString( jsonObjectGetKeyConst( selfield, "column" ) );
2840 // Get the field definition from the IDL
2841 osrfHash* field_def = osrfHashGet( class_field_set, col_name );
2843 // No such field in current class
2846 "%s: Selected column \"%s\" is not defined in IDL for class \"%s\"",
2852 osrfAppSessionStatus(
2854 OSRF_STATUS_INTERNALSERVERERROR,
2855 "osrfMethodException",
2857 "Selected column is not defined in JSON query"
2859 jsonIteratorFree( select_itr );
2860 jsonIteratorFree( selclass_itr );
2861 buffer_free( sql_buf );
2862 buffer_free( select_buf );
2863 buffer_free( order_buf );
2864 buffer_free( group_buf );
2865 buffer_free( having_buf );
2866 if( defaultselhash ) jsonObjectFree( defaultselhash );
2869 } else if ( str_is_true( osrfHashGet( field_def, "virtual" ) ) ) {
2870 // No such field in current class
2873 "%s: Selected column \"%s\" is virtual for class \"%s\"",
2879 osrfAppSessionStatus(
2881 OSRF_STATUS_INTERNALSERVERERROR,
2882 "osrfMethodException",
2884 "Selected column is virtual in JSON query"
2886 jsonIteratorFree( select_itr );
2887 jsonIteratorFree( selclass_itr );
2888 buffer_free( sql_buf );
2889 buffer_free( select_buf );
2890 buffer_free( order_buf );
2891 buffer_free( group_buf );
2892 buffer_free( having_buf );
2893 if( defaultselhash ) jsonObjectFree( defaultselhash );
2898 // Decide what to use as a column alias
2900 if ((tmp_const = jsonObjectGetKeyConst( selfield, "alias" ))) {
2901 _alias = jsonObjectToSimpleString( tmp_const );
2902 } else { // Use field name as the alias
2906 if (jsonObjectGetKeyConst( selfield, "transform" )) {
2907 char* transform_str = searchFieldTransform(cname, field_def, selfield);
2908 if( transform_str ) {
2909 buffer_fadd(select_buf, " %s AS \"%s\"", transform_str, _alias);
2910 free(transform_str);
2913 osrfAppSessionStatus(
2915 OSRF_STATUS_INTERNALSERVERERROR,
2916 "osrfMethodException",
2918 "Unable to generate transform function in JSON query"
2920 jsonIteratorFree( select_itr );
2921 jsonIteratorFree( selclass_itr );
2922 buffer_free( sql_buf );
2923 buffer_free( select_buf );
2924 buffer_free( order_buf );
2925 buffer_free( group_buf );
2926 buffer_free( having_buf );
2927 if( defaultselhash ) jsonObjectFree( defaultselhash );
2935 if (flags & DISABLE_I18N)
2938 i18n = osrfHashGet(field_def, "i18n");
2940 if( str_is_true( i18n ) ) {
2941 buffer_fadd( select_buf,
2942 " oils_i18n_xlate('%s', '%s', '%s', '%s', \"%s\".%s::TEXT, '%s') AS \"%s\"",
2943 class_tname, cname, col_name, class_pkey, cname, class_pkey, locale, _alias);
2945 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, _alias);
2948 buffer_fadd(select_buf, " \"%s\".%s AS \"%s\"", cname, col_name, _alias);
2952 if( _alias != col_name )
2959 "%s: Selected item is unexpected JSON type: %s",
2961 json_type( selfield->type )
2964 osrfAppSessionStatus(
2966 OSRF_STATUS_INTERNALSERVERERROR,
2967 "osrfMethodException",
2969 "Ill-formed SELECT item in JSON query"
2971 jsonIteratorFree( select_itr );
2972 jsonIteratorFree( selclass_itr );
2973 buffer_free( sql_buf );
2974 buffer_free( select_buf );
2975 buffer_free( order_buf );
2976 buffer_free( group_buf );
2977 buffer_free( having_buf );
2978 if( defaultselhash ) jsonObjectFree( defaultselhash );
2983 const jsonObject* agg_obj = jsonObjectGetKey( selfield, "aggregate" );
2984 if( obj_is_true( agg_obj ) )
2985 aggregate_found = 1;
2987 // Append a comma (except for the first one)
2988 // and add the column to a GROUP BY clause
2992 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
2994 buffer_fadd(group_buf, " %d", sel_pos);
2998 if (is_agg->size || (flags & SELECT_DISTINCT)) {
3000 const jsonObject* aggregate_obj = jsonObjectGetKey( selfield, "aggregate" );
3001 if ( ! obj_is_true( aggregate_obj ) ) {
3005 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
3008 buffer_fadd(group_buf, " %d", sel_pos);
3011 } else if (is_agg = jsonObjectGetKey( selfield, "having" )) {
3015 OSRF_BUFFER_ADD_CHAR( group_buf, ',' );
3018 _column = searchFieldTransform(cname, field, selfield);
3019 OSRF_BUFFER_ADD_CHAR(group_buf, ' ');
3020 OSRF_BUFFER_ADD(group_buf, _column);
3021 _column = searchFieldTransform(cname, field, selfield);
3028 } // end while -- iterating across SELECT columns
3030 jsonIteratorFree(select_itr);
3031 } // end while -- iterating across classes
3033 jsonIteratorFree(selclass_itr);
3037 char* col_list = buffer_release(select_buf);
3039 if (from_function) table = searchValueTransform(join_hash);
3040 else table = getSourceDefinition(core_meta);
3044 osrfAppSessionStatus(
3046 OSRF_STATUS_INTERNALSERVERERROR,
3047 "osrfMethodException",
3049 "Unable to identify table for core class"
3052 buffer_free( sql_buf );
3053 buffer_free( order_buf );
3054 buffer_free( group_buf );
3055 buffer_free( having_buf );
3056 if( defaultselhash ) jsonObjectFree( defaultselhash );
3061 // Put it all together
3062 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\" ", col_list, table, core_class );
3066 if (!from_function) {
3067 // Now, walk the join tree and add that clause
3069 char* join_clause = searchJOIN( join_hash, core_meta );
3071 buffer_add(sql_buf, join_clause);
3075 osrfAppSessionStatus(
3077 OSRF_STATUS_INTERNALSERVERERROR,
3078 "osrfMethodException",
3080 "Unable to construct JOIN clause(s)"
3082 buffer_free( sql_buf );
3083 buffer_free( order_buf );
3084 buffer_free( group_buf );
3085 buffer_free( having_buf );
3086 if( defaultselhash ) jsonObjectFree( defaultselhash );
3092 // Build a WHERE clause, if there is one
3093 if ( search_hash ) {
3094 buffer_add(sql_buf, " WHERE ");
3096 // and it's on the WHERE clause
3097 char* pred = searchWHERE( search_hash, core_meta, AND_OP_JOIN, ctx );
3100 buffer_add(sql_buf, pred);
3104 osrfAppSessionStatus(
3106 OSRF_STATUS_INTERNALSERVERERROR,
3107 "osrfMethodException",
3109 "Severe query error in WHERE predicate -- see error log for more details"
3113 buffer_free(having_buf);
3114 buffer_free(group_buf);
3115 buffer_free(order_buf);
3116 buffer_free(sql_buf);
3117 if (defaultselhash) jsonObjectFree(defaultselhash);
3122 // Build a HAVING clause, if there is one
3123 if ( having_hash ) {
3124 buffer_add(sql_buf, " HAVING ");
3126 // and it's on the the WHERE clause
3127 char* pred = searchWHERE( having_hash, core_meta, AND_OP_JOIN, ctx );
3130 buffer_add(sql_buf, pred);
3134 osrfAppSessionStatus(
3136 OSRF_STATUS_INTERNALSERVERERROR,
3137 "osrfMethodException",
3139 "Severe query error in HAVING predicate -- see error log for more details"
3143 buffer_free(having_buf);
3144 buffer_free(group_buf);
3145 buffer_free(order_buf);
3146 buffer_free(sql_buf);
3147 if (defaultselhash) jsonObjectFree(defaultselhash);
3152 // Build an ORDER BY clause, if there is one
3154 jsonIterator* class_itr = jsonNewIterator( order_hash );
3155 while ( (snode = jsonIteratorNext( class_itr )) ) {
3157 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
3160 if ( snode->type == JSON_HASH ) {
3162 jsonIterator* order_itr = jsonNewIterator( snode );
3163 while ( (onode = jsonIteratorNext( order_itr )) ) {
3165 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
3168 char* direction = NULL;
3169 if ( onode->type == JSON_HASH ) {
3170 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
3171 string = searchFieldTransform(
3173 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
3177 growing_buffer* field_buf = buffer_init(16);
3178 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
3179 string = buffer_release(field_buf);
3182 if ( (tmp_const = jsonObjectGetKeyConst( onode, "direction" )) ) {
3183 direction = jsonObjectToSimpleString(tmp_const);
3184 if (!strncasecmp(direction, "d", 1)) {
3186 direction = " DESC";
3194 string = strdup(order_itr->key);
3195 direction = jsonObjectToSimpleString(onode);
3196 if (!strncasecmp(direction, "d", 1)) {
3198 direction = " DESC";
3208 buffer_add(order_buf, ", ");
3211 buffer_add(order_buf, string);
3215 buffer_add(order_buf, direction);
3219 // jsonIteratorFree(order_itr);
3221 } else if ( snode->type == JSON_ARRAY ) {
3223 jsonIterator* order_itr = jsonNewIterator( snode );
3224 while ( (onode = jsonIteratorNext( order_itr )) ) {
3226 char* _f = jsonObjectToSimpleString( onode );
3228 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, _f))
3234 buffer_add(order_buf, ", ");
3237 buffer_add(order_buf, _f);
3241 // jsonIteratorFree(order_itr);
3244 // IT'S THE OOOOOOOOOOOLD STYLE!
3246 osrfLogError(OSRF_LOG_MARK, "%s: Possible SQL injection attempt; direct order by is not allowed", MODULENAME);
3248 osrfAppSessionStatus(
3250 OSRF_STATUS_INTERNALSERVERERROR,
3251 "osrfMethodException",
3253 "Severe query error -- see error log for more details"
3258 buffer_free(having_buf);
3259 buffer_free(group_buf);
3260 buffer_free(order_buf);
3261 buffer_free(sql_buf);
3262 if (defaultselhash) jsonObjectFree(defaultselhash);
3263 jsonIteratorFree(class_itr);
3268 // jsonIteratorFree(class_itr);
3272 string = buffer_release(group_buf);
3274 if ( *string && ( aggregate_found || (flags & SELECT_DISTINCT) ) ) {
3275 OSRF_BUFFER_ADD( sql_buf, " GROUP BY " );
3276 OSRF_BUFFER_ADD( sql_buf, string );
3281 string = buffer_release(having_buf);
3284 OSRF_BUFFER_ADD( sql_buf, " HAVING " );
3285 OSRF_BUFFER_ADD( sql_buf, string );
3290 string = buffer_release(order_buf);
3293 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
3294 OSRF_BUFFER_ADD( sql_buf, string );
3300 string = jsonObjectToSimpleString(limit);
3301 buffer_fadd( sql_buf, " LIMIT %d", atoi(string) );
3306 string = jsonObjectToSimpleString(offset);
3307 buffer_fadd( sql_buf, " OFFSET %d", atoi(string) );
3311 if (!(flags & SUBSELECT)) OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
3314 if (defaultselhash) jsonObjectFree(defaultselhash);
3316 return buffer_release(sql_buf);
3320 static char* buildSELECT ( jsonObject* search_hash, jsonObject* order_hash, osrfHash* meta, osrfMethodContext* ctx ) {
3322 const char* locale = osrf_message_get_last_locale();
3324 osrfHash* fields = osrfHashGet(meta, "fields");
3325 char* core_class = osrfHashGet(meta, "classname");
3327 const jsonObject* join_hash = jsonObjectGetKeyConst( order_hash, "join" );
3329 jsonObject* node = NULL;
3330 jsonObject* snode = NULL;
3331 jsonObject* onode = NULL;
3332 const jsonObject* _tmp = NULL;
3333 jsonObject* selhash = NULL;
3334 jsonObject* defaultselhash = NULL;
3336 growing_buffer* sql_buf = buffer_init(128);
3337 growing_buffer* select_buf = buffer_init(128);
3339 if ( !(selhash = jsonObjectGetKey( order_hash, "select" )) ) {
3340 defaultselhash = jsonNewObjectType(JSON_HASH);
3341 selhash = defaultselhash;
3344 if ( !jsonObjectGetKeyConst(selhash,core_class) ) {
3345 jsonObjectSetKey( selhash, core_class, jsonNewObjectType(JSON_ARRAY) );
3346 jsonObject* flist = jsonObjectGetKey( selhash, core_class );
3351 osrfStringArray* keys = osrfHashKeys( fields );
3352 while ( (field = osrfStringArrayGetString(keys, i++)) ) {
3353 if( ! str_is_true( osrfHashGet( osrfHashGet( fields, field ), "virtual" ) ) )
3354 jsonObjectPush( flist, jsonNewObject( field ) );
3356 osrfStringArrayFree(keys);
3360 jsonIterator* class_itr = jsonNewIterator( selhash );
3361 while ( (snode = jsonIteratorNext( class_itr )) ) {
3363 char* cname = class_itr->key;
3364 osrfHash* idlClass = osrfHashGet( oilsIDL(), cname );
3365 if (!idlClass) continue;
3367 if (strcmp(core_class,class_itr->key)) {
3368 if (!join_hash) continue;
3370 jsonObject* found = jsonObjectFindPath(join_hash, "//%s", class_itr->key);
3372 jsonObjectFree(found);
3376 jsonObjectFree(found);
3379 jsonIterator* select_itr = jsonNewIterator( snode );
3380 while ( (node = jsonIteratorNext( select_itr )) ) {
3381 char* item_str = jsonObjectToSimpleString(node);
3382 osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), item_str );
3384 char* fname = osrfHashGet(field, "name");
3386 if (!field) continue;
3391 OSRF_BUFFER_ADD_CHAR(select_buf, ',');
3396 const jsonObject* no_i18n_obj = jsonObjectGetKey( order_hash, "no_i18n" );
3397 if ( obj_is_true( no_i18n_obj ) ) // Suppress internationalization?
3400 i18n = osrfHashGet(field, "i18n");
3402 if( str_is_true( i18n ) ) {
3403 char* pkey = osrfHashGet(idlClass, "primarykey");
3404 char* tname = osrfHashGet(idlClass, "tablename");
3406 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);
3408 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
3411 buffer_fadd(select_buf, " \"%s\".%s", cname, fname);
3415 jsonIteratorFree(select_itr);
3418 jsonIteratorFree(class_itr);
3420 char* col_list = buffer_release(select_buf);
3421 char* table = getSourceDefinition(meta);
3423 table = strdup( "(null)" );
3425 buffer_fadd(sql_buf, "SELECT %s FROM %s AS \"%s\"", col_list, table, core_class );
3430 char* join_clause = searchJOIN( join_hash, meta );
3431 OSRF_BUFFER_ADD_CHAR(sql_buf, ' ');
3432 OSRF_BUFFER_ADD(sql_buf, join_clause);
3436 osrfLogDebug(OSRF_LOG_MARK, "%s pre-predicate SQL = %s",
3437 MODULENAME, OSRF_BUFFER_C_STR(sql_buf));
3439 buffer_add(sql_buf, " WHERE ");
3441 char* pred = searchWHERE( search_hash, meta, AND_OP_JOIN, ctx );
3443 osrfAppSessionStatus(
3445 OSRF_STATUS_INTERNALSERVERERROR,
3446 "osrfMethodException",
3448 "Severe query error -- see error log for more details"
3450 buffer_free(sql_buf);
3451 if(defaultselhash) jsonObjectFree(defaultselhash);
3454 buffer_add(sql_buf, pred);
3459 char* string = NULL;
3460 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "order_by" )) ){
3462 growing_buffer* order_buf = buffer_init(128);
3465 jsonIterator* class_itr = jsonNewIterator( _tmp );
3466 while ( (snode = jsonIteratorNext( class_itr )) ) {
3468 if (!jsonObjectGetKeyConst(selhash,class_itr->key))
3471 if ( snode->type == JSON_HASH ) {
3473 jsonIterator* order_itr = jsonNewIterator( snode );
3474 while ( (onode = jsonIteratorNext( order_itr )) ) {
3476 if (!oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ))
3479 char* direction = NULL;
3480 if ( onode->type == JSON_HASH ) {
3481 if ( jsonObjectGetKeyConst( onode, "transform" ) ) {
3482 string = searchFieldTransform(
3484 oilsIDLFindPath( "/%s/fields/%s", class_itr->key, order_itr->key ),
3488 growing_buffer* field_buf = buffer_init(16);
3489 buffer_fadd(field_buf, "\"%s\".%s", class_itr->key, order_itr->key);
3490 string = buffer_release(field_buf);
3493 if ( (_tmp = jsonObjectGetKeyConst( onode, "direction" )) ) {
3494 direction = jsonObjectToSimpleString(_tmp);
3495 if (!strncasecmp(direction, "d", 1)) {
3497 direction = " DESC";
3505 string = strdup(order_itr->key);
3506 direction = jsonObjectToSimpleString(onode);
3507 if (!strncasecmp(direction, "d", 1)) {
3509 direction = " DESC";
3519 buffer_add(order_buf, ", ");
3522 buffer_add(order_buf, string);
3526 buffer_add(order_buf, direction);
3531 jsonIteratorFree(order_itr);
3534 string = jsonObjectToSimpleString(snode);
3535 buffer_add(order_buf, string);
3542 jsonIteratorFree(class_itr);
3544 string = buffer_release(order_buf);
3547 OSRF_BUFFER_ADD( sql_buf, " ORDER BY " );
3548 OSRF_BUFFER_ADD( sql_buf, string );
3554 if ( (_tmp = jsonObjectGetKeyConst( order_hash, "limit" )) ){
3555 string = jsonObjectToSimpleString(_tmp);
3564 _tmp = jsonObjectGetKeyConst( order_hash, "offset" );
3566 string = jsonObjectToSimpleString(_tmp);
3576 if (defaultselhash) jsonObjectFree(defaultselhash);
3578 OSRF_BUFFER_ADD_CHAR(sql_buf, ';');
3579 return buffer_release(sql_buf);
3582 int doJSONSearch ( osrfMethodContext* ctx ) {
3583 if(osrfMethodVerifyContext( ctx )) {
3584 osrfLogError( OSRF_LOG_MARK, "Invalid method context" );
3588 osrfLogDebug(OSRF_LOG_MARK, "Recieved query request");
3593 dbhandle = writehandle;
3595 jsonObject* hash = jsonObjectGetIndex(ctx->params, 0);
3599 if ( obj_is_true( jsonObjectGetKey( hash, "distinct" ) ) )
3600 flags |= SELECT_DISTINCT;
3602 if ( obj_is_true( jsonObjectGetKey( hash, "no_i18n" ) ) )
3603 flags |= DISABLE_I18N;
3605 osrfLogDebug(OSRF_LOG_MARK, "Building SQL ...");
3608 jsonObjectGetKey( hash, "select" ),
3609 jsonObjectGetKey( hash, "from" ),
3610 jsonObjectGetKey( hash, "where" ),
3611 jsonObjectGetKey( hash, "having" ),
3612 jsonObjectGetKey( hash, "order_by" ),
3613 jsonObjectGetKey( hash, "limit" ),
3614 jsonObjectGetKey( hash, "offset" ),
3623 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3624 dbi_result result = dbi_conn_query(dbhandle, sql);
3627 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3629 if (dbi_result_first_row(result)) {
3630 /* JSONify the result */
3631 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3634 jsonObject* return_val = oilsMakeJSONFromResult( result );
3635 osrfAppRespond( ctx, return_val );
3636 jsonObjectFree( return_val );
3637 } while (dbi_result_next_row(result));
3640 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
3643 osrfAppRespondComplete( ctx, NULL );
3645 /* clean up the query */
3646 dbi_result_free(result);
3650 osrfLogError(OSRF_LOG_MARK, "%s: Error with query [%s]", MODULENAME, sql);
3651 osrfAppSessionStatus(
3653 OSRF_STATUS_INTERNALSERVERERROR,
3654 "osrfMethodException",
3656 "Severe query error -- see error log for more details"
3664 static jsonObject* doFieldmapperSearch ( osrfMethodContext* ctx, osrfHash* meta,
3665 const jsonObject* params, int* err ) {
3668 dbhandle = writehandle;
3670 osrfHash* links = osrfHashGet(meta, "links");
3671 osrfHash* fields = osrfHashGet(meta, "fields");
3672 char* core_class = osrfHashGet(meta, "classname");
3673 char* pkey = osrfHashGet(meta, "primarykey");
3675 const jsonObject* _tmp;
3677 jsonObject* search_hash = jsonObjectGetIndex(params, 0);
3678 jsonObject* order_hash = jsonObjectGetIndex(params, 1);
3680 char* sql = buildSELECT( search_hash, order_hash, meta, ctx );
3682 osrfLogDebug(OSRF_LOG_MARK, "Problem building query, returning NULL");
3687 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
3689 dbi_result result = dbi_conn_query(dbhandle, sql);
3690 if( NULL == result ) {
3691 osrfLogError(OSRF_LOG_MARK, "%s: Error retrieving %s with query [%s]",
3692 MODULENAME, osrfHashGet(meta, "fieldmapper"), sql);
3693 osrfAppSessionStatus(
3695 OSRF_STATUS_INTERNALSERVERERROR,
3696 "osrfMethodException",
3698 "Severe query error -- see error log for more details"
3705 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
3708 jsonObject* res_list = jsonNewObjectType(JSON_ARRAY);
3709 osrfHash* dedup = osrfNewHash();
3711 if (dbi_result_first_row(result)) {
3712 /* JSONify the result */
3713 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
3715 obj = oilsMakeFieldmapperFromResult( result, meta );
3716 char* pkey_val = oilsFMGetString( obj, pkey );
3717 if ( osrfHashGet( dedup, pkey_val ) ) {
3718 jsonObjectFree(obj);
3721 osrfHashSet( dedup, pkey_val, pkey_val );
3722 jsonObjectPush(res_list, obj);
3724 } while (dbi_result_next_row(result));
3726 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s",
3730 osrfHashFree(dedup);
3731 /* clean up the query */
3732 dbi_result_free(result);
3735 if (res_list->size && order_hash) {
3736 _tmp = jsonObjectGetKeyConst( order_hash, "flesh" );
3738 int x = (int)jsonObjectGetNumber(_tmp);
3739 if (x == -1 || x > max_flesh_depth) x = max_flesh_depth;
3741 const jsonObject* temp_blob;
3742 if ((temp_blob = jsonObjectGetKeyConst( order_hash, "flesh_fields" )) && x > 0) {
3744 jsonObject* flesh_blob = jsonObjectClone( temp_blob );
3745 const jsonObject* flesh_fields = jsonObjectGetKeyConst( flesh_blob, core_class );
3747 osrfStringArray* link_fields = NULL;
3750 if (flesh_fields->size == 1) {
3751 char* _t = jsonObjectToSimpleString( jsonObjectGetIndex( flesh_fields, 0 ) );
3752 if (!strcmp(_t,"*")) link_fields = osrfHashKeys( links );
3758 link_fields = osrfNewStringArray(1);
3759 jsonIterator* _i = jsonNewIterator( flesh_fields );
3760 while ((_f = jsonIteratorNext( _i ))) {
3761 osrfStringArrayAdd( link_fields, jsonObjectToSimpleString( _f ) );
3763 jsonIteratorFree(_i);
3768 jsonIterator* itr = jsonNewIterator( res_list );
3769 while ((cur = jsonIteratorNext( itr ))) {
3774 while ( (link_field = osrfStringArrayGetString(link_fields, i++)) ) {
3776 osrfLogDebug(OSRF_LOG_MARK, "Starting to flesh %s", link_field);
3778 osrfHash* kid_link = osrfHashGet(links, link_field);
3779 if (!kid_link) continue;
3781 osrfHash* field = osrfHashGet(fields, link_field);
3782 if (!field) continue;
3784 osrfHash* value_field = field;
3786 osrfHash* kid_idl = osrfHashGet(oilsIDL(), osrfHashGet(kid_link, "class"));
3787 if (!kid_idl) continue;
3789 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3790 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3793 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) { // might_have
3794 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
3797 osrfStringArray* link_map = osrfHashGet( kid_link, "map" );
3799 if (link_map->size > 0) {
3800 jsonObject* _kid_key = jsonNewObjectType(JSON_ARRAY);
3803 jsonNewObject( osrfStringArrayGetString( link_map, 0 ) )
3808 osrfHashGet(kid_link, "class"),
3815 "Link field: %s, remote class: %s, fkey: %s, reltype: %s",
3816 osrfHashGet(kid_link, "field"),
3817 osrfHashGet(kid_link, "class"),
3818 osrfHashGet(kid_link, "key"),
3819 osrfHashGet(kid_link, "reltype")
3822 jsonObject* fake_params = jsonNewObjectType(JSON_ARRAY);
3823 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // search hash
3824 jsonObjectPush(fake_params, jsonNewObjectType(JSON_HASH)); // order/flesh hash
3826 osrfLogDebug(OSRF_LOG_MARK, "Creating dummy params object...");
3829 jsonObjectToSimpleString(
3832 atoi( osrfHashGet(value_field, "array_position") )
3837 osrfLogDebug(OSRF_LOG_MARK, "Nothing to search for!");
3842 jsonObjectGetIndex(fake_params, 0),
3843 osrfHashGet(kid_link, "key"),
3844 jsonNewObject( search_key )
3851 jsonObjectGetIndex(fake_params, 1),
3853 jsonNewNumberObject( (double)(x - 1 + link_map->size) )
3857 jsonObjectSetKey( jsonObjectGetIndex(fake_params, 1), "flesh_fields", jsonObjectClone(flesh_blob) );
3859 if (jsonObjectGetKeyConst(order_hash, "order_by")) {
3861 jsonObjectGetIndex(fake_params, 1),
3863 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "order_by"))
3867 if (jsonObjectGetKeyConst(order_hash, "select")) {
3869 jsonObjectGetIndex(fake_params, 1),
3871 jsonObjectClone(jsonObjectGetKeyConst(order_hash, "select"))
3875 jsonObject* kids = doFieldmapperSearch(ctx, kid_idl, fake_params, err);
3878 jsonObjectFree( fake_params );
3879 osrfStringArrayFree(link_fields);
3880 jsonIteratorFree(itr);
3881 jsonObjectFree(res_list);
3882 jsonObjectFree(flesh_blob);
3886 osrfLogDebug(OSRF_LOG_MARK, "Search for %s return %d linked objects", osrfHashGet(kid_link, "class"), kids->size);
3888 jsonObject* X = NULL;
3889 if ( link_map->size > 0 && kids->size > 0 ) {
3891 kids = jsonNewObjectType(JSON_ARRAY);
3893 jsonObject* _k_node;
3894 jsonIterator* _k = jsonNewIterator( X );
3895 while ((_k_node = jsonIteratorNext( _k ))) {
3901 (unsigned long)atoi(
3907 osrfHashGet(kid_link, "class")
3911 osrfStringArrayGetString( link_map, 0 )
3920 jsonIteratorFree(_k);
3923 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_a" )) || !(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) {
3924 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3927 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3928 jsonObjectClone( jsonObjectGetIndex(kids, 0) )
3932 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
3933 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
3936 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
3937 jsonObjectClone( kids )
3942 jsonObjectFree(kids);
3946 jsonObjectFree( kids );
3947 jsonObjectFree( fake_params );
3949 osrfLogDebug(OSRF_LOG_MARK, "Fleshing of %s complete", osrfHashGet(kid_link, "field"));
3950 osrfLogDebug(OSRF_LOG_MARK, "%s", jsonObjectToJSON(cur));
3954 jsonObjectFree( flesh_blob );
3955 osrfStringArrayFree(link_fields);
3956 jsonIteratorFree(itr);
3965 static jsonObject* doUpdate(osrfMethodContext* ctx, int* err ) {
3967 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
3969 jsonObject* target = jsonObjectGetIndex( ctx->params, 1 );
3971 jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
3974 if (!verifyObjectClass(ctx, target)) {
3979 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
3980 osrfAppSessionStatus(
3982 OSRF_STATUS_BADREQUEST,
3983 "osrfMethodException",
3985 "No active transaction -- required for UPDATE"
3991 // The following test is harmless but redundant. If a class is
3992 // readonly, we don't register an update method for it.
3993 if( str_is_true( osrfHashGet( meta, "readonly" ) ) ) {
3994 osrfAppSessionStatus(
3996 OSRF_STATUS_BADREQUEST,
3997 "osrfMethodException",
3999 "Cannot UPDATE readonly class"
4005 dbhandle = writehandle;
4007 char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
4009 // Set the last_xact_id
4010 int index = oilsIDL_ntop( target->classname, "last_xact_id" );
4012 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
4013 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
4016 char* pkey = osrfHashGet(meta, "primarykey");
4017 osrfHash* fields = osrfHashGet(meta, "fields");
4019 char* id = oilsFMGetString( target, pkey );
4023 "%s updating %s object with %s = %s",
4025 osrfHashGet(meta, "fieldmapper"),
4030 growing_buffer* sql = buffer_init(128);
4031 buffer_fadd(sql,"UPDATE %s SET", osrfHashGet(meta, "tablename"));
4036 osrfStringArray* field_list = osrfHashKeys( fields );
4037 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
4039 osrfHash* field = osrfHashGet( fields, field_name );
4041 if(!( strcmp( field_name, pkey ) )) continue;
4042 if( str_is_true( osrfHashGet(osrfHashGet(fields,field_name), "virtual") ) )
4045 const jsonObject* field_object = oilsFMGetObject( target, field_name );
4048 if (field_object && field_object->classname) {
4049 value = oilsFMGetString(
4051 (char*)oilsIDLFindPath("/%s/primarykey", field_object->classname)
4054 value = jsonObjectToSimpleString( field_object );
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 ( !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" )