1 #include "opensrf/osrf_application.h"
2 #include "opensrf/osrf_settings.h"
3 #include "opensrf/utils.h"
4 #include "objson/object.h"
5 #include "opensrf/log.h"
6 #include "oils_utils.h"
7 #include "oils_constants.h"
8 #include "oils_event.h"
16 #define OILS_AUTH_CACHE_PRFX "oils_cstore_"
17 #define MODULENAME "open-ils.cstore"
18 #define PERSIST_NS "http://open-ils.org/spec/opensrf/IDL/persistance/v1"
19 #define OBJECT_NS "http://open-ils.org/spec/opensrf/IDL/objects/v1"
20 #define BASE_NS "http://opensrf.org/spec/IDL/base/v1"
22 int osrfAppChildInit();
23 int osrfAppInitialize();
25 int verifyObjectClass ( osrfMethodContext*, jsonObject* );
27 int beginTransaction ( osrfMethodContext* );
28 int commitTransaction ( osrfMethodContext* );
29 int rollbackTransaction ( osrfMethodContext* );
31 int setSavepoint ( osrfMethodContext* );
32 int releaseSavepoint ( osrfMethodContext* );
33 int rollbackSavepoint ( osrfMethodContext* );
35 int dispatchCRUDMethod ( osrfMethodContext* );
36 jsonObject* doCreate ( osrfMethodContext*, int* );
37 jsonObject* doRetrieve ( osrfMethodContext*, int* );
38 jsonObject* doUpdate ( osrfMethodContext*, int* );
39 jsonObject* doDelete ( osrfMethodContext*, int* );
40 jsonObject* doSearch ( osrfMethodContext*, osrfHash*, jsonObject*, int* );
41 jsonObject* oilsMakeJSONFromResult( dbi_result, osrfHash* );
43 char* searchWriteSimplePredicate ( osrfHash*, const char*, const char*, const char* );
44 char* searchSimplePredicate ( const char*, osrfHash*, jsonObject* );
45 char* searchFunctionPredicate ( osrfHash*, jsonObjectNode* );
46 char* searchFieldTransformPredicate ( osrfHash*, jsonObjectNode* );
47 char* searchBETWEENPredicate ( osrfHash*, jsonObject* );
48 char* searchINPredicate ( osrfHash*, jsonObject* );
49 char* searchPredicate ( osrfHash*, jsonObject* );
51 void userDataFree( void* );
52 void sessionDataFree( char*, void* );
54 dbi_conn writehandle; /* our MASTER db connection */
55 dbi_conn dbhandle; /* our CURRENT db connection */
57 jsonObject* jsonNULL = NULL; //
60 /* parse and store the IDL here */
63 int osrfAppInitialize() {
65 // first we register all the transaction and savepoint methods
66 osrfAppRegisterMethod( MODULENAME, "open-ils.cstore.transaction.begin", "beginTransaction", "", 0, 0 );
67 osrfAppRegisterMethod( MODULENAME, "open-ils.cstore.transaction.commit", "commitTransaction", "", 0, 0 );
68 osrfAppRegisterMethod( MODULENAME, "open-ils.cstore.transaction.rollback", "rollbackTransaction", "", 0, 0 );
70 osrfAppRegisterMethod( MODULENAME, "open-ils.cstore.savepoint.set", "setSavepoint", "", 1, 0 );
71 osrfAppRegisterMethod( MODULENAME, "open-ils.cstore.savepoint.release", "releaseSavepoint", "", 1, 0 );
72 osrfAppRegisterMethod( MODULENAME, "open-ils.cstore.savepoint.rollback", "rollbackSavepoint", "", 1, 0 );
75 osrfLogInfo(OSRF_LOG_MARK, "Initializing the CStore Server...");
76 osrfLogInfo(OSRF_LOG_MARK, "Finding XML file...");
78 char * idl_filename = osrf_settings_host_value("/apps/%s/app_settings/IDL", MODULENAME);
79 osrfLogInfo(OSRF_LOG_MARK, "Found file:");
80 osrfLogInfo(OSRF_LOG_MARK, idl_filename);
82 idl = oilsIDLInit( idl_filename );
85 osrfLogError(OSRF_LOG_MARK, "Problem loading the IDL. Seacrest out!");
89 osrfStringArray* global_methods = osrfNewStringArray(6);
91 osrfStringArrayAdd( global_methods, "create" );
92 osrfStringArrayAdd( global_methods, "retrieve" );
93 osrfStringArrayAdd( global_methods, "update" );
94 osrfStringArrayAdd( global_methods, "delete" );
95 osrfStringArrayAdd( global_methods, "search" );
96 osrfStringArrayAdd( global_methods, "id_list" );
100 osrfStringArray* classes = osrfHashKeys( idl );
101 osrfLogDebug(OSRF_LOG_MARK, "%d classes loaded", classes->size );
102 osrfLogDebug(OSRF_LOG_MARK, "At least %d methods will be generated", classes->size * global_methods->size);
104 while ( (classname = osrfStringArrayGetString(classes, c_index++)) ) {
105 osrfLogInfo(OSRF_LOG_MARK, "Generating class methods for %s", classname);
107 osrfHash* idlClass = osrfHashGet(idl, classname);
109 char* virt = osrfHashGet(idlClass, "virtual");
110 if (virt && !strcmp( virt, "true")) {
111 osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
115 osrfLogDebug(OSRF_LOG_MARK, "HERE");
122 osrfHash* method_meta;
123 while ( (method_type = osrfStringArrayGetString(global_methods, i++)) ) {
124 osrfLogDebug(OSRF_LOG_MARK, "Using files to build %s class methods for %s", method_type, classname);
126 if (!osrfHashGet(idlClass, "fieldmapper")) continue;
128 method_meta = osrfNewHash();
129 osrfHashSet(method_meta, idlClass, "class");
131 _fm = strdup( (char*)osrfHashGet(idlClass, "fieldmapper") );
132 part = strtok_r(_fm, ":", &st_tmp);
134 growing_buffer* method_name = buffer_init(64);
135 buffer_fadd(method_name, "%s.direct.%s", MODULENAME, part);
137 while ((part = strtok_r(NULL, ":", &st_tmp))) {
138 buffer_fadd(method_name, ".%s", part);
140 buffer_fadd(method_name, ".%s", method_type);
143 char* method = buffer_data(method_name);
144 buffer_free(method_name);
147 osrfHashSet( method_meta, method, "methodname" );
148 osrfHashSet( method_meta, method_type, "methodtype" );
151 if (!(strcmp( method_type, "search" )) || !(strcmp( method_type, "id_list" ))) {
152 flags = flags | OSRF_METHOD_STREAMING;
155 osrfAppRegisterExtendedMethod(
158 "dispatchCRUDMethod",
171 * Connects to the database
173 int osrfAppChildInit() {
175 osrfLogDebug(OSRF_LOG_MARK, "Attempting to initialize libdbi...");
176 dbi_initialize(NULL);
177 osrfLogDebug(OSRF_LOG_MARK, "... libdbi initialized.");
179 char* driver = osrf_settings_host_value("/apps/%s/app_settings/driver", MODULENAME);
180 char* user = osrf_settings_host_value("/apps/%s/app_settings/database/user", MODULENAME);
181 char* host = osrf_settings_host_value("/apps/%s/app_settings/database/host", MODULENAME);
182 char* port = osrf_settings_host_value("/apps/%s/app_settings/database/port", MODULENAME);
183 char* db = osrf_settings_host_value("/apps/%s/app_settings/database/db", MODULENAME);
184 char* pw = osrf_settings_host_value("/apps/%s/app_settings/database/pw", MODULENAME);
186 osrfLogDebug(OSRF_LOG_MARK, "Attempting to load the database driver [%s]...", driver);
187 writehandle = dbi_conn_new(driver);
190 osrfLogError(OSRF_LOG_MARK, "Error loading database driver [%s]", driver);
193 osrfLogDebug(OSRF_LOG_MARK, "Database driver [%s] seems OK", driver);
195 osrfLogInfo(OSRF_LOG_MARK, "%s connecting to database. host=%s, "
196 "port=%s, user=%s, pw=%s, db=%s", MODULENAME, host, port, user, pw, db );
198 if(host) dbi_conn_set_option(writehandle, "host", host );
199 if(port) dbi_conn_set_option_numeric( writehandle, "port", atoi(port) );
200 if(user) dbi_conn_set_option(writehandle, "username", user);
201 if(pw) dbi_conn_set_option(writehandle, "password", pw );
202 if(db) dbi_conn_set_option(writehandle, "dbname", db );
211 if (dbi_conn_connect(writehandle) < 0) {
212 dbi_conn_error(writehandle, &err);
213 osrfLogError( OSRF_LOG_MARK, "Error connecting to database: %s", err);
217 osrfLogInfo(OSRF_LOG_MARK, "%s successfully connected to the database", MODULENAME);
223 osrfStringArray* classes = osrfHashKeys( idl );
225 while ( (classname = osrfStringArrayGetString(classes, i++)) ) {
226 osrfHash* class = osrfHashGet( idl, classname );
227 osrfHash* fields = osrfHashGet( class, "fields" );
229 char* virt = osrfHashGet(class, "virtual");
230 if (virt && !strcmp( virt, "true")) {
231 osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
236 growing_buffer* sql_buf = buffer_init(32);
237 buffer_fadd( sql_buf, "SELECT * FROM %s WHERE 1=0;", osrfHashGet(class, "tablename") );
239 char* sql = buffer_data(sql_buf);
240 buffer_free(sql_buf);
241 osrfLogDebug(OSRF_LOG_MARK, "%s Investigatory SQL = %s", MODULENAME, sql);
243 dbi_result result = dbi_conn_query(writehandle, sql);
249 const char* columnName;
251 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
253 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
255 /* fetch the fieldmapper index */
256 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
258 osrfLogDebug(OSRF_LOG_MARK, "Found [%s] in IDL hash...", (char*)columnName);
260 /* determine the field type and storage attributes */
261 type = dbi_result_get_field_type(result, columnName);
262 attr = dbi_result_get_field_attribs(result, columnName);
266 case DBI_TYPE_INTEGER :
268 if ( !osrfHashGet(_f, "primitive") )
269 osrfHashSet(_f,"number", "primitive");
271 if( attr & DBI_INTEGER_SIZE8 )
272 osrfHashSet(_f,"INT8", "datatype");
274 osrfHashSet(_f,"INT", "datatype");
277 case DBI_TYPE_DECIMAL :
278 if ( !osrfHashGet(_f, "primitive") )
279 osrfHashSet(_f,"number", "primitive");
281 osrfHashSet(_f,"NUMERIC", "datatype");
284 case DBI_TYPE_STRING :
285 if ( !osrfHashGet(_f, "primitive") )
286 osrfHashSet(_f,"string", "primitive");
287 osrfHashSet(_f,"TEXT", "datatype");
290 case DBI_TYPE_DATETIME :
291 if ( !osrfHashGet(_f, "primitive") )
292 osrfHashSet(_f,"string", "primitive");
294 osrfHashSet(_f,"TIMESTAMP", "datatype");
297 case DBI_TYPE_BINARY :
298 if ( !osrfHashGet(_f, "primitive") )
299 osrfHashSet(_f,"string", "primitive");
301 osrfHashSet(_f,"BYTEA", "datatype");
306 "Setting [%s] to primitive [%s] and datatype [%s]...",
308 osrfHashGet(_f, "primitive"),
309 osrfHashGet(_f, "datatype")
313 dbi_result_free(result);
315 osrfLogDebug(OSRF_LOG_MARK, "No data found for class [%s]...", (char*)classname);
319 osrfStringArrayFree(classes);
324 void userDataFree( void* blob ) {
325 osrfHashFree( (osrfHash*)blob );
329 void sessionDataFree( char* key, void* item ) {
330 if (!(strcmp(key,"xact_id"))) {
332 dbi_conn_query(writehandle, "ROLLBACK;");
339 int beginTransaction ( osrfMethodContext* ctx ) {
340 OSRF_METHOD_VERIFY_CONTEXT(ctx);
342 dbi_result result = dbi_conn_query(writehandle, "START TRANSACTION;");
344 osrfLogError(OSRF_LOG_MARK, "%s: Error starting transaction", MODULENAME );
345 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error starting transaction" );
348 jsonObject* ret = jsonNewObject(ctx->session->session_id);
349 osrfAppRespondComplete( ctx, ret );
352 if (!ctx->session->userData) {
353 ctx->session->userData = osrfNewHash();
354 ((osrfHash*)ctx->session->userData)->freeItem = &sessionDataFree;
357 osrfHashSet( (osrfHash*)ctx->session->userData, strdup( ctx->session->session_id ), "xact_id" );
358 ctx->session->userDataFree = &userDataFree;
364 int setSavepoint ( osrfMethodContext* ctx ) {
365 OSRF_METHOD_VERIFY_CONTEXT(ctx);
367 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
369 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
370 osrfAppSessionStatus(
372 OSRF_STATUS_INTERNALSERVERERROR,
373 "osrfMethodException",
375 "No active transaction -- required for savepoints"
380 dbi_result result = dbi_conn_queryf(writehandle, "SAVEPOINT \"%s\";", spName);
384 "%s: Error creating savepoint %s in transaction %s",
387 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
389 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error creating savepoint" );
392 jsonObject* ret = jsonNewObject(spName);
393 osrfAppRespondComplete( ctx, ret );
399 int releaseSavepoint ( osrfMethodContext* ctx ) {
400 OSRF_METHOD_VERIFY_CONTEXT(ctx);
402 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
404 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
405 osrfAppSessionStatus(
407 OSRF_STATUS_INTERNALSERVERERROR,
408 "osrfMethodException",
410 "No active transaction -- required for savepoints"
415 dbi_result result = dbi_conn_queryf(writehandle, "RELEASE SAVEPOINT \"%s\";", spName);
419 "%s: Error releasing savepoint %s in transaction %s",
422 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
424 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error releasing savepoint" );
427 jsonObject* ret = jsonNewObject(spName);
428 osrfAppRespondComplete( ctx, ret );
434 int rollbackSavepoint ( osrfMethodContext* ctx ) {
435 OSRF_METHOD_VERIFY_CONTEXT(ctx);
437 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
439 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
440 osrfAppSessionStatus(
442 OSRF_STATUS_INTERNALSERVERERROR,
443 "osrfMethodException",
445 "No active transaction -- required for savepoints"
450 dbi_result result = dbi_conn_queryf(writehandle, "ROLLBACK TO SAVEPOINT \"%s\";", spName);
454 "%s: Error rolling back savepoint %s in transaction %s",
457 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
459 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back savepoint" );
462 jsonObject* ret = jsonNewObject(spName);
463 osrfAppRespondComplete( ctx, ret );
469 int commitTransaction ( osrfMethodContext* ctx ) {
470 OSRF_METHOD_VERIFY_CONTEXT(ctx);
472 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
473 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to commit" );
477 dbi_result result = dbi_conn_query(writehandle, "COMMIT;");
479 osrfLogError(OSRF_LOG_MARK, "%s: Error committing transaction", MODULENAME );
480 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error committing transaction" );
483 osrfHashRemove(ctx->session->userData, "xact_id");
484 jsonObject* ret = jsonNewObject(ctx->session->session_id);
485 osrfAppRespondComplete( ctx, ret );
491 int rollbackTransaction ( osrfMethodContext* ctx ) {
492 OSRF_METHOD_VERIFY_CONTEXT(ctx);
494 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
495 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to roll back" );
499 dbi_result result = dbi_conn_query(writehandle, "ROLLBACK;");
501 osrfLogError(OSRF_LOG_MARK, "%s: Error rolling back transaction", MODULENAME );
502 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back transaction" );
505 osrfHashRemove(ctx->session->userData, "xact_id");
506 jsonObject* ret = jsonNewObject(ctx->session->session_id);
507 osrfAppRespondComplete( ctx, ret );
513 int dispatchCRUDMethod ( osrfMethodContext* ctx ) {
514 OSRF_METHOD_VERIFY_CONTEXT(ctx);
516 osrfHash* meta = (osrfHash*) ctx->method->userData;
517 osrfHash* class_obj = osrfHashGet( meta, "class" );
521 jsonObject * obj = NULL;
522 if (!strcmp( (char*)osrfHashGet(meta, "methodtype"), "create"))
523 obj = doCreate(ctx, &err);
525 if (!strcmp( (char*)osrfHashGet(meta, "methodtype"), "retrieve"))
526 obj = doRetrieve(ctx, &err);
528 if (!strcmp( (char*)osrfHashGet(meta, "methodtype"), "update"))
529 obj = doUpdate(ctx, &err);
531 if (!strcmp( (char*)osrfHashGet(meta, "methodtype"), "delete"))
532 obj = doDelete(ctx, &err);
534 if (!strcmp( (char*)osrfHashGet(meta, "methodtype"), "search")) {
536 obj = doSearch(ctx, class_obj, ctx->params, &err);
540 jsonObjectIterator* itr = jsonNewObjectIterator( obj );
541 while ((cur = jsonObjectIteratorNext( itr ))) {
542 osrfAppRespond( ctx, jsonObjectClone(cur->item) );
544 jsonObjectIteratorFree(itr);
545 osrfAppRespondComplete( ctx, NULL );
547 } else if (!strcmp( (char*)osrfHashGet(meta, "methodtype"), "id_list")) {
549 jsonObject* _p = jsonObjectClone( ctx->params );
550 if (jsonObjectGetIndex( _p, 1 )) {
551 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh" );
552 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh_columns" );
554 jsonObjectSetIndex( _p, 1, jsonParseString("{}") );
557 growing_buffer* sel_list = buffer_init(16);
558 buffer_fadd(sel_list, "{ \"%s\":[\"%s\"] }", osrfHashGet( class_obj, "classname" ), osrfHashGet( class_obj, "primarykey" ));
559 char* _s = buffer_data(sel_list);
560 buffer_free(sel_list);
562 jsonObjectSetKey( jsonObjectGetIndex( _p, 1 ), "select", jsonParseString(_s) );
563 osrfLogDebug(OSRF_LOG_MARK, "%s: Select qualifer set to [%s]", MODULENAME, _s);
566 obj = doSearch(ctx, class_obj, _p, &err);
570 jsonObjectIterator* itr = jsonNewObjectIterator( obj );
571 while ((cur = jsonObjectIteratorNext( itr ))) {
580 osrfHashGet( class_obj, "fields" ),
581 osrfHashGet( class_obj, "primarykey")
590 jsonObjectIteratorFree(itr);
591 osrfAppRespondComplete( ctx, NULL );
594 osrfAppRespondComplete( ctx, obj );
602 int verifyObjectClass ( osrfMethodContext* ctx, jsonObject* param ) {
604 osrfHash* meta = (osrfHash*) ctx->method->userData;
605 osrfHash* class = osrfHashGet( meta, "class" );
607 if ((strcmp( osrfHashGet(class, "classname"), param->classname ))) {
609 growing_buffer* msg = buffer_init(128);
612 "%s: %s method for type %s was passed a %s",
614 osrfHashGet(meta, "methodtype"),
615 osrfHashGet(class, "classname"),
619 char* m = buffer_data(msg);
620 osrfAppSessionStatus( ctx->session, OSRF_STATUS_BADREQUEST, "osrfMethodException", ctx->request, m );
630 jsonObject* doCreate(osrfMethodContext* ctx, int* err ) {
632 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
633 jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
634 jsonObject* options = jsonObjectGetIndex( ctx->params, 1 );
636 if (!verifyObjectClass(ctx, target)) {
641 osrfLogDebug( OSRF_LOG_MARK, "Object seems to be of the correct type" );
643 if (!ctx->session || !ctx->session->userData || !osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
644 osrfLogError( OSRF_LOG_MARK, "No active transaction -- required for CREATE" );
646 osrfAppSessionStatus(
648 OSRF_STATUS_BADREQUEST,
649 "osrfMethodException",
651 "No active transaction -- required for CREATE"
657 char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
659 // Set the last_xact_id
660 osrfHash* last_xact_id;
661 if ((last_xact_id = oilsIDLFindPath("/%s/fields/last_xact_id", target->classname))) {
662 int index = atoi( osrfHashGet(last_xact_id, "array_position") );
663 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
664 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
667 osrfLogDebug( OSRF_LOG_MARK, "There is a transaction running..." );
669 dbhandle = writehandle;
671 osrfHash* fields = osrfHashGet(meta, "fields");
672 char* pkey = osrfHashGet(meta, "primarykey");
673 char* seq = osrfHashGet(meta, "sequence");
675 growing_buffer* table_buf = buffer_init(128);
676 growing_buffer* col_buf = buffer_init(128);
677 growing_buffer* val_buf = buffer_init(128);
679 buffer_fadd(table_buf,"INSERT INTO %s", osrfHashGet(meta, "tablename"));
680 buffer_add(col_buf,"(");
681 buffer_add(val_buf,"VALUES (");
687 osrfStringArray* field_list = osrfHashKeys( fields );
688 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
690 osrfHash* field = osrfHashGet( fields, field_name );
692 if(!( strcmp( osrfHashGet(osrfHashGet(fields,field_name), "virtual"), "true" ) )) continue;
694 osrfLogDebug( OSRF_LOG_MARK, "HERE..." );
696 int pos = atoi(osrfHashGet(field, "array_position"));
697 char* value = jsonObjectToSimpleString( jsonObjectGetIndex( target, pos ) );
699 osrfLogDebug( OSRF_LOG_MARK, "HERE..." );
704 buffer_add(col_buf, ",");
705 buffer_add(val_buf, ",");
708 buffer_add(col_buf, field_name);
710 osrfLogDebug( OSRF_LOG_MARK, "HERE..." );
712 if (!jsonObjectGetIndex(target, pos) || jsonObjectGetIndex(target, pos)->type == JSON_NULL) {
713 osrfLogDebug( OSRF_LOG_MARK, "HERE..." );
715 buffer_add( val_buf, "DEFAULT" );
717 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
718 osrfLogDebug( OSRF_LOG_MARK, "HERE..." );
720 if ( !strcmp(osrfHashGet(field, "datatype"), "INT8") ) {
721 buffer_fadd( val_buf, "%lld", atol(value) );
723 } else if ( !strcmp(osrfHashGet(field, "datatype"), "INT") ) {
724 buffer_fadd( val_buf, "%ld", atoll(value) );
726 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
727 buffer_fadd( val_buf, "%f", atof(value) );
730 osrfLogDebug( OSRF_LOG_MARK, "HERE..." );
732 if ( dbi_conn_quote_string(writehandle, &value) ) {
733 buffer_fadd( val_buf, "%s", value );
736 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
737 osrfAppSessionStatus(
739 OSRF_STATUS_INTERNALSERVERERROR,
740 "osrfMethodException",
742 "Error quoting string -- please see the error log for more details"
745 buffer_free(table_buf);
746 buffer_free(col_buf);
747 buffer_free(val_buf);
753 osrfLogDebug( OSRF_LOG_MARK, "HERE..." );
760 buffer_add(col_buf,")");
761 buffer_add(val_buf,")");
763 growing_buffer* sql = buffer_init(128);
767 buffer_data(table_buf),
768 buffer_data(col_buf),
771 buffer_free(table_buf);
772 buffer_free(col_buf);
773 buffer_free(val_buf);
775 char* query = buffer_data(sql);
778 osrfLogDebug(OSRF_LOG_MARK, "%s: Insert SQL [%s]", MODULENAME, query);
781 dbi_result result = dbi_conn_query(writehandle, query);
783 jsonObject* obj = NULL;
786 obj = jsonNewObject(NULL);
789 "%s ERROR inserting %s object using query [%s]",
791 osrfHashGet(meta, "fieldmapper"),
794 osrfAppSessionStatus(
796 OSRF_STATUS_INTERNALSERVERERROR,
797 "osrfMethodException",
799 "INSERT error -- please see the error log for more details"
804 int pos = atoi(osrfHashGet( osrfHashGet(fields, pkey), "array_position" ));
805 char* id = jsonObjectToSimpleString(jsonObjectGetIndex(target, pos));
807 unsigned long long new_id = dbi_conn_sequence_last(writehandle, seq);
808 growing_buffer* _id = buffer_init(10);
809 buffer_fadd(_id, "%lld", new_id);
810 id = buffer_data(_id);
815 || !jsonObjectGetKey( options, "quiet")
816 || strcmp( jsonObjectToSimpleString(jsonObjectGetKey( options, "quiet")), "true" )
819 jsonObject* fake_params = jsonParseString("[]");
820 jsonObjectPush(fake_params, jsonParseString("{}"));
823 jsonObjectGetIndex(fake_params, 0),
824 osrfHashGet(meta, "primarykey"),
828 jsonObject* list = doSearch( ctx,meta, fake_params, err);
831 jsonObjectFree( fake_params );
834 obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
837 jsonObjectFree( list );
838 jsonObjectFree( fake_params );
841 obj = jsonNewObject(id);
853 jsonObject* doRetrieve(osrfMethodContext* ctx, int* err ) {
855 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
859 char* id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
860 jsonObject* order_hash = jsonObjectGetIndex(ctx->params, 1);
864 "%s retrieving %s object with id %s",
866 osrfHashGet(meta, "fieldmapper"),
870 jsonObject* fake_params = jsonParseString("[]");
871 jsonObjectPush(fake_params, jsonParseString("{}"));
874 jsonObjectGetIndex(fake_params, 0),
875 osrfHashGet(meta, "primarykey"),
879 if (order_hash) jsonObjectPush(fake_params, jsonObjectClone(order_hash) );
881 jsonObject* list = doSearch( ctx,meta, fake_params, err);
884 jsonObjectFree( fake_params );
888 obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
890 jsonObjectFree( list );
891 jsonObjectFree( fake_params );
896 char* jsonNumberToDBString ( osrfHash* field, jsonObject* value ) {
897 growing_buffer* val_buf = buffer_init(32);
899 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", 3) ) {
900 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%ld", (long)jsonObjectGetNumber(value) );
901 else buffer_fadd( val_buf, "%ld", atol(jsonObjectToSimpleString(value)) );
903 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
904 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%f", jsonObjectGetNumber(value) );
905 else buffer_fadd( val_buf, "%f", atof(jsonObjectToSimpleString(value)) );
908 char* pred = buffer_data(val_buf);
909 buffer_free(val_buf);
914 char* searchINPredicate (osrfHash* field, jsonObject* node) {
915 growing_buffer* sql_buf = buffer_init(32);
920 osrfHashGet(field, "name")
923 int in_item_index = 0;
924 int in_item_first = 1;
926 while ( (in_item = jsonObjectGetIndex(node, in_item_index++)) ) {
931 buffer_add(sql_buf, ", ");
933 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
934 char* val = jsonNumberToDBString( field, in_item );
935 buffer_fadd( sql_buf, "%s", val );
939 char* key_string = jsonObjectToSimpleString(in_item);
940 if ( dbi_conn_quote_string(dbhandle, &key_string) ) {
941 buffer_fadd( sql_buf, "%s", key_string );
944 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, key_string);
946 buffer_free(sql_buf);
957 char* pred = buffer_data(sql_buf);
958 buffer_free(sql_buf);
963 char* searchValueTransform( jsonObject* array ) {
964 growing_buffer* sql_buf = buffer_init(32);
967 int func_item_index = 0;
968 int func_item_first = 2;
969 jsonObject* func_item;
970 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
972 val = jsonObjectToSimpleString(func_item);
974 if (func_item_first == 2) {
975 buffer_fadd(sql_buf, "%s( ", val);
984 buffer_add(sql_buf, ", ");
986 if ( dbi_conn_quote_string(dbhandle, &val) ) {
987 buffer_fadd( sql_buf, "%s", val );
990 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
992 buffer_free(sql_buf);
1002 char* pred = buffer_data(sql_buf);
1003 buffer_free(sql_buf);
1008 char* searchFunctionPredicate (osrfHash* field, jsonObjectNode* node) {
1009 growing_buffer* sql_buf = buffer_init(32);
1011 char* val = searchValueTransform(node->item);
1016 osrfHashGet(field, "name"),
1021 char* pred = buffer_data(sql_buf);
1022 buffer_free(sql_buf);
1028 char* searchFieldTransformPredicate (osrfHash* field, jsonObjectNode* node) {
1029 growing_buffer* sql_buf = buffer_init(32);
1031 char* field_transform = jsonObjectToSimpleString( jsonObjectGetKey( node->item, "transform" ) );
1034 if (jsonObjectGetKey( node->item, "value" )->type == JSON_ARRAY) {
1035 value = searchValueTransform(jsonObjectGetKey( node->item, "value" ));
1036 } else if (jsonObjectGetKey( node->item, "value" )->type != JSON_NULL) {
1037 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1038 value = jsonNumberToDBString( field, jsonObjectGetKey( node->item, "value" ) );
1040 value = jsonObjectToSimpleString(jsonObjectGetKey( node->item, "value" ));
1041 if ( !dbi_conn_quote_string(dbhandle, &value) ) {
1042 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, value);
1053 osrfHashGet(field, "name"),
1058 char* pred = buffer_data(sql_buf);
1059 buffer_free(sql_buf);
1064 char* searchSimplePredicate (const char* orig_op, osrfHash* field, jsonObject* node) {
1068 if (node->type != JSON_NULL) {
1069 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1070 val = jsonNumberToDBString( field, node );
1072 val = jsonObjectToSimpleString(node);
1076 char* pred = searchWriteSimplePredicate( field, osrfHashGet(field, "name"), orig_op, val );
1083 char* searchWriteSimplePredicate ( osrfHash* field, const char* left, const char* orig_op, const char* right ) {
1087 if (right == NULL) {
1088 val = strdup("NULL");
1090 if (strcmp( orig_op, "=" ))
1091 op = strdup("IS NOT");
1095 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1096 val = strdup(right);
1097 op = strdup(orig_op);
1100 val = strdup(right);
1101 if ( !dbi_conn_quote_string(dbhandle, &val) ) {
1102 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1106 op = strdup(orig_op);
1109 growing_buffer* sql_buf = buffer_init(16);
1110 buffer_fadd( sql_buf, "%s %s %s", left, op, val );
1114 char* pred = buffer_data(sql_buf);
1115 buffer_free(sql_buf);
1121 char* searchBETWEENPredicate (osrfHash* field, jsonObject* node) {
1126 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1127 x_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,0));
1128 y_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,1));
1131 x_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,0));
1132 y_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,1));
1133 if ( !(dbi_conn_quote_string(dbhandle, &x_string) && dbi_conn_quote_string(dbhandle, &y_string)) ) {
1134 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key strings [%s] and [%s]", MODULENAME, x_string, y_string);
1141 growing_buffer* sql_buf = buffer_init(32);
1142 buffer_fadd( sql_buf, "%s BETWEEN %s AND %s", osrfHashGet(field, "name"), x_string, y_string );
1146 char* pred = buffer_data(sql_buf);
1147 buffer_free(sql_buf);
1152 char* searchPredicate ( osrfHash* field, jsonObject* node ) {
1155 if (node->type == JSON_ARRAY) { // equality IN search
1156 pred = searchINPredicate( field, node );
1157 } else if (node->type == JSON_HASH) { // non-equality search
1158 jsonObjectNode* pred_node;
1159 jsonObjectIterator* pred_itr = jsonNewObjectIterator( node );
1160 while ( (pred_node = jsonObjectIteratorNext( pred_itr )) ) {
1161 if ( !(strcasecmp( pred_node->key,"between" )) )
1162 pred = searchBETWEENPredicate( field, pred_node->item );
1163 else if ( !(strcasecmp( pred_node->key,"in" )) )
1164 pred = searchINPredicate( field, pred_node->item );
1165 else if ( pred_node->item->type == JSON_ARRAY )
1166 pred = searchFunctionPredicate( field, pred_node );
1167 else if ( pred_node->item->type == JSON_HASH )
1168 pred = searchFieldTransformPredicate( field, pred_node );
1170 pred = searchSimplePredicate( pred_node->key, field, pred_node->item );
1174 } else if (node->type == JSON_NULL) { // IS NULL search
1175 growing_buffer* _p = buffer_init(16);
1179 osrfHashGet(field, "name")
1181 pred = buffer_data(_p);
1183 } else { // equality search
1184 pred = searchSimplePredicate( "=", field, node );
1191 jsonObject* doSearch(osrfMethodContext* ctx, osrfHash* meta, jsonObject* params, int* err ) {
1194 dbhandle = writehandle;
1196 osrfHash* links = osrfHashGet(meta, "links");
1197 osrfHash* fields = osrfHashGet(meta, "fields");
1198 char* core_class = osrfHashGet(meta, "classname");
1200 jsonObjectNode* node = NULL;
1201 jsonObjectNode* snode = NULL;
1204 jsonObject* search_hash = jsonObjectGetIndex(params, 0);
1205 jsonObject* order_hash = jsonObjectGetIndex(params, 1);
1207 growing_buffer* sql_buf = buffer_init(128);
1208 buffer_add(sql_buf, "SELECT");
1211 if ( (_tmp = jsonObjectGetKey( order_hash, "select" )) ) {
1213 jsonObjectIterator* class_itr = jsonNewObjectIterator( _tmp );
1214 while ( (snode = jsonObjectIteratorNext( class_itr )) ) {
1216 osrfHash* idlClass = osrfHashGet( idl, snode->key );
1217 if (!idlClass) continue;
1218 char* cname = osrfHashGet(idlClass, "classname");
1220 jsonObjectIterator* select_itr = jsonNewObjectIterator( snode->item );
1221 while ( (node = jsonObjectIteratorNext( select_itr )) ) {
1222 osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), jsonObjectToSimpleString(node->item) );
1223 char* fname = osrfHashGet(field, "name");
1225 if (!field) continue;
1230 buffer_add(sql_buf, ",");
1233 buffer_fadd(sql_buf, " \"%s\".%s", cname, fname, cname, fname);
1237 buffer_add(sql_buf, " *");
1240 buffer_fadd(sql_buf, " FROM %s AS \"%s\" WHERE ", osrfHashGet(meta, "tablename"), core_class );
1245 jsonObjectIterator* search_itr = jsonNewObjectIterator( search_hash );
1246 while ( (node = jsonObjectIteratorNext( search_itr )) ) {
1247 osrfHash* field = osrfHashGet( fields, node->key );
1249 if (!field) continue;
1254 buffer_add(sql_buf, " AND ");
1257 pred = searchPredicate( field, node->item);
1258 buffer_fadd( sql_buf, "%s", pred );
1262 jsonObjectIteratorFree(search_itr);
1266 if ( (_tmp = jsonObjectGetKey( jsonObjectGetKey( order_hash, "order_by" ), core_class ) ) ){
1267 string = jsonObjectToSimpleString(_tmp);
1276 if ( (_tmp = jsonObjectGetKey( order_hash, "limit" )) ){
1277 string = jsonObjectToSimpleString(_tmp);
1286 _tmp = jsonObjectGetKey( order_hash, "offset" );
1288 string = jsonObjectToSimpleString(_tmp);
1298 buffer_add(sql_buf, ";");
1300 char* sql = buffer_data(sql_buf);
1301 buffer_free(sql_buf);
1303 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
1304 dbi_result result = dbi_conn_query(dbhandle, sql);
1306 jsonObject* res_list = jsonParseString("[]");
1308 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
1310 if (dbi_result_first_row(result)) {
1311 /* JSONify the result */
1312 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
1314 obj = oilsMakeJSONFromResult( result, meta );
1315 jsonObjectPush(res_list, obj);
1316 } while (dbi_result_next_row(result));
1318 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
1321 /* clean up the query */
1322 dbi_result_free(result);
1325 osrfLogError(OSRF_LOG_MARK, "%s: Error retrieving %s with query [%s]", MODULENAME, osrfHashGet(meta, "fieldmapper"), sql);
1326 osrfAppSessionStatus(
1328 OSRF_STATUS_INTERNALSERVERERROR,
1329 "osrfMethodException",
1331 "Severe query error -- see error log for more details"
1335 jsonObjectFree(res_list);
1342 if (res_list->size && order_hash) {
1343 _tmp = jsonObjectGetKey( order_hash, "flesh" );
1345 int x = (int)jsonObjectGetNumber(_tmp);
1347 jsonObject* flesh_blob = NULL;
1348 if ((flesh_blob = jsonObjectGetKey( order_hash, "flesh_fields" )) && x > 0) {
1350 flesh_blob = jsonObjectClone( flesh_blob );
1351 jsonObject* flesh_fields = jsonObjectGetKey( flesh_blob, core_class );
1353 osrfStringArray* link_fields = NULL;
1356 if (flesh_fields->size == 1) {
1357 char* _t = jsonObjectToSimpleString( jsonObjectGetIndex( flesh_fields, 0 ) );
1358 if (!strcmp(_t,"*")) link_fields = osrfHashKeys( links );
1364 link_fields = osrfNewStringArray(1);
1365 jsonObjectIterator* _i = jsonNewObjectIterator( flesh_fields );
1366 while ((_f = jsonObjectIteratorNext( _i ))) {
1367 osrfStringArrayAdd( link_fields, jsonObjectToSimpleString( _f->item ) );
1372 jsonObjectNode* cur;
1373 jsonObjectIterator* itr = jsonNewObjectIterator( res_list );
1374 while ((cur = jsonObjectIteratorNext( itr ))) {
1379 while ( (link_field = osrfStringArrayGetString(link_fields, i++)) ) {
1381 osrfLogDebug(OSRF_LOG_MARK, "Starting to flesh %s", link_field);
1383 osrfHash* kid_link = osrfHashGet(links, link_field);
1384 if (!kid_link) continue;
1386 osrfHash* field = osrfHashGet(fields, link_field);
1387 if (!field) continue;
1389 osrfHash* value_field = field;
1391 osrfHash* kid_idl = osrfHashGet(idl, osrfHashGet(kid_link, "class"));
1392 if (!kid_idl) continue;
1394 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
1395 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
1398 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) { // might_have
1399 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
1402 osrfStringArray* link_map = osrfHashGet( kid_link, "map" );
1404 if (link_map->size > 0) {
1405 jsonObject* _kid_key = jsonParseString("[]");
1408 jsonNewObject( osrfStringArrayGetString( link_map, 0 ) )
1413 osrfHashGet(kid_link, "class"),
1420 "Link field: %s, remote class: %s, fkey: %s, reltype: %s",
1421 osrfHashGet(kid_link, "field"),
1422 osrfHashGet(kid_link, "class"),
1423 osrfHashGet(kid_link, "key"),
1424 osrfHashGet(kid_link, "reltype")
1427 jsonObject* fake_params = jsonParseString("[]");
1428 jsonObjectPush(fake_params, jsonParseString("{}")); // search hash
1429 jsonObjectPush(fake_params, jsonParseString("{}")); // order/flesh hash
1431 osrfLogDebug(OSRF_LOG_MARK, "Creating dummy params object...");
1434 jsonObjectToSimpleString(
1437 atoi( osrfHashGet(value_field, "array_position") )
1442 osrfLogDebug(OSRF_LOG_MARK, "Nothing to search for!");
1447 jsonObjectGetIndex(fake_params, 0),
1448 osrfHashGet(kid_link, "key"),
1449 jsonNewObject( search_key )
1456 jsonObjectGetIndex(fake_params, 1),
1458 jsonNewNumberObject( (double)(x - 1 + link_map->size) )
1462 jsonObjectSetKey( jsonObjectGetIndex(fake_params, 1), "flesh_fields", jsonObjectClone(flesh_blob) );
1464 if (jsonObjectGetKey(order_hash, "order_by")) {
1466 jsonObjectGetIndex(fake_params, 1),
1468 jsonObjectClone(jsonObjectGetKey(order_hash, "order_by"))
1472 if (jsonObjectGetKey(order_hash, "select")) {
1474 jsonObjectGetIndex(fake_params, 1),
1476 jsonObjectClone(jsonObjectGetKey(order_hash, "select"))
1480 jsonObject* kids = doSearch(ctx, kid_idl, fake_params, err);
1483 jsonObjectFree( fake_params );
1484 osrfStringArrayFree(link_fields);
1485 jsonObjectIteratorFree(itr);
1486 jsonObjectFree(res_list);
1490 osrfLogDebug(OSRF_LOG_MARK, "Search for %s return %d linked objects", osrfHashGet(kid_link, "class"), kids->size);
1492 jsonObject* X = NULL;
1493 if ( link_map->size > 0 && kids->size > 0 ) {
1495 kids = jsonParseString("[]");
1497 jsonObjectNode* _k_node;
1498 jsonObjectIterator* _k = jsonNewObjectIterator( X );
1499 while ((_k_node = jsonObjectIteratorNext( _k ))) {
1505 (unsigned long)atoi(
1511 osrfHashGet(kid_link, "class")
1515 osrfStringArrayGetString( link_map, 0 )
1526 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_a" ))) {
1527 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
1530 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
1531 jsonObjectClone( jsonObjectGetIndex(kids, 0) )
1535 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
1536 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
1539 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
1540 jsonObjectClone( kids )
1545 jsonObjectFree(kids);
1549 jsonObjectFree( kids );
1550 jsonObjectFree( fake_params );
1552 osrfLogDebug(OSRF_LOG_MARK, "Fleshing of %s complete", osrfHashGet(kid_link, "field"));
1553 osrfLogDebug(OSRF_LOG_MARK, "%s", jsonObjectToJSON(cur->item));
1557 jsonObjectFree( flesh_blob );
1558 osrfStringArrayFree(link_fields);
1559 jsonObjectIteratorFree(itr);
1568 jsonObject* doUpdate(osrfMethodContext* ctx, int* err ) {
1570 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1571 jsonObject* target = jsonObjectGetIndex(ctx->params, 0);
1573 if (!verifyObjectClass(ctx, target)) {
1578 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
1579 osrfAppSessionStatus(
1581 OSRF_STATUS_BADREQUEST,
1582 "osrfMethodException",
1584 "No active transaction -- required for UPDATE"
1590 dbhandle = writehandle;
1592 char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
1594 // Set the last_xact_id
1595 osrfHash* last_xact_id;
1596 if ((last_xact_id = oilsIDLFindPath("/%s/fields/last_xact_id", target->classname))) {
1597 int index = atoi( osrfHashGet(last_xact_id, "array_position") );
1598 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
1599 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
1602 char* pkey = osrfHashGet(meta, "primarykey");
1603 osrfHash* fields = osrfHashGet(meta, "fields");
1606 jsonObjectToSimpleString(
1609 atoi( osrfHashGet( osrfHashGet( fields, pkey ), "array_position" ) )
1615 "%s updating %s object with %s = %s",
1617 osrfHashGet(meta, "fieldmapper"),
1622 growing_buffer* sql = buffer_init(128);
1623 buffer_fadd(sql,"UPDATE %s SET", osrfHashGet(meta, "tablename"));
1628 osrfStringArray* field_list = osrfHashKeys( fields );
1629 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
1631 osrfHash* field = osrfHashGet( fields, field_name );
1633 if(!( strcmp( field_name, pkey ) )) continue;
1634 if(!( strcmp( osrfHashGet(osrfHashGet(fields,field_name), "virtual"), "true" ) )) continue;
1636 int pos = atoi(osrfHashGet(field, "array_position"));
1637 char* value = jsonObjectToSimpleString( jsonObjectGetIndex( target, pos ) );
1639 osrfLogDebug( OSRF_LOG_MARK, "Updating %s object with %s = %s", osrfHashGet(meta, "fieldmapper"), field_name, value);
1641 if (!jsonObjectGetIndex(target, pos) || jsonObjectGetIndex(target, pos)->type == JSON_NULL) {
1642 if ( !(!( strcmp( osrfHashGet(meta, "classname"), "au" ) ) && !( strcmp( field_name, "passwd" ) )) ) { // arg at the special case!
1643 if (first) first = 0;
1644 else buffer_add(sql, ",");
1645 buffer_fadd( sql, " %s = NULL", field_name );
1648 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1649 if (first) first = 0;
1650 else buffer_add(sql, ",");
1652 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
1653 buffer_fadd( sql, " %s = %ld", field_name, atol(value) );
1654 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
1655 buffer_fadd( sql, " %s = %f", field_name, atof(value) );
1658 osrfLogDebug( OSRF_LOG_MARK, "%s is of type %s", field_name, osrfHashGet(field, "datatype"));
1661 if ( dbi_conn_quote_string(dbhandle, &value) ) {
1662 if (first) first = 0;
1663 else buffer_add(sql, ",");
1664 buffer_fadd( sql, " %s = %s", field_name, value );
1667 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
1668 osrfAppSessionStatus(
1670 OSRF_STATUS_INTERNALSERVERERROR,
1671 "osrfMethodException",
1673 "Error quoting string -- please see the error log for more details"
1687 jsonObject* obj = jsonParseString(id);
1689 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
1690 dbi_conn_quote_string(dbhandle, &id);
1692 buffer_fadd( sql, " WHERE %s = %s;", pkey, id );
1694 char* query = buffer_data(sql);
1697 osrfLogDebug(OSRF_LOG_MARK, "%s: Update SQL [%s]", MODULENAME, query);
1699 dbi_result result = dbi_conn_query(dbhandle, query);
1703 jsonObjectFree(obj);
1704 obj = jsonNewObject(NULL);
1707 "%s ERROR updating %s object with %s = %s",
1709 osrfHashGet(meta, "fieldmapper"),
1720 jsonObject* doDelete(osrfMethodContext* ctx, int* err ) {
1722 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1724 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
1725 osrfAppSessionStatus(
1727 OSRF_STATUS_BADREQUEST,
1728 "osrfMethodException",
1730 "No active transaction -- required for DELETE"
1736 dbhandle = writehandle;
1740 char* pkey = osrfHashGet(meta, "primarykey");
1743 if (jsonObjectGetIndex(ctx->params, 0)->classname) {
1744 if (!verifyObjectClass(ctx, jsonObjectGetIndex( ctx->params, 0 ))) {
1749 id = jsonObjectToSimpleString(
1751 jsonObjectGetIndex(ctx->params, 0),
1752 atoi( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "array_position") )
1756 id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
1761 "%s deleting %s object with %s = %s",
1763 osrfHashGet(meta, "fieldmapper"),
1768 obj = jsonParseString(id);
1770 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
1771 dbi_conn_quote_string(writehandle, &id);
1773 dbi_result result = dbi_conn_queryf(writehandle, "DELETE FROM %s WHERE %s = %s;", osrfHashGet(meta, "tablename"), pkey, id);
1776 jsonObjectFree(obj);
1777 obj = jsonNewObject(NULL);
1780 "%s ERROR deleting %s object with %s = %s",
1782 osrfHashGet(meta, "fieldmapper"),
1795 jsonObject* oilsMakeJSONFromResult( dbi_result result, osrfHash* meta) {
1796 if(!(result && meta)) return jsonNULL;
1798 jsonObject* object = jsonParseString("[]");
1799 jsonObjectSetClass(object, osrfHashGet(meta, "classname"));
1801 osrfHash* fields = osrfHashGet(meta, "fields");
1803 osrfLogInternal(OSRF_LOG_MARK, "Setting object class to %s ", object->classname);
1807 char dt_string[256];
1811 int columnIndex = 1;
1813 unsigned short type;
1814 const char* columnName;
1816 /* cycle through the column list */
1817 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
1819 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
1821 fmIndex = -1; // reset the position
1823 /* determine the field type and storage attributes */
1824 type = dbi_result_get_field_type(result, columnName);
1825 attr = dbi_result_get_field_attribs(result, columnName);
1827 /* fetch the fieldmapper index */
1828 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
1829 char* virt = (char*)osrfHashGet(_f, "virtual");
1830 char* pos = (char*)osrfHashGet(_f, "array_position");
1832 if ( !virt || !pos || !(strcmp( virt, "true" )) ) continue;
1834 fmIndex = atoi( pos );
1835 osrfLogInternal(OSRF_LOG_MARK, "... Found column at position [%s]...", pos);
1840 if (dbi_result_field_is_null(result, columnName)) {
1841 jsonObjectSetIndex( object, fmIndex, jsonNewObject(NULL) );
1846 case DBI_TYPE_INTEGER :
1848 if( attr & DBI_INTEGER_SIZE8 )
1849 jsonObjectSetIndex( object, fmIndex,
1850 jsonNewNumberObject(dbi_result_get_longlong(result, columnName)));
1852 jsonObjectSetIndex( object, fmIndex,
1853 jsonNewNumberObject(dbi_result_get_long(result, columnName)));
1857 case DBI_TYPE_DECIMAL :
1858 jsonObjectSetIndex( object, fmIndex,
1859 jsonNewNumberObject(dbi_result_get_double(result, columnName)));
1862 case DBI_TYPE_STRING :
1868 jsonNewObject( dbi_result_get_string(result, columnName) )
1873 case DBI_TYPE_DATETIME :
1875 memset(dt_string, '\0', 256);
1876 memset(&gmdt, '\0', sizeof(gmdt));
1877 memset(&_tmp_dt, '\0', sizeof(_tmp_dt));
1879 _tmp_dt = dbi_result_get_datetime(result, columnName);
1881 localtime_r( &_tmp_dt, &gmdt );
1883 if (!(attr & DBI_DATETIME_DATE)) {
1884 strftime(dt_string, 255, "%T", &gmdt);
1885 } else if (!(attr & DBI_DATETIME_TIME)) {
1886 strftime(dt_string, 255, "%F", &gmdt);
1888 strftime(dt_string, 255, "%FT%T%z", &gmdt);
1891 jsonObjectSetIndex( object, fmIndex, jsonNewObject(dt_string) );
1895 case DBI_TYPE_BINARY :
1896 osrfLogError( OSRF_LOG_MARK,
1897 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);