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 );
631 jsonObject* options = jsonObjectGetIndex( ctx->params, 1 );
633 if (!verifyObjectClass(ctx, target)) {
638 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
639 osrfAppSessionStatus(
641 OSRF_STATUS_BADREQUEST,
642 "osrfMethodException",
644 "No active transaction -- required for CREATE"
650 dbhandle = writehandle;
652 osrfHash* fields = osrfHashGet(meta, "fields");
653 char* pkey = osrfHashGet(meta, "primarykey");
654 char* seq = osrfHashGet(meta, "sequence");
656 growing_buffer* table_buf = buffer_init(128);
657 growing_buffer* col_buf = buffer_init(128);
658 growing_buffer* val_buf = buffer_init(128);
660 buffer_fadd(table_buf,"INSERT INTO %s", osrfHashGet(meta, "tablename"));
661 buffer_add(col_buf,"(");
662 buffer_add(val_buf,"VALUES (");
667 osrfStringArray* field_list = osrfHashKeys( fields );
668 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
670 osrfHash* field = osrfHashGet( fields, field_name );
672 if(!( strcmp( osrfHashGet(osrfHashGet(fields,field_name), "virtual"), "true" ) )) continue;
674 int pos = atoi(osrfHashGet(field, "array_position"));
675 char* value = jsonObjectToSimpleString( jsonObjectGetIndex( target, pos ) );
680 buffer_add(col_buf, ",");
681 buffer_add(val_buf, ",");
684 buffer_add(col_buf, field_name);
686 if (jsonObjectGetIndex(target, pos)->type == JSON_NULL) {
687 buffer_add( val_buf, "DEFAULT" );
689 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
690 if ( !strcmp(osrfHashGet(field, "datatype"), "INT8") ) {
691 buffer_fadd( val_buf, "%lld", atol(value) );
693 } else if ( !strcmp(osrfHashGet(field, "datatype"), "INT") ) {
694 buffer_fadd( val_buf, "%ld", atoll(value) );
696 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
697 buffer_fadd( val_buf, "%f", atof(value) );
700 if ( dbi_conn_quote_string(writehandle, &value) ) {
701 buffer_fadd( val_buf, "%s", value );
704 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
705 osrfAppSessionStatus(
707 OSRF_STATUS_INTERNALSERVERERROR,
708 "osrfMethodException",
710 "Error quoting string -- please see the error log for more details"
713 buffer_free(table_buf);
714 buffer_free(col_buf);
715 buffer_free(val_buf);
725 buffer_add(col_buf,")");
726 buffer_add(val_buf,")");
728 growing_buffer* sql = buffer_init(128);
732 buffer_data(table_buf),
733 buffer_data(col_buf),
736 buffer_free(table_buf);
737 buffer_free(col_buf);
738 buffer_free(val_buf);
740 char* query = buffer_data(sql);
743 osrfLogDebug(OSRF_LOG_MARK, "%s: Insert SQL [%s]", MODULENAME, query);
746 dbi_result result = dbi_conn_query(writehandle, query);
748 jsonObject* obj = NULL;
751 obj = jsonNewObject(NULL);
754 "%s ERROR inserting %s object using query [%s]",
756 osrfHashGet(meta, "fieldmapper"),
759 osrfAppSessionStatus(
761 OSRF_STATUS_INTERNALSERVERERROR,
762 "osrfMethodException",
764 "INSERT error -- please see the error log for more details"
769 int pos = atoi(osrfHashGet( osrfHashGet(fields, pkey), "array_position" ));
770 char* id = jsonObjectToSimpleString(jsonObjectGetIndex(target, pos));
772 unsigned long long new_id = dbi_conn_sequence_last(writehandle, seq);
773 growing_buffer* _id = buffer_init(10);
774 buffer_fadd(_id, "%lld", new_id);
775 id = buffer_data(_id);
780 || !jsonObjectGetKey( options, "quiet")
781 || strcmp( jsonObjectToSimpleString(jsonObjectGetKey( options, "quiet")), "true" )
784 jsonObject* fake_params = jsonParseString("[]");
785 jsonObjectPush(fake_params, jsonParseString("{}"));
788 jsonObjectGetIndex(fake_params, 0),
789 osrfHashGet(meta, "primarykey"),
793 jsonObject* list = doSearch( ctx,meta, fake_params, err);
796 jsonObjectFree( fake_params );
799 obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
802 jsonObjectFree( list );
803 jsonObjectFree( fake_params );
806 obj = jsonNewObject(id);
818 jsonObject* doRetrieve(osrfMethodContext* ctx, int* err ) {
820 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
824 char* id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
825 jsonObject* order_hash = jsonObjectGetIndex(ctx->params, 1);
829 "%s retrieving %s object with id %s",
831 osrfHashGet(meta, "fieldmapper"),
835 jsonObject* fake_params = jsonParseString("[]");
836 jsonObjectPush(fake_params, jsonParseString("{}"));
839 jsonObjectGetIndex(fake_params, 0),
840 osrfHashGet(meta, "primarykey"),
844 if (order_hash) jsonObjectPush(fake_params, jsonObjectClone(order_hash) );
846 jsonObject* list = doSearch( ctx,meta, fake_params, err);
849 jsonObjectFree( fake_params );
853 obj = jsonObjectClone( jsonObjectGetIndex(list, 0) );
855 jsonObjectFree( list );
856 jsonObjectFree( fake_params );
861 char* jsonNumberToDBString ( osrfHash* field, jsonObject* value ) {
862 growing_buffer* val_buf = buffer_init(32);
864 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", 3) ) {
865 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%ld", (long)jsonObjectGetNumber(value) );
866 else buffer_fadd( val_buf, "%ld", atol(jsonObjectToSimpleString(value)) );
868 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
869 if (value->type == JSON_NUMBER) buffer_fadd( val_buf, "%f", jsonObjectGetNumber(value) );
870 else buffer_fadd( val_buf, "%f", atof(jsonObjectToSimpleString(value)) );
873 char* pred = buffer_data(val_buf);
874 buffer_free(val_buf);
879 char* searchINPredicate (osrfHash* field, jsonObject* node) {
880 growing_buffer* sql_buf = buffer_init(32);
885 osrfHashGet(field, "name")
888 int in_item_index = 0;
889 int in_item_first = 1;
891 while ( (in_item = jsonObjectGetIndex(node, in_item_index++)) ) {
896 buffer_add(sql_buf, ", ");
898 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
899 char* val = jsonNumberToDBString( field, in_item );
900 buffer_fadd( sql_buf, "%s", val );
904 char* key_string = jsonObjectToSimpleString(in_item);
905 if ( dbi_conn_quote_string(dbhandle, &key_string) ) {
906 buffer_fadd( sql_buf, "%s", key_string );
909 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, key_string);
911 buffer_free(sql_buf);
922 char* pred = buffer_data(sql_buf);
923 buffer_free(sql_buf);
928 char* searchValueTransform( jsonObject* array ) {
929 growing_buffer* sql_buf = buffer_init(32);
932 int func_item_index = 0;
933 int func_item_first = 2;
934 jsonObject* func_item;
935 while ( (func_item = jsonObjectGetIndex(array, func_item_index++)) ) {
937 val = jsonObjectToSimpleString(func_item);
939 if (func_item_first == 2) {
940 buffer_fadd(sql_buf, "%s( ", val);
949 buffer_add(sql_buf, ", ");
951 if ( dbi_conn_quote_string(dbhandle, &val) ) {
952 buffer_fadd( sql_buf, "%s", val );
955 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
957 buffer_free(sql_buf);
967 char* pred = buffer_data(sql_buf);
968 buffer_free(sql_buf);
973 char* searchFunctionPredicate (osrfHash* field, jsonObjectNode* node) {
974 growing_buffer* sql_buf = buffer_init(32);
976 char* val = searchValueTransform(node->item);
981 osrfHashGet(field, "name"),
986 char* pred = buffer_data(sql_buf);
987 buffer_free(sql_buf);
993 char* searchFieldTransformPredicate (osrfHash* field, jsonObjectNode* node) {
994 growing_buffer* sql_buf = buffer_init(32);
996 char* field_transform = jsonObjectToSimpleString( jsonObjectGetKey( node->item, "transform" ) );
999 if (jsonObjectGetKey( node->item, "value" )->type == JSON_ARRAY) {
1000 value = searchValueTransform(jsonObjectGetKey( node->item, "value" ));
1001 } else if (jsonObjectGetKey( node->item, "value" )->type != JSON_NULL) {
1002 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1003 value = jsonNumberToDBString( field, jsonObjectGetKey( node->item, "value" ) );
1005 value = jsonObjectToSimpleString(jsonObjectGetKey( node->item, "value" ));
1006 if ( !dbi_conn_quote_string(dbhandle, &value) ) {
1007 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, value);
1018 osrfHashGet(field, "name"),
1023 char* pred = buffer_data(sql_buf);
1024 buffer_free(sql_buf);
1029 char* searchSimplePredicate (const char* orig_op, osrfHash* field, jsonObject* node) {
1033 if (node->type != JSON_NULL) {
1034 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1035 val = jsonNumberToDBString( field, node );
1037 val = jsonObjectToSimpleString(node);
1041 char* pred = searchWriteSimplePredicate( field, osrfHashGet(field, "name"), orig_op, val );
1048 char* searchWriteSimplePredicate ( osrfHash* field, const char* left, const char* orig_op, const char* right ) {
1052 if (right == NULL) {
1053 val = strdup("NULL");
1055 if (strcmp( orig_op, "=" ))
1056 op = strdup("IS NOT");
1060 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1061 val = strdup(right);
1062 op = strdup(orig_op);
1065 val = strdup(right);
1066 if ( !dbi_conn_quote_string(dbhandle, &val) ) {
1067 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key string [%s]", MODULENAME, val);
1071 op = strdup(orig_op);
1074 growing_buffer* sql_buf = buffer_init(16);
1075 buffer_fadd( sql_buf, "%s %s %s", left, op, val );
1079 char* pred = buffer_data(sql_buf);
1080 buffer_free(sql_buf);
1086 char* searchBETWEENPredicate (osrfHash* field, jsonObject* node) {
1091 if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1092 x_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,0));
1093 y_string = jsonNumberToDBString(field, jsonObjectGetIndex(node,1));
1096 x_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,0));
1097 y_string = jsonObjectToSimpleString(jsonObjectGetIndex(node,1));
1098 if ( !(dbi_conn_quote_string(dbhandle, &x_string) && dbi_conn_quote_string(dbhandle, &y_string)) ) {
1099 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting key strings [%s] and [%s]", MODULENAME, x_string, y_string);
1106 growing_buffer* sql_buf = buffer_init(32);
1107 buffer_fadd( sql_buf, "%s BETWEEN %s AND %s", osrfHashGet(field, "name"), x_string, y_string );
1111 char* pred = buffer_data(sql_buf);
1112 buffer_free(sql_buf);
1117 char* searchPredicate ( osrfHash* field, jsonObject* node ) {
1120 if (node->type == JSON_ARRAY) { // equality IN search
1121 pred = searchINPredicate( field, node );
1122 } else if (node->type == JSON_HASH) { // non-equality search
1123 jsonObjectNode* pred_node;
1124 jsonObjectIterator* pred_itr = jsonNewObjectIterator( node );
1125 while ( (pred_node = jsonObjectIteratorNext( pred_itr )) ) {
1126 if ( !(strcasecmp( pred_node->key,"between" )) )
1127 pred = searchBETWEENPredicate( field, pred_node->item );
1128 else if ( !(strcasecmp( pred_node->key,"in" )) )
1129 pred = searchINPredicate( field, pred_node->item );
1130 else if ( pred_node->item->type == JSON_ARRAY )
1131 pred = searchFunctionPredicate( field, pred_node );
1132 else if ( pred_node->item->type == JSON_HASH )
1133 pred = searchFieldTransformPredicate( field, pred_node );
1135 pred = searchSimplePredicate( pred_node->key, field, pred_node->item );
1139 } else if (node->type == JSON_NULL) { // IS NULL search
1140 growing_buffer* _p = buffer_init(16);
1144 osrfHashGet(field, "name")
1146 pred = buffer_data(_p);
1148 } else { // equality search
1149 pred = searchSimplePredicate( "=", field, node );
1156 jsonObject* doSearch(osrfMethodContext* ctx, osrfHash* meta, jsonObject* params, int* err ) {
1159 dbhandle = writehandle;
1161 osrfHash* links = osrfHashGet(meta, "links");
1162 osrfHash* fields = osrfHashGet(meta, "fields");
1163 char* core_class = osrfHashGet(meta, "classname");
1165 jsonObjectNode* node = NULL;
1166 jsonObjectNode* snode = NULL;
1169 jsonObject* search_hash = jsonObjectGetIndex(params, 0);
1170 jsonObject* order_hash = jsonObjectGetIndex(params, 1);
1172 growing_buffer* sql_buf = buffer_init(128);
1173 buffer_add(sql_buf, "SELECT");
1176 if ( (_tmp = jsonObjectGetKey( order_hash, "select" )) ) {
1178 jsonObjectIterator* class_itr = jsonNewObjectIterator( _tmp );
1179 while ( (snode = jsonObjectIteratorNext( class_itr )) ) {
1181 osrfHash* idlClass = osrfHashGet( idl, snode->key );
1182 if (!idlClass) continue;
1183 char* cname = osrfHashGet(idlClass, "classname");
1185 jsonObjectIterator* select_itr = jsonNewObjectIterator( snode->item );
1186 while ( (node = jsonObjectIteratorNext( select_itr )) ) {
1187 osrfHash* field = osrfHashGet( osrfHashGet( idlClass, "fields" ), jsonObjectToSimpleString(node->item) );
1188 char* fname = osrfHashGet(field, "name");
1190 if (!field) continue;
1195 buffer_add(sql_buf, ",");
1198 buffer_fadd(sql_buf, " \"%s\".%s", cname, fname, cname, fname);
1202 buffer_add(sql_buf, " *");
1205 buffer_fadd(sql_buf, " FROM %s AS \"%s\" WHERE ", osrfHashGet(meta, "tablename"), core_class );
1210 jsonObjectIterator* search_itr = jsonNewObjectIterator( search_hash );
1211 while ( (node = jsonObjectIteratorNext( search_itr )) ) {
1212 osrfHash* field = osrfHashGet( fields, node->key );
1214 if (!field) continue;
1219 buffer_add(sql_buf, " AND ");
1222 pred = searchPredicate( field, node->item);
1223 buffer_fadd( sql_buf, "%s", pred );
1227 jsonObjectIteratorFree(search_itr);
1231 if ( (_tmp = jsonObjectGetKey( jsonObjectGetKey( order_hash, "order_by" ), core_class ) ) ){
1232 string = jsonObjectToSimpleString(_tmp);
1241 if ( (_tmp = jsonObjectGetKey( order_hash, "limit" )) ){
1242 string = jsonObjectToSimpleString(_tmp);
1251 _tmp = jsonObjectGetKey( order_hash, "offset" );
1253 string = jsonObjectToSimpleString(_tmp);
1263 buffer_add(sql_buf, ";");
1265 char* sql = buffer_data(sql_buf);
1266 buffer_free(sql_buf);
1268 osrfLogDebug(OSRF_LOG_MARK, "%s SQL = %s", MODULENAME, sql);
1269 dbi_result result = dbi_conn_query(dbhandle, sql);
1271 jsonObject* res_list = jsonParseString("[]");
1273 osrfLogDebug(OSRF_LOG_MARK, "Query returned with no errors");
1275 if (dbi_result_first_row(result)) {
1276 /* JSONify the result */
1277 osrfLogDebug(OSRF_LOG_MARK, "Query returned at least one row");
1279 obj = oilsMakeJSONFromResult( result, meta );
1280 jsonObjectPush(res_list, obj);
1281 } while (dbi_result_next_row(result));
1283 osrfLogDebug(OSRF_LOG_MARK, "%s returned no results for query %s", MODULENAME, sql);
1286 /* clean up the query */
1287 dbi_result_free(result);
1290 osrfLogError(OSRF_LOG_MARK, "%s: Error retrieving %s with query [%s]", MODULENAME, osrfHashGet(meta, "fieldmapper"), sql);
1291 osrfAppSessionStatus(
1293 OSRF_STATUS_INTERNALSERVERERROR,
1294 "osrfMethodException",
1296 "Severe query error -- see error log for more details"
1300 jsonObjectFree(res_list);
1307 if (res_list->size && order_hash) {
1308 _tmp = jsonObjectGetKey( order_hash, "flesh" );
1310 int x = (int)jsonObjectGetNumber(_tmp);
1312 jsonObject* flesh_blob = NULL;
1313 if ((flesh_blob = jsonObjectGetKey( order_hash, "flesh_fields" )) && x > 0) {
1315 flesh_blob = jsonObjectClone( flesh_blob );
1316 jsonObject* flesh_fields = jsonObjectGetKey( flesh_blob, core_class );
1318 osrfStringArray* link_fields = NULL;
1321 if (flesh_fields->size == 1) {
1322 char* _t = jsonObjectToSimpleString( jsonObjectGetIndex( flesh_fields, 0 ) );
1323 if (!strcmp(_t,"*")) link_fields = osrfHashKeys( links );
1329 link_fields = osrfNewStringArray(1);
1330 jsonObjectIterator* _i = jsonNewObjectIterator( flesh_fields );
1331 while ((_f = jsonObjectIteratorNext( _i ))) {
1332 osrfStringArrayAdd( link_fields, jsonObjectToSimpleString( _f->item ) );
1337 jsonObjectNode* cur;
1338 jsonObjectIterator* itr = jsonNewObjectIterator( res_list );
1339 while ((cur = jsonObjectIteratorNext( itr ))) {
1344 while ( (link_field = osrfStringArrayGetString(link_fields, i++)) ) {
1346 osrfLogDebug(OSRF_LOG_MARK, "Starting to flesh %s", link_field);
1348 osrfHash* kid_link = osrfHashGet(links, link_field);
1349 if (!kid_link) continue;
1351 osrfHash* field = osrfHashGet(fields, link_field);
1352 if (!field) continue;
1354 osrfHash* value_field = field;
1356 osrfHash* kid_idl = osrfHashGet(idl, osrfHashGet(kid_link, "class"));
1357 if (!kid_idl) continue;
1359 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
1360 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
1363 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "might_have" ))) { // might_have
1364 value_field = osrfHashGet( fields, osrfHashGet(meta, "primarykey") );
1367 osrfStringArray* link_map = osrfHashGet( kid_link, "map" );
1369 if (link_map->size > 0) {
1370 jsonObject* _kid_key = jsonParseString("[]");
1373 jsonNewObject( osrfStringArrayGetString( link_map, 0 ) )
1378 osrfHashGet(kid_link, "class"),
1385 "Link field: %s, remote class: %s, fkey: %s, reltype: %s",
1386 osrfHashGet(kid_link, "field"),
1387 osrfHashGet(kid_link, "class"),
1388 osrfHashGet(kid_link, "key"),
1389 osrfHashGet(kid_link, "reltype")
1392 jsonObject* fake_params = jsonParseString("[]");
1393 jsonObjectPush(fake_params, jsonParseString("{}")); // search hash
1394 jsonObjectPush(fake_params, jsonParseString("{}")); // order/flesh hash
1396 osrfLogDebug(OSRF_LOG_MARK, "Creating dummy params object...");
1399 jsonObjectToSimpleString(
1402 atoi( osrfHashGet(value_field, "array_position") )
1407 osrfLogDebug(OSRF_LOG_MARK, "Nothing to search for!");
1412 jsonObjectGetIndex(fake_params, 0),
1413 osrfHashGet(kid_link, "key"),
1414 jsonNewObject( search_key )
1421 jsonObjectGetIndex(fake_params, 1),
1423 jsonNewNumberObject( (double)(x - 1 + link_map->size) )
1427 jsonObjectSetKey( jsonObjectGetIndex(fake_params, 1), "flesh_fields", jsonObjectClone(flesh_blob) );
1429 if (jsonObjectGetKey(order_hash, "order_by")) {
1431 jsonObjectGetIndex(fake_params, 1),
1433 jsonObjectClone(jsonObjectGetKey(order_hash, "order_by"))
1437 jsonObject* kids = doSearch(ctx, kid_idl, fake_params, err);
1440 jsonObjectFree( fake_params );
1441 osrfStringArrayFree(link_fields);
1442 jsonObjectIteratorFree(itr);
1443 jsonObjectFree(res_list);
1447 osrfLogDebug(OSRF_LOG_MARK, "Search for %s return %d linked objects", osrfHashGet(kid_link, "class"), kids->size);
1449 jsonObject* X = NULL;
1450 if ( link_map->size > 0 && kids->size > 0 ) {
1452 kids = jsonParseString("[]");
1454 jsonObjectNode* _k_node;
1455 jsonObjectIterator* _k = jsonNewObjectIterator( X );
1456 while ((_k_node = jsonObjectIteratorNext( _k ))) {
1462 (unsigned long)atoi(
1468 osrfHashGet(kid_link, "class")
1472 osrfStringArrayGetString( link_map, 0 )
1483 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_a" ))) {
1484 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
1487 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
1488 jsonObjectClone( jsonObjectGetIndex(kids, 0) )
1492 if (!(strcmp( osrfHashGet(kid_link, "reltype"), "has_many" ))) { // has_many
1493 osrfLogDebug(OSRF_LOG_MARK, "Storing fleshed objects in %s", osrfHashGet(kid_link, "field"));
1496 (unsigned long)atoi( osrfHashGet( field, "array_position" ) ),
1497 jsonObjectClone( kids )
1502 jsonObjectFree(kids);
1506 jsonObjectFree( kids );
1507 jsonObjectFree( fake_params );
1509 osrfLogDebug(OSRF_LOG_MARK, "Fleshing of %s complete", osrfHashGet(kid_link, "field"));
1510 osrfLogDebug(OSRF_LOG_MARK, "%s", jsonObjectToJSON(cur->item));
1514 jsonObjectFree( flesh_blob );
1515 osrfStringArrayFree(link_fields);
1516 jsonObjectIteratorFree(itr);
1525 jsonObject* doUpdate(osrfMethodContext* ctx, int* err ) {
1527 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1528 jsonObject* target = jsonObjectGetIndex(ctx->params, 0);
1530 if (!verifyObjectClass(ctx, target)) {
1535 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
1536 osrfAppSessionStatus(
1538 OSRF_STATUS_BADREQUEST,
1539 "osrfMethodException",
1541 "No active transaction -- required for UPDATE"
1547 dbhandle = writehandle;
1549 char* pkey = osrfHashGet(meta, "primarykey");
1550 osrfHash* fields = osrfHashGet(meta, "fields");
1553 jsonObjectToSimpleString(
1556 atoi( osrfHashGet( osrfHashGet( fields, pkey ), "array_position" ) )
1562 "%s updating %s object with %s = %s",
1564 osrfHashGet(meta, "fieldmapper"),
1569 growing_buffer* sql = buffer_init(128);
1570 buffer_fadd(sql,"UPDATE %s SET", osrfHashGet(meta, "tablename"));
1575 osrfStringArray* field_list = osrfHashKeys( fields );
1576 while ( (field_name = osrfStringArrayGetString(field_list, i++)) ) {
1578 osrfHash* field = osrfHashGet( fields, field_name );
1580 if(!( strcmp( field_name, pkey ) )) continue;
1581 if(!( strcmp( osrfHashGet(osrfHashGet(fields,field_name), "virtual"), "true" ) )) continue;
1583 int pos = atoi(osrfHashGet(field, "array_position"));
1584 char* value = jsonObjectToSimpleString( jsonObjectGetIndex( target, pos ) );
1586 osrfLogDebug( OSRF_LOG_MARK, "Updating %s object with %s = %s", osrfHashGet(meta, "fieldmapper"), field_name, value);
1588 if (jsonObjectGetIndex(target, pos)->type == JSON_NULL) {
1589 if ( !(!( strcmp( osrfHashGet(meta, "classname"), "au" ) ) && !( strcmp( field_name, "passwd" ) )) ) { // arg at the special case!
1590 if (first) first = 0;
1591 else buffer_add(sql, ",");
1592 buffer_fadd( sql, " %s = NULL", field_name );
1595 } else if ( !strcmp(osrfHashGet(field, "primitive"), "number") ) {
1596 if (first) first = 0;
1597 else buffer_add(sql, ",");
1599 if ( !strncmp(osrfHashGet(field, "datatype"), "INT", (size_t)3) ) {
1600 buffer_fadd( sql, " %s = %ld", field_name, atol(value) );
1601 } else if ( !strcmp(osrfHashGet(field, "datatype"), "NUMERIC") ) {
1602 buffer_fadd( sql, " %s = %f", field_name, atof(value) );
1605 osrfLogDebug( OSRF_LOG_MARK, "%s is of type %s", field_name, osrfHashGet(field, "datatype"));
1608 if ( dbi_conn_quote_string(dbhandle, &value) ) {
1609 if (first) first = 0;
1610 else buffer_add(sql, ",");
1611 buffer_fadd( sql, " %s = %s", field_name, value );
1614 osrfLogError(OSRF_LOG_MARK, "%s: Error quoting string [%s]", MODULENAME, value);
1615 osrfAppSessionStatus(
1617 OSRF_STATUS_INTERNALSERVERERROR,
1618 "osrfMethodException",
1620 "Error quoting string -- please see the error log for more details"
1634 jsonObject* obj = jsonParseString(id);
1636 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
1637 dbi_conn_quote_string(dbhandle, &id);
1639 buffer_fadd( sql, " WHERE %s = %s;", pkey, id );
1641 char* query = buffer_data(sql);
1644 osrfLogDebug(OSRF_LOG_MARK, "%s: Update SQL [%s]", MODULENAME, query);
1646 dbi_result result = dbi_conn_query(dbhandle, query);
1650 jsonObjectFree(obj);
1651 obj = jsonNewObject(NULL);
1654 "%s ERROR updating %s object with %s = %s",
1656 osrfHashGet(meta, "fieldmapper"),
1667 jsonObject* doDelete(osrfMethodContext* ctx, int* err ) {
1669 osrfHash* meta = osrfHashGet( (osrfHash*) ctx->method->userData, "class" );
1671 if (!osrfHashGet( (osrfHash*)ctx->session->userData, "xact_id" )) {
1672 osrfAppSessionStatus(
1674 OSRF_STATUS_BADREQUEST,
1675 "osrfMethodException",
1677 "No active transaction -- required for DELETE"
1683 dbhandle = writehandle;
1687 char* pkey = osrfHashGet(meta, "primarykey");
1690 if (jsonObjectGetIndex(ctx->params, 0)->classname) {
1691 if (!verifyObjectClass(ctx, jsonObjectGetIndex( ctx->params, 0 ))) {
1696 id = jsonObjectToSimpleString(
1698 jsonObjectGetIndex(ctx->params, 0),
1699 atoi( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "array_position") )
1703 id = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0));
1708 "%s deleting %s object with %s = %s",
1710 osrfHashGet(meta, "fieldmapper"),
1715 obj = jsonParseString(id);
1717 if ( strcmp( osrfHashGet( osrfHashGet( osrfHashGet(meta, "fields"), pkey ), "primitive" ), "number" ) )
1718 dbi_conn_quote_string(writehandle, &id);
1720 dbi_result result = dbi_conn_queryf(writehandle, "DELETE FROM %s WHERE %s = %s;", osrfHashGet(meta, "tablename"), pkey, id);
1723 jsonObjectFree(obj);
1724 obj = jsonNewObject(NULL);
1727 "%s ERROR deleting %s object with %s = %s",
1729 osrfHashGet(meta, "fieldmapper"),
1742 jsonObject* oilsMakeJSONFromResult( dbi_result result, osrfHash* meta) {
1743 if(!(result && meta)) return jsonNULL;
1745 jsonObject* object = jsonParseString("[]");
1746 jsonObjectSetClass(object, osrfHashGet(meta, "classname"));
1748 osrfHash* fields = osrfHashGet(meta, "fields");
1750 osrfLogDebug(OSRF_LOG_MARK, "Setting object class to %s ", object->classname);
1754 char dt_string[256];
1758 int columnIndex = 1;
1760 unsigned short type;
1761 const char* columnName;
1763 /* cycle through the column list */
1764 while( (columnName = dbi_result_get_field_name(result, columnIndex++)) ) {
1766 osrfLogDebug(OSRF_LOG_MARK, "Looking for column named [%s]...", (char*)columnName);
1768 fmIndex = -1; // reset the position
1770 /* determine the field type and storage attributes */
1771 type = dbi_result_get_field_type(result, columnName);
1772 attr = dbi_result_get_field_attribs(result, columnName);
1774 /* fetch the fieldmapper index */
1775 if( (_f = osrfHashGet(fields, (char*)columnName)) ) {
1776 char* virt = (char*)osrfHashGet(_f, "virtual");
1777 char* pos = (char*)osrfHashGet(_f, "array_position");
1779 if ( !virt || !pos || !(strcmp( virt, "true" )) ) continue;
1781 fmIndex = atoi( pos );
1782 osrfLogDebug(OSRF_LOG_MARK, "... Found column at position [%s]...", pos);
1787 if (dbi_result_field_is_null(result, columnName)) {
1788 jsonObjectSetIndex( object, fmIndex, jsonNewObject(NULL) );
1793 case DBI_TYPE_INTEGER :
1795 if( attr & DBI_INTEGER_SIZE8 )
1796 jsonObjectSetIndex( object, fmIndex,
1797 jsonNewNumberObject(dbi_result_get_longlong(result, columnName)));
1799 jsonObjectSetIndex( object, fmIndex,
1800 jsonNewNumberObject(dbi_result_get_long(result, columnName)));
1804 case DBI_TYPE_DECIMAL :
1805 jsonObjectSetIndex( object, fmIndex,
1806 jsonNewNumberObject(dbi_result_get_double(result, columnName)));
1809 case DBI_TYPE_STRING :
1815 jsonNewObject( dbi_result_get_string(result, columnName) )
1820 case DBI_TYPE_DATETIME :
1822 memset(dt_string, '\0', 256);
1823 memset(&gmdt, '\0', sizeof(gmdt));
1824 memset(&_tmp_dt, '\0', sizeof(_tmp_dt));
1826 _tmp_dt = dbi_result_get_datetime(result, columnName);
1828 localtime_r( &_tmp_dt, &gmdt );
1830 if (!(attr & DBI_DATETIME_DATE)) {
1831 strftime(dt_string, 255, "%T", &gmdt);
1832 } else if (!(attr & DBI_DATETIME_TIME)) {
1833 strftime(dt_string, 255, "%F", &gmdt);
1835 strftime(dt_string, 255, "%FT%T%z", &gmdt);
1838 jsonObjectSetIndex( object, fmIndex, jsonNewObject(dt_string) );
1842 case DBI_TYPE_BINARY :
1843 osrfLogError( OSRF_LOG_MARK,
1844 "Can't do binary at column %s : index %d", columnName, columnIndex - 1);