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* searchFieldTransform (osrfHash*, jsonObject*);
47 char* searchFieldTransformPredicate ( osrfHash*, jsonObjectNode* );
48 char* searchBETWEENPredicate ( osrfHash*, jsonObject* );
49 char* searchINPredicate ( osrfHash*, jsonObject* );
50 char* searchPredicate ( osrfHash*, jsonObject* );
51 char* buildSELECT ( jsonObject*, jsonObject*, osrfHash*, osrfMethodContext* );
53 void userDataFree( void* );
54 void sessionDataFree( char*, void* );
56 dbi_conn writehandle; /* our MASTER db connection */
57 dbi_conn dbhandle; /* our CURRENT db connection */
59 jsonObject* jsonNULL = NULL; //
62 /* parse and store the IDL here */
65 int osrfAppInitialize() {
67 // first we register all the transaction and savepoint methods
68 osrfAppRegisterMethod( MODULENAME, "open-ils.cstore.transaction.begin", "beginTransaction", "", 0, 0 );
69 osrfAppRegisterMethod( MODULENAME, "open-ils.cstore.transaction.commit", "commitTransaction", "", 0, 0 );
70 osrfAppRegisterMethod( MODULENAME, "open-ils.cstore.transaction.rollback", "rollbackTransaction", "", 0, 0 );
72 osrfAppRegisterMethod( MODULENAME, "open-ils.cstore.savepoint.set", "setSavepoint", "", 1, 0 );
73 osrfAppRegisterMethod( MODULENAME, "open-ils.cstore.savepoint.release", "releaseSavepoint", "", 1, 0 );
74 osrfAppRegisterMethod( MODULENAME, "open-ils.cstore.savepoint.rollback", "rollbackSavepoint", "", 1, 0 );
77 osrfLogInfo(OSRF_LOG_MARK, "Initializing the CStore Server...");
78 osrfLogInfo(OSRF_LOG_MARK, "Finding XML file...");
80 char * idl_filename = osrf_settings_host_value("/apps/%s/app_settings/IDL", MODULENAME);
81 osrfLogInfo(OSRF_LOG_MARK, "Found file:");
82 osrfLogInfo(OSRF_LOG_MARK, idl_filename);
84 idl = oilsIDLInit( idl_filename );
87 osrfLogError(OSRF_LOG_MARK, "Problem loading the IDL. Seacrest out!");
91 osrfStringArray* global_methods = osrfNewStringArray(6);
93 osrfStringArrayAdd( global_methods, "create" );
94 osrfStringArrayAdd( global_methods, "retrieve" );
95 osrfStringArrayAdd( global_methods, "update" );
96 osrfStringArrayAdd( global_methods, "delete" );
97 osrfStringArrayAdd( global_methods, "search" );
98 osrfStringArrayAdd( global_methods, "id_list" );
102 osrfStringArray* classes = osrfHashKeys( idl );
103 osrfLogDebug(OSRF_LOG_MARK, "%d classes loaded", classes->size );
104 osrfLogDebug(OSRF_LOG_MARK, "At least %d methods will be generated", classes->size * global_methods->size);
106 while ( (classname = osrfStringArrayGetString(classes, c_index++)) ) {
107 osrfLogInfo(OSRF_LOG_MARK, "Generating class methods for %s", classname);
109 osrfHash* idlClass = osrfHashGet(idl, classname);
111 char* virt = osrfHashGet(idlClass, "virtual");
112 if (virt && !strcmp( virt, "true")) {
113 osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
117 osrfLogDebug(OSRF_LOG_MARK, "HERE");
124 osrfHash* method_meta;
125 while ( (method_type = osrfStringArrayGetString(global_methods, i++)) ) {
126 osrfLogDebug(OSRF_LOG_MARK, "Using files to build %s class methods for %s", method_type, classname);
128 if (!osrfHashGet(idlClass, "fieldmapper")) continue;
130 method_meta = osrfNewHash();
131 osrfHashSet(method_meta, idlClass, "class");
133 _fm = strdup( (char*)osrfHashGet(idlClass, "fieldmapper") );
134 part = strtok_r(_fm, ":", &st_tmp);
136 growing_buffer* method_name = buffer_init(64);
137 buffer_fadd(method_name, "%s.direct.%s", MODULENAME, part);
139 while ((part = strtok_r(NULL, ":", &st_tmp))) {
140 buffer_fadd(method_name, ".%s", part);
142 buffer_fadd(method_name, ".%s", method_type);
145 char* method = buffer_data(method_name);
146 buffer_free(method_name);
149 osrfHashSet( method_meta, method, "methodname" );
150 osrfHashSet( method_meta, method_type, "methodtype" );
153 if (!(strcmp( method_type, "search" )) || !(strcmp( method_type, "id_list" ))) {
154 flags = flags | OSRF_METHOD_STREAMING;
157 osrfAppRegisterExtendedMethod(
160 "dispatchCRUDMethod",
173 * Connects to the database
175 int osrfAppChildInit() {
177 osrfLogDebug(OSRF_LOG_MARK, "Attempting to initialize libdbi...");
178 dbi_initialize(NULL);
179 osrfLogDebug(OSRF_LOG_MARK, "... libdbi initialized.");
181 char* driver = osrf_settings_host_value("/apps/%s/app_settings/driver", MODULENAME);
182 char* user = osrf_settings_host_value("/apps/%s/app_settings/database/user", MODULENAME);
183 char* host = osrf_settings_host_value("/apps/%s/app_settings/database/host", MODULENAME);
184 char* port = osrf_settings_host_value("/apps/%s/app_settings/database/port", MODULENAME);
185 char* db = osrf_settings_host_value("/apps/%s/app_settings/database/db", MODULENAME);
186 char* pw = osrf_settings_host_value("/apps/%s/app_settings/database/pw", MODULENAME);
188 osrfLogDebug(OSRF_LOG_MARK, "Attempting to load the database driver [%s]...", driver);
189 writehandle = dbi_conn_new(driver);
192 osrfLogError(OSRF_LOG_MARK, "Error loading database driver [%s]", driver);
195 osrfLogDebug(OSRF_LOG_MARK, "Database driver [%s] seems OK", driver);
197 osrfLogInfo(OSRF_LOG_MARK, "%s connecting to database. host=%s, "
198 "port=%s, user=%s, pw=%s, db=%s", MODULENAME, host, port, user, pw, db );
200 if(host) dbi_conn_set_option(writehandle, "host", host );
201 if(port) dbi_conn_set_option_numeric( writehandle, "port", atoi(port) );
202 if(user) dbi_conn_set_option(writehandle, "username", user);
203 if(pw) dbi_conn_set_option(writehandle, "password", pw );
204 if(db) dbi_conn_set_option(writehandle, "dbname", db );
213 if (dbi_conn_connect(writehandle) < 0) {
214 dbi_conn_error(writehandle, &err);
215 osrfLogError( OSRF_LOG_MARK, "Error connecting to database: %s", err);
219 osrfLogInfo(OSRF_LOG_MARK, "%s successfully connected to the database", MODULENAME);
225 osrfStringArray* classes = osrfHashKeys( idl );
227 while ( (classname = osrfStringArrayGetString(classes, i++)) ) {
228 osrfHash* class = osrfHashGet( idl, classname );
229 osrfHash* fields = osrfHashGet( class, "fields" );
231 char* virt = osrfHashGet(class, "virtual");
232 if (virt && !strcmp( virt, "true")) {
233 osrfLogDebug(OSRF_LOG_MARK, "Class %s is virtual, skipping", classname );
238 growing_buffer* sql_buf = buffer_init(32);
239 buffer_fadd( sql_buf, "SELECT * FROM %s WHERE 1=0;", osrfHashGet(class, "tablename") );
241 char* sql = buffer_data(sql_buf);
242 buffer_free(sql_buf);
243 osrfLogDebug(OSRF_LOG_MARK, "%s Investigatory SQL = %s", MODULENAME, sql);
245 dbi_result result = dbi_conn_query(writehandle, sql);
251 const char* columnName;
253 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
255 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
257 /* fetch the fieldmapper index */
258 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
260 osrfLogDebug(OSRF_LOG_MARK, "Found [%s] in IDL hash...", (char*)columnName);
262 /* determine the field type and storage attributes */
263 type = dbi_result_get_field_type(result, columnName);
264 attr = dbi_result_get_field_attribs(result, columnName);
268 case DBI_TYPE_INTEGER :
270 if ( !osrfHashGet(_f, "primitive") )
271 osrfHashSet(_f,"number", "primitive");
273 if( attr & DBI_INTEGER_SIZE8 )
274 osrfHashSet(_f,"INT8", "datatype");
276 osrfHashSet(_f,"INT", "datatype");
279 case DBI_TYPE_DECIMAL :
280 if ( !osrfHashGet(_f, "primitive") )
281 osrfHashSet(_f,"number", "primitive");
283 osrfHashSet(_f,"NUMERIC", "datatype");
286 case DBI_TYPE_STRING :
287 if ( !osrfHashGet(_f, "primitive") )
288 osrfHashSet(_f,"string", "primitive");
289 osrfHashSet(_f,"TEXT", "datatype");
292 case DBI_TYPE_DATETIME :
293 if ( !osrfHashGet(_f, "primitive") )
294 osrfHashSet(_f,"string", "primitive");
296 osrfHashSet(_f,"TIMESTAMP", "datatype");
299 case DBI_TYPE_BINARY :
300 if ( !osrfHashGet(_f, "primitive") )
301 osrfHashSet(_f,"string", "primitive");
303 osrfHashSet(_f,"BYTEA", "datatype");
308 "Setting [%s] to primitive [%s] and datatype [%s]...",
310 osrfHashGet(_f, "primitive"),
311 osrfHashGet(_f, "datatype")
315 dbi_result_free(result);
317 osrfLogDebug(OSRF_LOG_MARK, "No data found for class [%s]...", (char*)classname);
321 osrfStringArrayFree(classes);
326 void userDataFree( void* blob ) {
327 osrfHashFree( (osrfHash*)blob );
331 void sessionDataFree( char* key, void* item ) {
332 if (!(strcmp(key,"xact_id"))) {
334 dbi_conn_query(writehandle, "ROLLBACK;");
341 int beginTransaction ( osrfMethodContext* ctx ) {
342 OSRF_METHOD_VERIFY_CONTEXT(ctx);
344 dbi_result result = dbi_conn_query(writehandle, "START TRANSACTION;");
346 osrfLogError(OSRF_LOG_MARK, "%s: Error starting transaction", MODULENAME );
347 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error starting transaction" );
350 jsonObject* ret = jsonNewObject(ctx->session->session_id);
351 osrfAppRespondComplete( ctx, ret );
354 if (!ctx->session->userData) {
355 ctx->session->userData = osrfNewHash();
356 ((osrfHash*)ctx->session->userData)->freeItem = &sessionDataFree;
359 osrfHashSet( (osrfHash*)ctx->session->userData, strdup( ctx->session->session_id ), "xact_id" );
360 ctx->session->userDataFree = &userDataFree;
366 int setSavepoint ( osrfMethodContext* ctx ) {
367 OSRF_METHOD_VERIFY_CONTEXT(ctx);
369 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
371 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
372 osrfAppSessionStatus(
374 OSRF_STATUS_INTERNALSERVERERROR,
375 "osrfMethodException",
377 "No active transaction -- required for savepoints"
382 dbi_result result = dbi_conn_queryf(writehandle, "SAVEPOINT \"%s\";", spName);
386 "%s: Error creating savepoint %s in transaction %s",
389 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
391 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error creating savepoint" );
394 jsonObject* ret = jsonNewObject(spName);
395 osrfAppRespondComplete( ctx, ret );
401 int releaseSavepoint ( osrfMethodContext* ctx ) {
402 OSRF_METHOD_VERIFY_CONTEXT(ctx);
404 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
406 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
407 osrfAppSessionStatus(
409 OSRF_STATUS_INTERNALSERVERERROR,
410 "osrfMethodException",
412 "No active transaction -- required for savepoints"
417 dbi_result result = dbi_conn_queryf(writehandle, "RELEASE SAVEPOINT \"%s\";", spName);
421 "%s: Error releasing savepoint %s in transaction %s",
424 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
426 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error releasing savepoint" );
429 jsonObject* ret = jsonNewObject(spName);
430 osrfAppRespondComplete( ctx, ret );
436 int rollbackSavepoint ( osrfMethodContext* ctx ) {
437 OSRF_METHOD_VERIFY_CONTEXT(ctx);
439 char* spName = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
441 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
442 osrfAppSessionStatus(
444 OSRF_STATUS_INTERNALSERVERERROR,
445 "osrfMethodException",
447 "No active transaction -- required for savepoints"
452 dbi_result result = dbi_conn_queryf(writehandle, "ROLLBACK TO SAVEPOINT \"%s\";", spName);
456 "%s: Error rolling back savepoint %s in transaction %s",
459 osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )
461 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back savepoint" );
464 jsonObject* ret = jsonNewObject(spName);
465 osrfAppRespondComplete( ctx, ret );
471 int commitTransaction ( osrfMethodContext* ctx ) {
472 OSRF_METHOD_VERIFY_CONTEXT(ctx);
474 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
475 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to commit" );
479 dbi_result result = dbi_conn_query(writehandle, "COMMIT;");
481 osrfLogError(OSRF_LOG_MARK, "%s: Error committing transaction", MODULENAME );
482 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error committing transaction" );
485 osrfHashRemove(ctx->session->userData, "xact_id");
486 jsonObject* ret = jsonNewObject(ctx->session->session_id);
487 osrfAppRespondComplete( ctx, ret );
493 int rollbackTransaction ( osrfMethodContext* ctx ) {
494 OSRF_METHOD_VERIFY_CONTEXT(ctx);
496 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
497 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "No active transaction to roll back" );
501 dbi_result result = dbi_conn_query(writehandle, "ROLLBACK;");
503 osrfLogError(OSRF_LOG_MARK, "%s: Error rolling back transaction", MODULENAME );
504 osrfAppSessionStatus( ctx->session, OSRF_STATUS_INTERNALSERVERERROR, "osrfMethodException", ctx->request, "Error rolling back transaction" );
507 osrfHashRemove(ctx->session->userData, "xact_id");
508 jsonObject* ret = jsonNewObject(ctx->session->session_id);
509 osrfAppRespondComplete( ctx, ret );
515 int dispatchCRUDMethod ( osrfMethodContext* ctx ) {
516 OSRF_METHOD_VERIFY_CONTEXT(ctx);
518 osrfHash* meta = (osrfHash*) ctx->method->userData;
519 osrfHash* class_obj = osrfHashGet( meta, "class" );
523 jsonObject * obj = NULL;
524 if (!strcmp( (char*)osrfHashGet(meta, "methodtype"), "create"))
525 obj = doCreate(ctx, &err);
527 if (!strcmp( (char*)osrfHashGet(meta, "methodtype"), "retrieve"))
528 obj = doRetrieve(ctx, &err);
530 if (!strcmp( (char*)osrfHashGet(meta, "methodtype"), "update"))
531 obj = doUpdate(ctx, &err);
533 if (!strcmp( (char*)osrfHashGet(meta, "methodtype"), "delete"))
534 obj = doDelete(ctx, &err);
536 if (!strcmp( (char*)osrfHashGet(meta, "methodtype"), "search")) {
538 obj = doSearch(ctx, class_obj, ctx->params, &err);
542 jsonObjectIterator* itr = jsonNewObjectIterator( obj );
543 while ((cur = jsonObjectIteratorNext( itr ))) {
544 osrfAppRespond( ctx, jsonObjectClone(cur->item) );
546 jsonObjectIteratorFree(itr);
547 osrfAppRespondComplete( ctx, NULL );
549 } else if (!strcmp( (char*)osrfHashGet(meta, "methodtype"), "id_list")) {
551 jsonObject* _p = jsonObjectClone( ctx->params );
552 if (jsonObjectGetIndex( _p, 1 )) {
553 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh" );
554 jsonObjectRemoveKey( jsonObjectGetIndex( _p, 1 ), "flesh_columns" );
556 jsonObjectSetIndex( _p, 1, jsonParseString("{}") );
559 growing_buffer* sel_list = buffer_init(16);
560 buffer_fadd(sel_list, "{ \"%s\":[\"%s\"] }", osrfHashGet( class_obj, "classname" ), osrfHashGet( class_obj, "primarykey" ));
561 char* _s = buffer_data(sel_list);
562 buffer_free(sel_list);
564 jsonObjectSetKey( jsonObjectGetIndex( _p, 1 ), "select", jsonParseString(_s) );
565 osrfLogDebug(OSRF_LOG_MARK, "%s: Select qualifer set to [%s]", MODULENAME, _s);
568 obj = doSearch(ctx, class_obj, _p, &err);
572 jsonObjectIterator* itr = jsonNewObjectIterator( obj );
573 while ((cur = jsonObjectIteratorNext( itr ))) {
582 osrfHashGet( class_obj, "fields" ),
583 osrfHashGet( class_obj, "primarykey")
592 jsonObjectIteratorFree(itr);
593 osrfAppRespondComplete( ctx, NULL );
596 osrfAppRespondComplete( ctx, obj );
604 int verifyObjectClass ( osrfMethodContext* ctx, jsonObject* param ) {
606 osrfHash* meta = (osrfHash*) ctx->method->userData;
607 osrfHash* class = osrfHashGet( meta, "class" );
609 if ((strcmp( osrfHashGet(class, "classname"), param->classname ))) {
611 growing_buffer* msg = buffer_init(128);
614 "%s: %s method for type %s was passed a %s",
616 osrfHashGet(meta, "methodtype"),
617 osrfHashGet(class, "classname"),
621 char* m = buffer_data(msg);
622 osrfAppSessionStatus( ctx->session, OSRF_STATUS_BADREQUEST, "osrfMethodException", ctx->request, m );
632 jsonObject* doCreate(osrfMethodContext* ctx, int* err ) {
634 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
635 jsonObject* target = jsonObjectGetIndex( ctx->params, 0 );
636 jsonObject* options = jsonObjectGetIndex( ctx->params, 1 );
638 if (!verifyObjectClass(ctx, target)) {
643 osrfLogDebug( OSRF_LOG_MARK, "Object seems to be of the correct type" );
645 if (!ctx->session || !ctx->session->userData || !osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
646 osrfLogError( OSRF_LOG_MARK, "No active transaction -- required for CREATE" );
648 osrfAppSessionStatus(
650 OSRF_STATUS_BADREQUEST,
651 "osrfMethodException",
653 "No active transaction -- required for CREATE"
659 char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
661 // Set the last_xact_id
662 osrfHash* last_xact_id;
663 if ((last_xact_id = oilsIDLFindPath("/%s/fields/last_xact_id", target->classname))) {
664 int index = atoi( osrfHashGet(last_xact_id, "array_position") );
665 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
666 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
669 osrfLogDebug( OSRF_LOG_MARK, "There is a transaction running..." );
671 dbhandle = writehandle;
673 osrfHash* fields = osrfHashGet(meta, "fields");
674 char* pkey = osrfHashGet(meta, "primarykey");
675 char* seq = osrfHashGet(meta, "sequence");
677 growing_buffer* table_buf = buffer_init(128);
678 growing_buffer* col_buf = buffer_init(128);
679 growing_buffer* val_buf = buffer_init(128);
681 buffer_fadd(table_buf,"INSERT INTO %s", osrfHashGet(meta, "tablename"));
682 buffer_add(col_buf,"(");
683 buffer_add(val_buf,"VALUES (");
689 osrfStringArray* field_list = osrfHashKeys( fields );
690 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
692 osrfHash* field = osrfHashGet( fields, field_name );
694 if(!( strcmp( osrfHashGet(osrfHashGet(fields,field_name), "virtual"), "true" ) )) continue;
696 int pos = atoi(osrfHashGet(field, "array_position"));
697 char* value = jsonObjectToSimpleString( jsonObjectGetIndex( target, pos ) );
702 buffer_add(col_buf, ",");
703 buffer_add(val_buf, ",");
706 buffer_add(col_buf, field_name);
708 if (!jsonObjectGetIndex(target, pos) || jsonObjectGetIndex(target, pos)->type == JSON_NULL) {
709 buffer_add( val_buf, "DEFAULT" );
711 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
712 if ( !strcmp(osrfHashGet(field, "datatype"), "INT8") ) {
713 buffer_fadd( val_buf, "%lld", atol(value) );
715 } else if ( !strcmp(osrfHashGet(field, "datatype"), "INT") ) {
716 buffer_fadd( val_buf, "%ld", atoll(value) );
718 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
719 buffer_fadd( val_buf, "%f", atof(value) );
722 if ( dbi_conn_quote_string(writehandle, &value) ) {
723 buffer_fadd( val_buf, "%s", value );
726 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
727 osrfAppSessionStatus(
729 OSRF_STATUS_INTERNALSERVERERROR,
730 "osrfMethodException",
732 "Error quoting string -- please see the error log for more details"
735 buffer_free(table_buf);
736 buffer_free(col_buf);
737 buffer_free(val_buf);
748 buffer_add(col_buf,")");
749 buffer_add(val_buf,")");
751 growing_buffer* sql = buffer_init(128);
755 buffer_data(table_buf),
756 buffer_data(col_buf),
759 buffer_free(table_buf);
760 buffer_free(col_buf);
761 buffer_free(val_buf);
763 char* query = buffer_data(sql);
766 osrfLogDebug(OSRF_LOG_MARK, "%s: Insert SQL [%s]", MODULENAME, query);
769 dbi_result result = dbi_conn_query(writehandle, query);
771 jsonObject* obj = NULL;
774 obj = jsonNewObject(NULL);
777 "%s ERROR inserting %s object using query [%s]",
779 osrfHashGet(meta, "fieldmapper"),
782 osrfAppSessionStatus(
784 OSRF_STATUS_INTERNALSERVERERROR,
785 "osrfMethodException",
787 "INSERT error -- please see the error log for more details"
792 int pos = atoi(osrfHashGet( osrfHashGet(fields, pkey), "array_position" ));
793 char* id = jsonObjectToSimpleString(jsonObjectGetIndex(target, pos));
795 unsigned long long new_id = dbi_conn_sequence_last(writehandle, seq);
796 growing_buffer* _id = buffer_init(10);
797 buffer_fadd(_id, "%lld", new_id);
798 id = buffer_data(_id);
803 || !jsonObjectGetKey( options, "quiet")
804 || strcmp( jsonObjectToSimpleString(jsonObjectGetKey( options, "quiet")), "true" )
807 jsonObject* fake_params = jsonParseString("[]");
808 jsonObjectPush(fake_params, jsonParseString("{}"));
811 jsonObjectGetIndex(fake_params, 0),
812 osrfHashGet(meta, "primarykey"),
816 jsonObject* list = doSearch( ctx,meta, fake_params, err);
819 jsonObjectFree( fake_params );
822 obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
825 jsonObjectFree( list );
826 jsonObjectFree( fake_params );
829 obj = jsonNewObject(id);
841 jsonObject* doRetrieve(osrfMethodContext* ctx, int* err ) {
843 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
847 char* id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
848 jsonObject* order_hash = jsonObjectGetIndex(ctx->params, 1);
852 "%s retrieving %s object with id %s",
854 osrfHashGet(meta, "fieldmapper"),
858 jsonObject* fake_params = jsonParseString("[]");
859 jsonObjectPush(fake_params, jsonParseString("{}"));
862 jsonObjectGetIndex(fake_params, 0),
863 osrfHashGet(meta, "primarykey"),
867 if (order_hash) jsonObjectPush(fake_params, jsonObjectClone(order_hash) );
869 jsonObject* list = doSearch( ctx,meta, fake_params, err);
872 jsonObjectFree( fake_params );
876 obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
878 jsonObjectFree( list );
879 jsonObjectFree( fake_params );
884 char* jsonNumberToDBString ( osrfHash* field, jsonObject* value ) {
885 growing_buffer* val_buf = buffer_init(32);
887 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", 3) ) {
888 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%ld", (long)jsonObjectGetNumber(value) );
889 else buffer_fadd( val_buf, "%ld", atol(jsonObjectToSimpleString(value)) );
891 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
892 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%f", jsonObjectGetNumber(value) );
893 else buffer_fadd( val_buf, "%f", atof(jsonObjectToSimpleString(value)) );
896 char* pred = buffer_data(val_buf);
897 buffer_free(val_buf);
902 char* searchINPredicate (osrfHash* field, jsonObject* node) {
903 growing_buffer* sql_buf = buffer_init(32);
908 osrfHashGet(field, "name")
911 int in_item_index = 0;
912 int in_item_first = 1;
914 while ( (in_item = jsonObjectGetIndex(node, in_item_index++)) ) {
919 buffer_add(sql_buf, ", ");
921 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
922 char* val = jsonNumberToDBString( field, in_item );
923 buffer_fadd( sql_buf, "%s", val );
927 char* key_string = jsonObjectToSimpleString(in_item);
928 if ( dbi_conn_quote_string(dbhandle, &key_string) ) {
929 buffer_fadd( sql_buf, "%s", key_string );
932 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, key_string);
934 buffer_free(sql_buf);
945 char* pred = buffer_data(sql_buf);
946 buffer_free(sql_buf);
951 char* searchValueTransform( jsonObject* array ) {
952 growing_buffer* sql_buf = buffer_init(32);
955 int func_item_index = 0;
956 int func_item_first = 2;
957 jsonObject* func_item;
958 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
960 val = jsonObjectToSimpleString(func_item);
962 if (func_item_first == 2) {
963 buffer_fadd(sql_buf, "%s( ", val);
972 buffer_add(sql_buf, ", ");
974 if ( dbi_conn_quote_string(dbhandle, &val) ) {
975 buffer_fadd( sql_buf, "%s", val );
978 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
980 buffer_free(sql_buf);
990 char* pred = buffer_data(sql_buf);
991 buffer_free(sql_buf);
996 char* searchFunctionPredicate (osrfHash* field, jsonObjectNode* node) {
997 growing_buffer* sql_buf = buffer_init(32);
999 char* val = searchValueTransform(node->item);
1004 osrfHashGet(field, "name"),
1009 char* pred = buffer_data(sql_buf);
1010 buffer_free(sql_buf);
1016 char* searchFieldTransform (osrfHash* field, jsonObject* node) {
1017 growing_buffer* sql_buf = buffer_init(32);
1019 char* field_transform = jsonObjectToSimpleString( jsonObjectGetKey( node, "transform" ) );
1025 osrfHashGet(field, "name")
1028 char* pred = buffer_data(sql_buf);
1029 buffer_free(sql_buf);
1030 free(field_transform);
1035 char* searchFieldTransformPredicate (osrfHash* field, jsonObjectNode* node) {
1036 growing_buffer* sql_buf = buffer_init(32);
1038 char* field_transform = searchFieldTransform( field, node->item );
1041 if (jsonObjectGetKey( node->item, "value" )->type == JSON_ARRAY) {
1042 value = searchValueTransform(jsonObjectGetKey( node->item, "value" ));
1043 } else if (jsonObjectGetKey( node->item, "value" )->type != JSON_NULL) {
1044 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1045 value = jsonNumberToDBString( field, jsonObjectGetKey( node->item, "value" ) );
1047 value = jsonObjectToSimpleString(jsonObjectGetKey( node->item, "value" ));
1048 if ( !dbi_conn_quote_string(dbhandle, &value) ) {
1049 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, value);
1064 char* pred = buffer_data(sql_buf);
1065 buffer_free(sql_buf);
1066 free(field_transform);
1071 char* searchSimplePredicate (const char* orig_op, osrfHash* field, jsonObject* node) {
1075 if (node->type != JSON_NULL) {
1076 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1077 val = jsonNumberToDBString( field, node );
1079 val = jsonObjectToSimpleString(node);
1083 char* pred = searchWriteSimplePredicate( field, osrfHashGet(field, "name"), orig_op, val );
1090 char* searchWriteSimplePredicate ( osrfHash* field, const char* left, const char* orig_op, const char* right ) {
1094 if (right == NULL) {
1095 val = strdup("NULL");
1097 if (strcmp( orig_op, "=" ))
1098 op = strdup("IS NOT");
1102 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1103 val = strdup(right);
1104 op = strdup(orig_op);
1107 val = strdup(right);
1108 if ( !dbi_conn_quote_string(dbhandle, &val) ) {
1109 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1113 op = strdup(orig_op);
1116 growing_buffer* sql_buf = buffer_init(16);
1117 buffer_fadd( sql_buf, "%s %s %s", left, op, val );
1121 char* pred = buffer_data(sql_buf);
1122 buffer_free(sql_buf);
1128 char* searchBETWEENPredicate (osrfHash* field, jsonObject* node) {
1133 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1134 x_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,0));
1135 y_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,1));
1138 x_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,0));
1139 y_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,1));
1140 if ( !(dbi_conn_quote_string(dbhandle, &x_string) && dbi_conn_quote_string(dbhandle, &y_string)) ) {
1141 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key strings [%s] and [%s]", MODULENAME, x_string, y_string);
1148 growing_buffer* sql_buf = buffer_init(32);
1149 buffer_fadd( sql_buf, "%s BETWEEN %s AND %s", osrfHashGet(field, "name"), x_string, y_string );
1153 char* pred = buffer_data(sql_buf);
1154 buffer_free(sql_buf);
1159 char* searchPredicate ( osrfHash* field, jsonObject* node ) {
1162 if (node->type == JSON_ARRAY) { // equality IN search
1163 pred = searchINPredicate( field, node );
1164 } else if (node->type == JSON_HASH) { // non-equality search
1165 jsonObjectNode* pred_node;
1166 jsonObjectIterator* pred_itr = jsonNewObjectIterator( node );
1167 while ( (pred_node = jsonObjectIteratorNext( pred_itr )) ) {
1168 if ( !(strcasecmp( pred_node->key,"between" )) )
1169 pred = searchBETWEENPredicate( field, pred_node->item );
1170 else if ( !(strcasecmp( pred_node->key,"in" )) )
1171 pred = searchINPredicate( field, pred_node->item );
1172 else if ( pred_node->item->type == JSON_ARRAY )
1173 pred = searchFunctionPredicate( field, pred_node );
1174 else if ( pred_node->item->type == JSON_HASH )
1175 pred = searchFieldTransformPredicate( field, pred_node );
1177 pred = searchSimplePredicate( pred_node->key, field, pred_node->item );
1181 } else if (node->type == JSON_NULL) { // IS NULL search
1182 growing_buffer* _p = buffer_init(16);
1186 osrfHashGet(field, "name")
1188 pred = buffer_data(_p);
1190 } else { // equality search
1191 pred = searchSimplePredicate( "=", field, node );
1198 char* buildSELECT ( jsonObject* search_hash, jsonObject* order_hash, osrfHash* meta, osrfMethodContext* ctx ) {
1200 osrfHash* links = osrfHashGet(meta, "links");
1201 osrfHash* fields = osrfHashGet(meta, "fields");
1202 char* core_class = osrfHashGet(meta, "classname");
1204 jsonObjectNode* node = NULL;
1205 jsonObjectNode* snode = NULL;
1208 growing_buffer* sql_buf = buffer_init(128);
1209 buffer_add(sql_buf, "SELECT");
1212 if ( (_tmp = jsonObjectGetKey( order_hash, "select" )) ) {
1214 jsonObjectIterator* class_itr = jsonNewObjectIterator( _tmp );
1215 while ( (snode = jsonObjectIteratorNext( class_itr )) ) {
1217 osrfHash* idlClass = osrfHashGet( idl, snode->key );
1218 if (!idlClass) continue;
1219 char* cname = osrfHashGet(idlClass, "classname");
1221 if (strcmp(core_class,snode->key)) continue;
1223 jsonObjectIterator* select_itr = jsonNewObjectIterator( snode->item );
1224 while ( (node = jsonObjectIteratorNext( select_itr )) ) {
1225 osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), jsonObjectToSimpleString(node->item) );
1226 char* fname = osrfHashGet(field, "name");
1228 if (!field) continue;
1233 buffer_add(sql_buf, ",");
1236 buffer_fadd(sql_buf, " \"%s\".%s", cname, fname, cname, fname);
1240 if (first) buffer_add(sql_buf, " *");
1243 buffer_add(sql_buf, " *");
1246 buffer_fadd(sql_buf, " FROM %s AS \"%s\" WHERE ", osrfHashGet(meta, "tablename"), core_class );
1251 jsonObjectIterator* search_itr = jsonNewObjectIterator( search_hash );
1252 while ( (node = jsonObjectIteratorNext( search_itr )) ) {
1253 osrfHash* field = osrfHashGet( fields, node->key );
1258 "%s: Attempt to reference non-existant column %s on table %s",
1261 osrfHashGet(meta, "tablename")
1263 osrfAppSessionStatus(
1265 OSRF_STATUS_INTERNALSERVERERROR,
1266 "osrfMethodException",
1268 "Severe query error -- see error log for more details"
1270 buffer_free(sql_buf);
1277 buffer_add(sql_buf, " AND ");
1280 pred = searchPredicate( field, node->item);
1281 buffer_fadd( sql_buf, "%s", pred );
1285 jsonObjectIteratorFree(search_itr);
1289 if ( (_tmp = jsonObjectGetKey( jsonObjectGetKey( order_hash, "order_by" ), core_class ) ) ){
1290 string = jsonObjectToSimpleString(_tmp);
1299 if ( (_tmp = jsonObjectGetKey( order_hash, "limit" )) ){
1300 string = jsonObjectToSimpleString(_tmp);
1309 _tmp = jsonObjectGetKey( order_hash, "offset" );
1311 string = jsonObjectToSimpleString(_tmp);
1321 buffer_add(sql_buf, ";");
1323 char* sql = buffer_data(sql_buf);
1324 buffer_free(sql_buf);
1329 jsonObject* doSearch ( osrfMethodContext* ctx, osrfHash* meta, jsonObject* params, int* err ) {
1332 dbhandle = writehandle;
1334 osrfHash* links = osrfHashGet(meta, "links");
1335 osrfHash* fields = osrfHashGet(meta, "fields");
1336 char* core_class = osrfHashGet(meta, "classname");
1340 jsonObject* search_hash = jsonObjectGetIndex(params, 0);
1341 jsonObject* order_hash = jsonObjectGetIndex(params, 1);
1343 char* sql = buildSELECT( search_hash, order_hash, meta, ctx );
1349 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
1350 dbi_result result = dbi_conn_query(dbhandle, sql);
1352 jsonObject* res_list = jsonParseString("[]");
1354 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
1356 if (dbi_result_first_row(result)) {
1357 /* JSONify the result */
1358 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
1360 obj = oilsMakeJSONFromResult( result, meta );
1361 jsonObjectPush(res_list, obj);
1362 } while (dbi_result_next_row(result));
1364 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
1367 /* clean up the query */
1368 dbi_result_free(result);
1371 osrfLogError(OSRF_LOG_MARK, "%s: Error retrieving %s with query [%s]", MODULENAME, osrfHashGet(meta, "fieldmapper"), sql);
1372 osrfAppSessionStatus(
1374 OSRF_STATUS_INTERNALSERVERERROR,
1375 "osrfMethodException",
1377 "Severe query error -- see error log for more details"
1381 jsonObjectFree(res_list);
1388 if (res_list->size && order_hash) {
1389 _tmp = jsonObjectGetKey( order_hash, "flesh" );
1391 int x = (int)jsonObjectGetNumber(_tmp);
1393 jsonObject* flesh_blob = NULL;
1394 if ((flesh_blob = jsonObjectGetKey( order_hash, "flesh_fields" )) && x > 0) {
1396 flesh_blob = jsonObjectClone( flesh_blob );
1397 jsonObject* flesh_fields = jsonObjectGetKey( flesh_blob, core_class );
1399 osrfStringArray* link_fields = NULL;
1402 if (flesh_fields->size == 1) {
1403 char* _t = jsonObjectToSimpleString( jsonObjectGetIndex( flesh_fields, 0 ) );
1404 if (!strcmp(_t,"*")) link_fields = osrfHashKeys( links );
1410 link_fields = osrfNewStringArray(1);
1411 jsonObjectIterator* _i = jsonNewObjectIterator( flesh_fields );
1412 while ((_f = jsonObjectIteratorNext( _i ))) {
1413 osrfStringArrayAdd( link_fields, jsonObjectToSimpleString( _f->item ) );
1418 jsonObjectNode* cur;
1419 jsonObjectIterator* itr = jsonNewObjectIterator( res_list );
1420 while ((cur = jsonObjectIteratorNext( itr ))) {
1425 while ( (link_field = osrfStringArrayGetString(link_fields, i++)) ) {
1427 osrfLogDebug(OSRF_LOG_MARK, "Starting to flesh %s", link_field);
1429 osrfHash* kid_link = osrfHashGet(links, link_field);
1430 if (!kid_link) continue;
1432 osrfHash* field = osrfHashGet(fields, link_field);
1433 if (!field) continue;
1435 osrfHash* value_field = field;
1437 osrfHash* kid_idl = osrfHashGet(idl, osrfHashGet(kid_link, "class"));
1438 if (!kid_idl) continue;
1440 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
1441 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
1444 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) { // might_have
1445 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
1448 osrfStringArray* link_map = osrfHashGet( kid_link, "map" );
1450 if (link_map->size > 0) {
1451 jsonObject* _kid_key = jsonParseString("[]");
1454 jsonNewObject( osrfStringArrayGetString( link_map, 0 ) )
1459 osrfHashGet(kid_link, "class"),
1466 "Link field: %s, remote class: %s, fkey: %s, reltype: %s",
1467 osrfHashGet(kid_link, "field"),
1468 osrfHashGet(kid_link, "class"),
1469 osrfHashGet(kid_link, "key"),
1470 osrfHashGet(kid_link, "reltype")
1473 jsonObject* fake_params = jsonParseString("[]");
1474 jsonObjectPush(fake_params, jsonParseString("{}")); // search hash
1475 jsonObjectPush(fake_params, jsonParseString("{}")); // order/flesh hash
1477 osrfLogDebug(OSRF_LOG_MARK, "Creating dummy params object...");
1480 jsonObjectToSimpleString(
1483 atoi( osrfHashGet(value_field, "array_position") )
1488 osrfLogDebug(OSRF_LOG_MARK, "Nothing to search for!");
1493 jsonObjectGetIndex(fake_params, 0),
1494 osrfHashGet(kid_link, "key"),
1495 jsonNewObject( search_key )
1502 jsonObjectGetIndex(fake_params, 1),
1504 jsonNewNumberObject( (double)(x - 1 + link_map->size) )
1508 jsonObjectSetKey( jsonObjectGetIndex(fake_params, 1), "flesh_fields", jsonObjectClone(flesh_blob) );
1510 if (jsonObjectGetKey(order_hash, "order_by")) {
1512 jsonObjectGetIndex(fake_params, 1),
1514 jsonObjectClone(jsonObjectGetKey(order_hash, "order_by"))
1518 if (jsonObjectGetKey(order_hash, "select")) {
1520 jsonObjectGetIndex(fake_params, 1),
1522 jsonObjectClone(jsonObjectGetKey(order_hash, "select"))
1526 jsonObject* kids = doSearch(ctx, kid_idl, fake_params, err);
1529 jsonObjectFree( fake_params );
1530 osrfStringArrayFree(link_fields);
1531 jsonObjectIteratorFree(itr);
1532 jsonObjectFree(res_list);
1536 osrfLogDebug(OSRF_LOG_MARK, "Search for %s return %d linked objects", osrfHashGet(kid_link, "class"), kids->size);
1538 jsonObject* X = NULL;
1539 if ( link_map->size > 0 && kids->size > 0 ) {
1541 kids = jsonParseString("[]");
1543 jsonObjectNode* _k_node;
1544 jsonObjectIterator* _k = jsonNewObjectIterator( X );
1545 while ((_k_node = jsonObjectIteratorNext( _k ))) {
1551 (unsigned long)atoi(
1557 osrfHashGet(kid_link, "class")
1561 osrfStringArrayGetString( link_map, 0 )
1572 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_a" )) || !(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) {
1573 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
1576 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
1577 jsonObjectClone( jsonObjectGetIndex(kids, 0) )
1581 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
1582 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
1585 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
1586 jsonObjectClone( kids )
1591 jsonObjectFree(kids);
1595 jsonObjectFree( kids );
1596 jsonObjectFree( fake_params );
1598 osrfLogDebug(OSRF_LOG_MARK, "Fleshing of %s complete", osrfHashGet(kid_link, "field"));
1599 osrfLogDebug(OSRF_LOG_MARK, "%s", jsonObjectToJSON(cur->item));
1603 jsonObjectFree( flesh_blob );
1604 osrfStringArrayFree(link_fields);
1605 jsonObjectIteratorFree(itr);
1614 jsonObject* doUpdate(osrfMethodContext* ctx, int* err ) {
1616 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1617 jsonObject* target = jsonObjectGetIndex(ctx->params, 0);
1619 if (!verifyObjectClass(ctx, target)) {
1624 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
1625 osrfAppSessionStatus(
1627 OSRF_STATUS_BADREQUEST,
1628 "osrfMethodException",
1630 "No active transaction -- required for UPDATE"
1636 dbhandle = writehandle;
1638 char* trans_id = osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" );
1640 // Set the last_xact_id
1641 osrfHash* last_xact_id;
1642 if ((last_xact_id = oilsIDLFindPath("/%s/fields/last_xact_id", target->classname))) {
1643 int index = atoi( osrfHashGet(last_xact_id, "array_position") );
1644 osrfLogDebug(OSRF_LOG_MARK, "Setting last_xact_id to %s on %s at position %d", trans_id, target->classname, index);
1645 jsonObjectSetIndex(target, index, jsonNewObject(trans_id));
1648 char* pkey = osrfHashGet(meta, "primarykey");
1649 osrfHash* fields = osrfHashGet(meta, "fields");
1652 jsonObjectToSimpleString(
1655 atoi( osrfHashGet( osrfHashGet( fields, pkey ), "array_position" ) )
1661 "%s updating %s object with %s = %s",
1663 osrfHashGet(meta, "fieldmapper"),
1668 growing_buffer* sql = buffer_init(128);
1669 buffer_fadd(sql,"UPDATE %s SET", osrfHashGet(meta, "tablename"));
1674 osrfStringArray* field_list = osrfHashKeys( fields );
1675 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
1677 osrfHash* field = osrfHashGet( fields, field_name );
1679 if(!( strcmp( field_name, pkey ) )) continue;
1680 if(!( strcmp( osrfHashGet(osrfHashGet(fields,field_name), "virtual"), "true" ) )) continue;
1682 int pos = atoi(osrfHashGet(field, "array_position"));
1683 char* value = jsonObjectToSimpleString( jsonObjectGetIndex( target, pos ) );
1685 osrfLogDebug( OSRF_LOG_MARK, "Updating %s object with %s = %s", osrfHashGet(meta, "fieldmapper"), field_name, value);
1687 if (!jsonObjectGetIndex(target, pos) || jsonObjectGetIndex(target, pos)->type == JSON_NULL) {
1688 if ( !(!( strcmp( osrfHashGet(meta, "classname"), "au" ) ) && !( strcmp( field_name, "passwd" ) )) ) { // arg at the special case!
1689 if (first) first = 0;
1690 else buffer_add(sql, ",");
1691 buffer_fadd( sql, " %s = NULL", field_name );
1694 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1695 if (first) first = 0;
1696 else buffer_add(sql, ",");
1698 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
1699 buffer_fadd( sql, " %s = %ld", field_name, atol(value) );
1700 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
1701 buffer_fadd( sql, " %s = %f", field_name, atof(value) );
1704 osrfLogDebug( OSRF_LOG_MARK, "%s is of type %s", field_name, osrfHashGet(field, "datatype"));
1707 if ( dbi_conn_quote_string(dbhandle, &value) ) {
1708 if (first) first = 0;
1709 else buffer_add(sql, ",");
1710 buffer_fadd( sql, " %s = %s", field_name, value );
1713 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
1714 osrfAppSessionStatus(
1716 OSRF_STATUS_INTERNALSERVERERROR,
1717 "osrfMethodException",
1719 "Error quoting string -- please see the error log for more details"
1733 jsonObject* obj = jsonParseString(id);
1735 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
1736 dbi_conn_quote_string(dbhandle, &id);
1738 buffer_fadd( sql, " WHERE %s = %s;", pkey, id );
1740 char* query = buffer_data(sql);
1743 osrfLogDebug(OSRF_LOG_MARK, "%s: Update SQL [%s]", MODULENAME, query);
1745 dbi_result result = dbi_conn_query(dbhandle, query);
1749 jsonObjectFree(obj);
1750 obj = jsonNewObject(NULL);
1753 "%s ERROR updating %s object with %s = %s",
1755 osrfHashGet(meta, "fieldmapper"),
1766 jsonObject* doDelete(osrfMethodContext* ctx, int* err ) {
1768 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1770 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
1771 osrfAppSessionStatus(
1773 OSRF_STATUS_BADREQUEST,
1774 "osrfMethodException",
1776 "No active transaction -- required for DELETE"
1782 dbhandle = writehandle;
1786 char* pkey = osrfHashGet(meta, "primarykey");
1789 if (jsonObjectGetIndex(ctx->params, 0)->classname) {
1790 if (!verifyObjectClass(ctx, jsonObjectGetIndex( ctx->params, 0 ))) {
1795 id = jsonObjectToSimpleString(
1797 jsonObjectGetIndex(ctx->params, 0),
1798 atoi( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "array_position") )
1802 id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
1807 "%s deleting %s object with %s = %s",
1809 osrfHashGet(meta, "fieldmapper"),
1814 obj = jsonParseString(id);
1816 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
1817 dbi_conn_quote_string(writehandle, &id);
1819 dbi_result result = dbi_conn_queryf(writehandle, "DELETE FROM %s WHERE %s = %s;", osrfHashGet(meta, "tablename"), pkey, id);
1822 jsonObjectFree(obj);
1823 obj = jsonNewObject(NULL);
1826 "%s ERROR deleting %s object with %s = %s",
1828 osrfHashGet(meta, "fieldmapper"),
1841 jsonObject* oilsMakeJSONFromResult( dbi_result result, osrfHash* meta) {
1842 if(!(result && meta)) return jsonNULL;
1844 jsonObject* object = jsonParseString("[]");
1845 jsonObjectSetClass(object, osrfHashGet(meta, "classname"));
1847 osrfHash* fields = osrfHashGet(meta, "fields");
1849 osrfLogInternal(OSRF_LOG_MARK, "Setting object class to %s ", object->classname);
1853 char dt_string[256];
1857 int columnIndex = 1;
1859 unsigned short type;
1860 const char* columnName;
1862 /* cycle through the column list */
1863 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
1865 osrfLogInternal(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
1867 fmIndex = -1; // reset the position
1869 /* determine the field type and storage attributes */
1870 type = dbi_result_get_field_type(result, columnName);
1871 attr = dbi_result_get_field_attribs(result, columnName);
1873 /* fetch the fieldmapper index */
1874 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
1875 char* virt = (char*)osrfHashGet(_f, "virtual");
1876 char* pos = (char*)osrfHashGet(_f, "array_position");
1878 if ( !virt || !pos || !(strcmp( virt, "true" )) ) continue;
1880 fmIndex = atoi( pos );
1881 osrfLogInternal(OSRF_LOG_MARK, "... Found column at position [%s]...", pos);
1886 if (dbi_result_field_is_null(result, columnName)) {
1887 jsonObjectSetIndex( object, fmIndex, jsonNewObject(NULL) );
1892 case DBI_TYPE_INTEGER :
1894 if( attr & DBI_INTEGER_SIZE8 )
1895 jsonObjectSetIndex( object, fmIndex,
1896 jsonNewNumberObject(dbi_result_get_longlong(result, columnName)));
1898 jsonObjectSetIndex( object, fmIndex,
1899 jsonNewNumberObject(dbi_result_get_long(result, columnName)));
1903 case DBI_TYPE_DECIMAL :
1904 jsonObjectSetIndex( object, fmIndex,
1905 jsonNewNumberObject(dbi_result_get_double(result, columnName)));
1908 case DBI_TYPE_STRING :
1914 jsonNewObject( dbi_result_get_string(result, columnName) )
1919 case DBI_TYPE_DATETIME :
1921 memset(dt_string, '\0', 256);
1922 memset(&gmdt, '\0', sizeof(gmdt));
1923 memset(&_tmp_dt, '\0', sizeof(_tmp_dt));
1925 _tmp_dt = dbi_result_get_datetime(result, columnName);
1927 localtime_r( &_tmp_dt, &gmdt );
1929 if (!(attr & DBI_DATETIME_DATE)) {
1930 strftime(dt_string, 255, "%T", &gmdt);
1931 } else if (!(attr & DBI_DATETIME_TIME)) {
1932 strftime(dt_string, 255, "%F", &gmdt);
1934 strftime(dt_string, 255, "%FT%T%z", &gmdt);
1937 jsonObjectSetIndex( object, fmIndex, jsonNewObject(dt_string) );
1941 case DBI_TYPE_BINARY :
1942 osrfLogError( OSRF_LOG_MARK,
1943 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);