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 osrfLogDebug(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")))
336 int beginTransaction ( osrfMethodContext* ctx ) {
337 OSRF_METHOD_VERIFY_CONTEXT(ctx);
339 dbi_result result = dbi_conn_query(writehandle, "START TRANSACTION;");
341 osrfLogError(OSRF_LOG_MARK, "%s: Error starting transaction", MODULENAME );
342 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error starting transaction" );
345 jsonObject* ret = jsonNewObject(ctx->session->session_id);
346 osrfAppRespondComplete( ctx, ret );
349 if (!ctx->session->userData) {
350 ctx->session->userData = osrfNewHash();
351 ((osrfHash*)ctx->session->userData)->freeItem = &sessionDataFree;
354 osrfHashSet( (osrfHash*)ctx->session->userData, strdup( ctx->session->session_id ), "xact_id" );
355 ctx->session->userDataFree = &userDataFree;
361 int setSavepoint ( osrfMethodContext* ctx ) {
362 OSRF_METHOD_VERIFY_CONTEXT(ctx);
364 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
366 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
367 osrfAppSessionStatus(
369 OSRF_STATUS_INTERNALSERVERERROR,
370 "osrfMethodException",
372 "No active transaction -- required for savepoints"
377 dbi_result result = dbi_conn_queryf(writehandle, "SAVEPOINT \"%s\";", spName);
381 "%s: Error creating savepoint %s in transaction %s",
384 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
386 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error creating savepoint" );
389 jsonObject* ret = jsonNewObject(spName);
390 osrfAppRespondComplete( ctx, ret );
396 int releaseSavepoint ( osrfMethodContext* ctx ) {
397 OSRF_METHOD_VERIFY_CONTEXT(ctx);
399 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
401 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
402 osrfAppSessionStatus(
404 OSRF_STATUS_INTERNALSERVERERROR,
405 "osrfMethodException",
407 "No active transaction -- required for savepoints"
412 dbi_result result = dbi_conn_queryf(writehandle, "RELEASE SAVEPOINT \"%s\";", spName);
416 "%s: Error releasing savepoint %s in transaction %s",
419 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
421 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error releasing savepoint" );
424 jsonObject* ret = jsonNewObject(spName);
425 osrfAppRespondComplete( ctx, ret );
431 int rollbackSavepoint ( osrfMethodContext* ctx ) {
432 OSRF_METHOD_VERIFY_CONTEXT(ctx);
434 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
436 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
437 osrfAppSessionStatus(
439 OSRF_STATUS_INTERNALSERVERERROR,
440 "osrfMethodException",
442 "No active transaction -- required for savepoints"
447 dbi_result result = dbi_conn_queryf(writehandle, "ROLLBACK TO SAVEPOINT \"%s\";", spName);
451 "%s: Error rolling back savepoint %s in transaction %s",
454 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
456 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back savepoint" );
459 jsonObject* ret = jsonNewObject(spName);
460 osrfAppRespondComplete( ctx, ret );
466 int commitTransaction ( osrfMethodContext* ctx ) {
467 OSRF_METHOD_VERIFY_CONTEXT(ctx);
469 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
470 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to commit" );
474 dbi_result result = dbi_conn_query(writehandle, "COMMIT;");
476 osrfLogError(OSRF_LOG_MARK, "%s: Error committing transaction", MODULENAME );
477 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error committing transaction" );
480 osrfHashRemove(ctx->session->userData, "xact_id");
481 jsonObject* ret = jsonNewObject(ctx->session->session_id);
482 osrfAppRespondComplete( ctx, ret );
488 int rollbackTransaction ( osrfMethodContext* ctx ) {
489 OSRF_METHOD_VERIFY_CONTEXT(ctx);
491 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
492 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to roll back" );
496 dbi_result result = dbi_conn_query(writehandle, "ROLLBACK;");
498 osrfLogError(OSRF_LOG_MARK, "%s: Error rolling back transaction", MODULENAME );
499 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back transaction" );
502 osrfHashRemove(ctx->session->userData, "xact_id");
503 jsonObject* ret = jsonNewObject(ctx->session->session_id);
504 osrfAppRespondComplete( ctx, ret );
510 int dispatchCRUDMethod ( osrfMethodContext* ctx ) {
511 OSRF_METHOD_VERIFY_CONTEXT(ctx);
513 osrfHash* meta = (osrfHash*) ctx->method->userData;
514 osrfHash* class_obj = osrfHashGet( meta, "class" );
518 jsonObject * obj = NULL;
519 if (!strcmp( (char*)osrfHashGet(meta, "methodtype"), "create"))
520 obj = doCreate(ctx, &err);
522 if (!strcmp( (char*)osrfHashGet(meta, "methodtype"), "retrieve"))
523 obj = doRetrieve(ctx, &err);
525 if (!strcmp( (char*)osrfHashGet(meta, "methodtype"), "update"))
526 obj = doUpdate(ctx, &err);
528 if (!strcmp( (char*)osrfHashGet(meta, "methodtype"), "delete"))
529 obj = doDelete(ctx, &err);
531 if (!strcmp( (char*)osrfHashGet(meta, "methodtype"), "search")) {
533 obj = doSearch(ctx, class_obj, ctx->params, &err);
537 jsonObjectIterator* itr = jsonNewObjectIterator( obj );
538 while ((cur = jsonObjectIteratorNext( itr ))) {
539 osrfAppRespond( ctx, jsonObjectClone(cur->item) );
541 jsonObjectIteratorFree(itr);
542 osrfAppRespondComplete( ctx, NULL );
544 } else if (!strcmp( (char*)osrfHashGet(meta, "methodtype"), "id_list")) {
546 jsonObject* _p = jsonObjectClone( ctx->params );
547 if (jsonObjectGetIndex( _p, 1 )) {
548 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh" );
549 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh_columns" );
551 jsonObjectSetIndex( _p, 1, jsonParseString("{}") );
554 growing_buffer* sel_list = buffer_init(16);
555 buffer_fadd(sel_list, "{ \"%s\":[\"%s\"] }", osrfHashGet( class_obj, "classname" ), osrfHashGet( class_obj, "primarykey" ));
556 char* _s = buffer_data(sel_list);
557 buffer_free(sel_list);
559 jsonObjectSetKey( jsonObjectGetIndex( _p, 1 ), "select", jsonParseString(_s) );
560 osrfLogDebug(OSRF_LOG_MARK, "%s: Select qualifer set to [%s]", MODULENAME, _s);
563 obj = doSearch(ctx, class_obj, _p, &err);
567 jsonObjectIterator* itr = jsonNewObjectIterator( obj );
568 while ((cur = jsonObjectIteratorNext( itr ))) {
577 osrfHashGet( class_obj, "fields" ),
578 osrfHashGet( class_obj, "primarykey")
587 jsonObjectIteratorFree(itr);
588 osrfAppRespondComplete( ctx, NULL );
591 osrfAppRespondComplete( ctx, obj );
599 int verifyObjectClass ( osrfMethodContext* ctx, jsonObject* param ) {
601 osrfHash* meta = (osrfHash*) ctx->method->userData;
602 osrfHash* class = osrfHashGet( meta, "class" );
604 if ((strcmp( osrfHashGet(class, "classname"), param->classname ))) {
606 growing_buffer* msg = buffer_init(128);
609 "%s: %s method for type %s was passed a %s",
611 osrfHashGet(meta, "methodtype"),
612 osrfHashGet(class, "classname"),
616 char* m = buffer_data(msg);
617 osrfAppSessionStatus( ctx->session, OSRF_STATUS_BADREQUEST, "osrfMethodException", ctx->request, m );
627 jsonObject* doCreate(osrfMethodContext* ctx, int* err ) {
629 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
630 jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
632 if (!verifyObjectClass(ctx, target)) {
637 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
638 osrfAppSessionStatus(
640 OSRF_STATUS_BADREQUEST,
641 "osrfMethodException",
643 "No active transaction -- required for CREATE"
649 dbhandle = writehandle;
651 osrfHash* fields = osrfHashGet(meta, "fields");
652 char* pkey = osrfHashGet(meta, "primarykey");
653 char* seq = osrfHashGet(meta, "sequence");
655 growing_buffer* table_buf = buffer_init(128);
656 growing_buffer* col_buf = buffer_init(128);
657 growing_buffer* val_buf = buffer_init(128);
659 buffer_fadd(table_buf,"INSERT INTO %s", osrfHashGet(meta, "tablename"));
660 buffer_add(col_buf,"(");
661 buffer_add(val_buf,"VALUES (");
666 osrfStringArray* field_list = osrfHashKeys( fields );
667 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
669 osrfHash* field = osrfHashGet( fields, field_name );
671 if(!( strcmp( osrfHashGet(osrfHashGet(fields,field_name), "virtual"), "true" ) )) continue;
673 int pos = atoi(osrfHashGet(field, "array_position"));
674 char* value = jsonObjectToSimpleString( jsonObjectGetIndex( target, pos ) );
679 buffer_add(col_buf, ",");
680 buffer_add(val_buf, ",");
683 buffer_add(col_buf, field_name);
685 if (jsonObjectGetIndex(target, pos)->type == JSON_NULL) {
686 buffer_add( val_buf, "DEFAULT" );
688 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
689 if ( !strcmp(osrfHashGet(field, "datatype"), "INT8") ) {
690 buffer_fadd( val_buf, "%lld", atol(value) );
692 } else if ( !strcmp(osrfHashGet(field, "datatype"), "INT") ) {
693 buffer_fadd( val_buf, "%ld", atoll(value) );
695 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
696 buffer_fadd( val_buf, "%f", atof(value) );
699 if ( dbi_conn_quote_string(writehandle, &value) ) {
700 buffer_fadd( val_buf, "%s", value );
703 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
704 osrfAppSessionStatus(
706 OSRF_STATUS_INTERNALSERVERERROR,
707 "osrfMethodException",
709 "Error quoting string -- please see the error log for more details"
712 buffer_free(table_buf);
713 buffer_free(col_buf);
714 buffer_free(val_buf);
724 buffer_add(col_buf,")");
725 buffer_add(val_buf,")");
727 growing_buffer* sql = buffer_init(128);
731 buffer_data(table_buf),
732 buffer_data(col_buf),
735 buffer_free(table_buf);
736 buffer_free(col_buf);
737 buffer_free(val_buf);
739 char* query = buffer_data(sql);
742 osrfLogDebug(OSRF_LOG_MARK, "%s: Insert SQL [%s]", MODULENAME, query);
745 dbi_result result = dbi_conn_query(writehandle, query);
747 jsonObject* obj = NULL;
750 obj = jsonNewObject(NULL);
753 "%s ERROR inserting %s object using query [%s]",
755 osrfHashGet(meta, "fieldmapper"),
758 osrfAppSessionStatus(
760 OSRF_STATUS_INTERNALSERVERERROR,
761 "osrfMethodException",
763 "INSERT error -- please see the error log for more details"
768 int pos = atoi(osrfHashGet( osrfHashGet(fields, pkey), "array_position" ));
769 char* id = jsonObjectToSimpleString(jsonObjectGetIndex(target, pos));
771 unsigned long long new_id = dbi_conn_sequence_last(writehandle, seq);
772 growing_buffer* _id = buffer_init(10);
773 buffer_fadd(_id, "%lld", new_id);
774 id = buffer_data(_id);
778 jsonObject* fake_params = jsonParseString("[]");
779 jsonObjectPush(fake_params, jsonParseString("{}"));
782 jsonObjectGetIndex(fake_params, 0),
783 osrfHashGet(meta, "primarykey"),
787 jsonObject* list = doSearch( ctx,meta, fake_params, err);
790 jsonObjectFree( fake_params );
793 obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
796 jsonObjectFree( list );
797 jsonObjectFree( fake_params );
808 jsonObject* doRetrieve(osrfMethodContext* ctx, int* err ) {
810 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
814 char* id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
815 jsonObject* order_hash = jsonObjectGetIndex(ctx->params, 1);
819 "%s retrieving %s object with id %s",
821 osrfHashGet(meta, "fieldmapper"),
825 jsonObject* fake_params = jsonParseString("[]");
826 jsonObjectPush(fake_params, jsonParseString("{}"));
829 jsonObjectGetIndex(fake_params, 0),
830 osrfHashGet(meta, "primarykey"),
834 if (order_hash) jsonObjectPush(fake_params, jsonObjectClone(order_hash) );
836 jsonObject* list = doSearch( ctx,meta, fake_params, err);
839 jsonObjectFree( fake_params );
843 obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
845 jsonObjectFree( list );
846 jsonObjectFree( fake_params );
851 char* jsonNumberToDBString ( osrfHash* field, jsonObject* value ) {
852 growing_buffer* val_buf = buffer_init(32);
854 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", 3) ) {
855 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%ld", (long)jsonObjectGetNumber(value) );
856 else buffer_fadd( val_buf, "%ld", atol(jsonObjectToSimpleString(value)) );
858 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
859 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%f", jsonObjectGetNumber(value) );
860 else buffer_fadd( val_buf, "%f", atof(jsonObjectToSimpleString(value)) );
863 char* pred = buffer_data(val_buf);
864 buffer_free(val_buf);
869 char* searchINPredicate (osrfHash* field, jsonObject* node) {
870 growing_buffer* sql_buf = buffer_init(32);
875 osrfHashGet(field, "name")
878 int in_item_index = 0;
879 int in_item_first = 1;
881 while ( (in_item = jsonObjectGetIndex(node, in_item_index++)) ) {
886 buffer_add(sql_buf, ", ");
888 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
889 char* val = jsonNumberToDBString( field, in_item );
890 buffer_fadd( sql_buf, "%s", val );
894 char* key_string = jsonObjectToSimpleString(in_item);
895 if ( dbi_conn_quote_string(dbhandle, &key_string) ) {
896 buffer_fadd( sql_buf, "%s", key_string );
899 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, key_string);
901 buffer_free(sql_buf);
912 char* pred = buffer_data(sql_buf);
913 buffer_free(sql_buf);
918 char* searchValueTransform( jsonObject* array ) {
919 growing_buffer* sql_buf = buffer_init(32);
922 int func_item_index = 0;
923 int func_item_first = 2;
924 jsonObject* func_item;
925 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
927 val = jsonObjectToSimpleString(func_item);
929 if (func_item_first == 2) {
930 buffer_fadd(sql_buf, "%s( ", val);
939 buffer_add(sql_buf, ", ");
941 if ( dbi_conn_quote_string(dbhandle, &val) ) {
942 buffer_fadd( sql_buf, "%s", val );
945 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
947 buffer_free(sql_buf);
957 char* pred = buffer_data(sql_buf);
958 buffer_free(sql_buf);
963 char* searchFunctionPredicate (osrfHash* field, jsonObjectNode* node) {
964 growing_buffer* sql_buf = buffer_init(32);
966 char* val = searchValueTransform(node->item);
971 osrfHashGet(field, "name"),
976 char* pred = buffer_data(sql_buf);
977 buffer_free(sql_buf);
983 char* searchFieldTransformPredicate (osrfHash* field, jsonObjectNode* node) {
984 growing_buffer* sql_buf = buffer_init(32);
986 char* field_transform = jsonObjectToSimpleString( jsonObjectGetKey( node->item, "transform" ) );
989 if (jsonObjectGetKey( node->item, "value" )->type == JSON_ARRAY) {
990 value = searchValueTransform(jsonObjectGetKey( node->item, "value" ));
991 } else if (jsonObjectGetKey( node->item, "value" )->type != JSON_NULL) {
992 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
993 value = jsonNumberToDBString( field, jsonObjectGetKey( node->item, "value" ) );
995 value = jsonObjectToSimpleString(jsonObjectGetKey( node->item, "value" ));
996 if ( !dbi_conn_quote_string(dbhandle, &value) ) {
997 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, value);
1008 osrfHashGet(field, "name"),
1013 char* pred = buffer_data(sql_buf);
1014 buffer_free(sql_buf);
1019 char* searchSimplePredicate (const char* orig_op, osrfHash* field, jsonObject* node) {
1023 if (node->type != JSON_NULL) {
1024 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1025 val = jsonNumberToDBString( field, node );
1027 val = jsonObjectToSimpleString(node);
1031 char* pred = searchWriteSimplePredicate( field, osrfHashGet(field, "name"), orig_op, val );
1038 char* searchWriteSimplePredicate ( osrfHash* field, const char* left, const char* orig_op, const char* right ) {
1042 if (right == NULL) {
1043 val = strdup("NULL");
1045 if (strcmp( orig_op, "=" ))
1046 op = strdup("IS NOT");
1050 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1051 val = strdup(right);
1052 op = strdup(orig_op);
1055 val = strdup(right);
1056 if ( !dbi_conn_quote_string(dbhandle, &val) ) {
1057 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1061 op = strdup(orig_op);
1064 growing_buffer* sql_buf = buffer_init(16);
1065 buffer_fadd( sql_buf, "%s %s %s", left, op, val );
1069 char* pred = buffer_data(sql_buf);
1070 buffer_free(sql_buf);
1076 char* searchBETWEENPredicate (osrfHash* field, jsonObject* node) {
1081 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1082 x_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,0));
1083 y_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,1));
1086 x_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,0));
1087 y_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,1));
1088 if ( !(dbi_conn_quote_string(dbhandle, &x_string) && dbi_conn_quote_string(dbhandle, &y_string)) ) {
1089 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key strings [%s] and [%s]", MODULENAME, x_string, y_string);
1096 growing_buffer* sql_buf = buffer_init(32);
1097 buffer_fadd( sql_buf, "%s BETWEEN %s AND %s", osrfHashGet(field, "name"), x_string, y_string );
1101 char* pred = buffer_data(sql_buf);
1102 buffer_free(sql_buf);
1107 char* searchPredicate ( osrfHash* field, jsonObject* node ) {
1110 if (node->type == JSON_ARRAY) { // equality IN search
1111 pred = searchINPredicate( field, node );
1112 } else if (node->type == JSON_HASH) { // non-equality search
1113 jsonObjectNode* pred_node;
1114 jsonObjectIterator* pred_itr = jsonNewObjectIterator( node );
1115 while ( (pred_node = jsonObjectIteratorNext( pred_itr )) ) {
1116 if ( !(strcasecmp( pred_node->key,"between" )) )
1117 pred = searchBETWEENPredicate( field, pred_node->item );
1118 else if ( !(strcasecmp( pred_node->key,"in" )) )
1119 pred = searchINPredicate( field, pred_node->item );
1120 else if ( pred_node->item->type == JSON_ARRAY )
1121 pred = searchFunctionPredicate( field, pred_node );
1122 else if ( pred_node->item->type == JSON_HASH )
1123 pred = searchFieldTransformPredicate( field, pred_node );
1125 pred = searchSimplePredicate( pred_node->key, field, pred_node->item );
1129 } else if (node->type == JSON_NULL) { // IS NULL search
1130 growing_buffer* _p = buffer_init(16);
1134 osrfHashGet(field, "name")
1136 pred = buffer_data(_p);
1138 } else { // equality search
1139 pred = searchSimplePredicate( "=", field, node );
1146 jsonObject* doSearch(osrfMethodContext* ctx, osrfHash* meta, jsonObject* params, int* err ) {
1149 dbhandle = writehandle;
1151 osrfHash* links = osrfHashGet(meta, "links");
1152 osrfHash* fields = osrfHashGet(meta, "fields");
1153 char* core_class = osrfHashGet(meta, "classname");
1155 jsonObjectNode* node = NULL;
1156 jsonObjectNode* snode = NULL;
1159 jsonObject* search_hash = jsonObjectGetIndex(params, 0);
1160 jsonObject* order_hash = jsonObjectGetIndex(params, 1);
1162 growing_buffer* sql_buf = buffer_init(128);
1163 buffer_add(sql_buf, "SELECT");
1166 if ( (_tmp = jsonObjectGetKey( order_hash, "select" )) ) {
1168 jsonObjectIterator* class_itr = jsonNewObjectIterator( _tmp );
1169 while ( (snode = jsonObjectIteratorNext( class_itr )) ) {
1171 osrfHash* idlClass = osrfHashGet( idl, snode->key );
1172 if (!idlClass) continue;
1173 char* cname = osrfHashGet(idlClass, "classname");
1175 jsonObjectIterator* select_itr = jsonNewObjectIterator( snode->item );
1176 while ( (node = jsonObjectIteratorNext( select_itr )) ) {
1177 osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), jsonObjectToSimpleString(node->item) );
1178 char* fname = osrfHashGet(field, "name");
1180 if (!field) continue;
1185 buffer_add(sql_buf, ",");
1188 buffer_fadd(sql_buf, " \"%s\".%s", cname, fname, cname, fname);
1192 buffer_add(sql_buf, " *");
1195 buffer_fadd(sql_buf, " FROM %s AS \"%s\" WHERE ", osrfHashGet(meta, "tablename"), core_class );
1200 jsonObjectIterator* search_itr = jsonNewObjectIterator( search_hash );
1201 while ( (node = jsonObjectIteratorNext( search_itr )) ) {
1202 osrfHash* field = osrfHashGet( fields, node->key );
1204 if (!field) continue;
1209 buffer_add(sql_buf, " AND ");
1212 pred = searchPredicate( field, node->item);
1213 buffer_fadd( sql_buf, "%s", pred );
1217 jsonObjectIteratorFree(search_itr);
1221 if ( (_tmp = jsonObjectGetKey( jsonObjectGetKey( order_hash, "order_by" ), core_class ) ) ){
1222 string = jsonObjectToSimpleString(_tmp);
1231 if ( (_tmp = jsonObjectGetKey( order_hash, "limit" )) ){
1232 string = jsonObjectToSimpleString(_tmp);
1241 _tmp = jsonObjectGetKey( order_hash, "offset" );
1243 string = jsonObjectToSimpleString(_tmp);
1253 buffer_add(sql_buf, ";");
1255 char* sql = buffer_data(sql_buf);
1256 buffer_free(sql_buf);
1258 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
1259 dbi_result result = dbi_conn_query(dbhandle, sql);
1261 jsonObject* res_list = jsonParseString("[]");
1263 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
1265 if (dbi_result_first_row(result)) {
1266 /* JSONify the result */
1267 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
1269 obj = oilsMakeJSONFromResult( result, meta );
1270 jsonObjectPush(res_list, obj);
1271 } while (dbi_result_next_row(result));
1273 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
1276 /* clean up the query */
1277 dbi_result_free(result);
1280 osrfLogError(OSRF_LOG_MARK, "%s: Error retrieving %s with query [%s]", MODULENAME, osrfHashGet(meta, "fieldmapper"), sql);
1281 osrfAppSessionStatus(
1283 OSRF_STATUS_INTERNALSERVERERROR,
1284 "osrfMethodException",
1286 "Severe query error -- see error log for more details"
1290 jsonObjectFree(res_list);
1297 if (res_list->size && order_hash) {
1298 _tmp = jsonObjectGetKey( order_hash, "flesh" );
1300 int x = (int)jsonObjectGetNumber(_tmp);
1302 jsonObject* flesh_blob = NULL;
1303 if ((flesh_blob = jsonObjectGetKey( order_hash, "flesh_fields" )) && x > 0) {
1305 flesh_blob = jsonObjectClone( flesh_blob );
1306 jsonObject* flesh_fields = jsonObjectGetKey( flesh_blob, core_class );
1308 osrfStringArray* link_fields = NULL;
1311 if (flesh_fields->size == 1) {
1312 char* _t = jsonObjectToSimpleString( jsonObjectGetIndex( flesh_fields, 0 ) );
1313 if (!strcmp(_t,"*")) link_fields = osrfHashKeys( links );
1319 link_fields = osrfNewStringArray(1);
1320 jsonObjectIterator* _i = jsonNewObjectIterator( flesh_fields );
1321 while ((_f = jsonObjectIteratorNext( _i ))) {
1322 osrfStringArrayAdd( link_fields, jsonObjectToSimpleString( _f->item ) );
1327 jsonObjectNode* cur;
1328 jsonObjectIterator* itr = jsonNewObjectIterator( res_list );
1329 while ((cur = jsonObjectIteratorNext( itr ))) {
1334 while ( (link_field = osrfStringArrayGetString(link_fields, i++)) ) {
1336 osrfLogDebug(OSRF_LOG_MARK, "Starting to flesh %s", link_field);
1338 osrfHash* kid_link = osrfHashGet(links, link_field);
1339 if (!kid_link) continue;
1341 osrfHash* field = osrfHashGet(fields, link_field);
1342 if (!field) continue;
1344 osrfHash* value_field = field;
1346 osrfHash* kid_idl = osrfHashGet(idl, osrfHashGet(kid_link, "class"));
1347 if (!kid_idl) continue;
1349 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
1350 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
1353 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) { // might_have
1354 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
1357 osrfStringArray* link_map = osrfHashGet( kid_link, "map" );
1359 if (link_map->size > 0) {
1360 jsonObject* _kid_key = jsonParseString("[]");
1363 jsonNewObject( osrfStringArrayGetString( link_map, 0 ) )
1368 osrfHashGet(kid_link, "class"),
1375 "Link field: %s, remote class: %s, fkey: %s, reltype: %s",
1376 osrfHashGet(kid_link, "field"),
1377 osrfHashGet(kid_link, "class"),
1378 osrfHashGet(kid_link, "key"),
1379 osrfHashGet(kid_link, "reltype")
1382 jsonObject* fake_params = jsonParseString("[]");
1383 jsonObjectPush(fake_params, jsonParseString("{}")); // search hash
1384 jsonObjectPush(fake_params, jsonParseString("{}")); // order/flesh hash
1386 osrfLogDebug(OSRF_LOG_MARK, "Creating dummy params object...");
1389 jsonObjectToSimpleString(
1392 atoi( osrfHashGet(value_field, "array_position") )
1397 osrfLogDebug(OSRF_LOG_MARK, "Nothing to search for!");
1402 jsonObjectGetIndex(fake_params, 0),
1403 osrfHashGet(kid_link, "key"),
1404 jsonNewObject( search_key )
1411 jsonObjectGetIndex(fake_params, 1),
1413 jsonNewNumberObject( (double)(x - 1 + link_map->size) )
1417 jsonObjectSetKey( jsonObjectGetIndex(fake_params, 1), "flesh_fields", jsonObjectClone(flesh_blob) );
1419 if (jsonObjectGetKey(order_hash, "order_by")) {
1421 jsonObjectGetIndex(fake_params, 1),
1423 jsonObjectClone(jsonObjectGetKey(order_hash, "order_by"))
1427 jsonObject* kids = doSearch(ctx, kid_idl, fake_params, err);
1430 jsonObjectFree( fake_params );
1431 osrfStringArrayFree(link_fields);
1432 jsonObjectIteratorFree(itr);
1433 jsonObjectFree(res_list);
1437 osrfLogDebug(OSRF_LOG_MARK, "Search for %s return %d linked objects", osrfHashGet(kid_link, "class"), kids->size);
1439 jsonObject* X = NULL;
1440 if ( link_map->size > 0 && kids->size > 0 ) {
1442 kids = jsonParseString("[]");
1444 jsonObjectNode* _k_node;
1445 jsonObjectIterator* _k = jsonNewObjectIterator( X );
1446 while ((_k_node = jsonObjectIteratorNext( _k ))) {
1452 (unsigned long)atoi(
1458 osrfHashGet(kid_link, "class")
1462 osrfStringArrayGetString( link_map, 0 )
1473 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_a" ))) {
1474 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
1477 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
1478 jsonObjectClone( jsonObjectGetIndex(kids, 0) )
1482 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
1483 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
1486 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
1487 jsonObjectClone( kids )
1492 jsonObjectFree(kids);
1496 jsonObjectFree( kids );
1497 jsonObjectFree( fake_params );
1499 osrfLogDebug(OSRF_LOG_MARK, "Fleshing of %s complete", osrfHashGet(kid_link, "field"));
1500 osrfLogDebug(OSRF_LOG_MARK, "%s", jsonObjectToJSON(cur->item));
1504 jsonObjectFree( flesh_blob );
1505 osrfStringArrayFree(link_fields);
1506 jsonObjectIteratorFree(itr);
1515 jsonObject* doUpdate(osrfMethodContext* ctx, int* err ) {
1517 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1518 jsonObject* target = jsonObjectGetIndex(ctx->params, 0);
1520 if (!verifyObjectClass(ctx, target)) {
1525 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
1526 osrfAppSessionStatus(
1528 OSRF_STATUS_BADREQUEST,
1529 "osrfMethodException",
1531 "No active transaction -- required for UPDATE"
1537 dbhandle = writehandle;
1539 char* pkey = osrfHashGet(meta, "primarykey");
1540 osrfHash* fields = osrfHashGet(meta, "fields");
1543 jsonObjectToSimpleString(
1546 atoi( osrfHashGet( osrfHashGet( fields, pkey ), "array_position" ) )
1552 "%s updating %s object with %s = %s",
1554 osrfHashGet(meta, "fieldmapper"),
1559 growing_buffer* sql = buffer_init(128);
1560 buffer_fadd(sql,"UPDATE %s SET", osrfHashGet(meta, "tablename"));
1565 osrfStringArray* field_list = osrfHashKeys( fields );
1566 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
1568 osrfHash* field = osrfHashGet( fields, field_name );
1570 if(!( strcmp( field_name, pkey ) )) continue;
1571 if(!( strcmp( osrfHashGet(osrfHashGet(fields,field_name), "virtual"), "true" ) )) continue;
1573 int pos = atoi(osrfHashGet(field, "array_position"));
1574 char* value = jsonObjectToSimpleString( jsonObjectGetIndex( target, pos ) );
1576 osrfLogDebug( OSRF_LOG_MARK, "Updating %s object with %s = %s", osrfHashGet(meta, "fieldmapper"), field_name, value);
1578 if (jsonObjectGetIndex(target, pos)->type == JSON_NULL) {
1579 if ( !(!( strcmp( osrfHashGet(meta, "classname"), "au" ) ) && !( strcmp( field_name, "passwd" ) )) ) { // arg at the special case!
1580 if (first) first = 0;
1581 else buffer_add(sql, ",");
1582 buffer_fadd( sql, " %s = NULL", field_name );
1585 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1586 if (first) first = 0;
1587 else buffer_add(sql, ",");
1589 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
1590 buffer_fadd( sql, " %s = %ld", field_name, atol(value) );
1591 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
1592 buffer_fadd( sql, " %s = %f", field_name, atof(value) );
1595 osrfLogDebug( OSRF_LOG_MARK, "%s is of type %s", field_name, osrfHashGet(field, "datatype"));
1598 if ( dbi_conn_quote_string(dbhandle, &value) ) {
1599 if (first) first = 0;
1600 else buffer_add(sql, ",");
1601 buffer_fadd( sql, " %s = %s", field_name, value );
1604 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
1605 osrfAppSessionStatus(
1607 OSRF_STATUS_INTERNALSERVERERROR,
1608 "osrfMethodException",
1610 "Error quoting string -- please see the error log for more details"
1624 jsonObject* obj = jsonParseString(id);
1626 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
1627 dbi_conn_quote_string(dbhandle, &id);
1629 buffer_fadd( sql, " WHERE %s = %s;", pkey, id );
1631 char* query = buffer_data(sql);
1634 osrfLogDebug(OSRF_LOG_MARK, "%s: Update SQL [%s]", MODULENAME, query);
1636 dbi_result result = dbi_conn_query(dbhandle, query);
1640 jsonObjectFree(obj);
1641 obj = jsonNewObject(NULL);
1644 "%s ERROR updating %s object with %s = %s",
1646 osrfHashGet(meta, "fieldmapper"),
1657 jsonObject* doDelete(osrfMethodContext* ctx, int* err ) {
1659 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1661 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
1662 osrfAppSessionStatus(
1664 OSRF_STATUS_BADREQUEST,
1665 "osrfMethodException",
1667 "No active transaction -- required for DELETE"
1673 dbhandle = writehandle;
1677 char* pkey = osrfHashGet(meta, "primarykey");
1680 if (jsonObjectGetIndex(ctx->params, 0)->classname) {
1681 if (!verifyObjectClass(ctx, jsonObjectGetIndex( ctx->params, 0 ))) {
1686 id = jsonObjectToSimpleString(
1688 jsonObjectGetIndex(ctx->params, 0),
1689 atoi( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "array_position") )
1693 id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
1698 "%s deleting %s object with %s = %s",
1700 osrfHashGet(meta, "fieldmapper"),
1705 obj = jsonParseString(id);
1707 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
1708 dbi_conn_quote_string(writehandle, &id);
1710 dbi_result result = dbi_conn_queryf(writehandle, "DELETE FROM %s WHERE %s = %s;", osrfHashGet(meta, "tablename"), pkey, id);
1713 jsonObjectFree(obj);
1714 obj = jsonNewObject(NULL);
1717 "%s ERROR deleting %s object with %s = %s",
1719 osrfHashGet(meta, "fieldmapper"),
1732 jsonObject* oilsMakeJSONFromResult( dbi_result result, osrfHash* meta) {
1733 if(!(result && meta)) return jsonNULL;
1735 jsonObject* object = jsonParseString("[]");
1736 jsonObjectSetClass(object, osrfHashGet(meta, "classname"));
1738 osrfHash* fields = osrfHashGet(meta, "fields");
1740 osrfLogDebug(OSRF_LOG_MARK, "Setting object class to %s ", object->classname);
1744 char dt_string[256];
1748 int columnIndex = 1;
1750 unsigned short type;
1751 const char* columnName;
1753 /* cycle through the column list */
1754 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
1756 osrfLogDebug(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
1758 fmIndex = -1; // reset the position
1760 /* determine the field type and storage attributes */
1761 type = dbi_result_get_field_type(result, columnName);
1762 attr = dbi_result_get_field_attribs(result, columnName);
1764 /* fetch the fieldmapper index */
1765 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
1766 char* virt = (char*)osrfHashGet(_f, "virtual");
1767 char* pos = (char*)osrfHashGet(_f, "array_position");
1769 if ( !virt || !pos || !(strcmp( virt, "true" )) ) continue;
1771 fmIndex = atoi( pos );
1772 osrfLogDebug(OSRF_LOG_MARK, "... Found column at position [%s]...", pos);
1777 if (dbi_result_field_is_null(result, columnName)) {
1778 jsonObjectSetIndex( object, fmIndex, jsonNewObject(NULL) );
1783 case DBI_TYPE_INTEGER :
1785 if( attr & DBI_INTEGER_SIZE8 )
1786 jsonObjectSetIndex( object, fmIndex,
1787 jsonNewNumberObject(dbi_result_get_longlong(result, columnName)));
1789 jsonObjectSetIndex( object, fmIndex,
1790 jsonNewNumberObject(dbi_result_get_long(result, columnName)));
1794 case DBI_TYPE_DECIMAL :
1795 jsonObjectSetIndex( object, fmIndex,
1796 jsonNewNumberObject(dbi_result_get_double(result, columnName)));
1799 case DBI_TYPE_STRING :
1805 jsonNewObject( dbi_result_get_string(result, columnName) )
1810 case DBI_TYPE_DATETIME :
1812 memset(dt_string, '\0', 256);
1813 memset(&gmdt, '\0', sizeof(gmdt));
1814 memset(&_tmp_dt, '\0', sizeof(_tmp_dt));
1816 _tmp_dt = dbi_result_get_datetime(result, columnName);
1818 localtime_r( &_tmp_dt, &gmdt );
1820 if (!(attr & DBI_DATETIME_DATE)) {
1821 strftime(dt_string, 255, "%T", &gmdt);
1822 } else if (!(attr & DBI_DATETIME_TIME)) {
1823 strftime(dt_string, 255, "%F", &gmdt);
1825 strftime(dt_string, 255, "%FT%T%z", &gmdt);
1828 jsonObjectSetIndex( object, fmIndex, jsonNewObject(dt_string) );
1832 case DBI_TYPE_BINARY :
1833 osrfLogError( OSRF_LOG_MARK,
1834 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);