void get_bd(http_request_t req, socket_t * clientSocket,db_t * db) { char text[20]; strcpy(text,req.uri+4); int count= db_count(db,text); char buf[10000]; char tmp[1000]; sqlite3_stmt * stmt = NULL; strcpy(buf,"<html>" "<head>" "<title>Page Title</title>" "</head>" "<body>" "<table border=\"3\" align=\"center\">" "<tr>" "<th>NAME</th>" "<th>SURNAME</th>" "<th>AGE</th>" "</tr>"); for(int i=0;i<count;i++) { stmt=db_getrow(db,text,i); sprintf(tmp,"<tr>" "<th><a href=\"/db/%s/%i\">%s</a></th>" "<th><a href=\"/db/%s/%i\">%s</a></th>" "<th><a href=\"/db/%s/%i\">%i</a></a></th>" "</tr>",text,i,sqlite3_column_text(stmt, 0),text,i,sqlite3_column_text(stmt, 1),text,i,sqlite3_column_int(stmt, 2)); strcat(buf,tmp); sqlite3_finalize(stmt); } strcat(buf,"</table>"); sprintf(tmp,"<p align=\"center\">Count: %i<br><br><br></p>" "<p align=\"center\"><a href=\"/db/paste/%s\">Insert new row</a></p>" "<p align=\"center\"><a href=\"/db\">To Databases</a></p>",count,text); strcat(buf,tmp); strcat(buf, "</body>" "</html>"); socket_write_string(clientSocket,buf); }
/* ** Try to figure out how every page in the database file is being used. */ static void page_usage_report(const char *zDbName){ int i, j; int rc; sqlite3 *db; sqlite3_stmt *pStmt; unsigned char *a; char zQuery[200]; /* Avoid the pathological case */ if( mxPage<1 ){ printf("empty database\n"); return; } /* Open the database file */ rc = sqlite3_open(zDbName, &db); if( rc ){ printf("cannot open database: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); return; } /* Set up global variables zPageUse[] and mxPage to record page ** usages */ zPageUse = sqlite3_malloc( sizeof(zPageUse[0])*(mxPage+1) ); if( zPageUse==0 ) out_of_memory(); memset(zPageUse, 0, sizeof(zPageUse[0])*(mxPage+1)); /* Discover the usage of each page */ a = getContent(0, 100); page_usage_freelist(decodeInt32(a+32)); page_usage_ptrmap(a); free(a); page_usage_btree(1, 0, 0, "sqlite_master"); sqlite3_exec(db, "PRAGMA writable_schema=ON", 0, 0, 0); for(j=0; j<2; j++){ sqlite3_snprintf(sizeof(zQuery), zQuery, "SELECT type, name, rootpage FROM SQLITE_MASTER WHERE rootpage" " ORDER BY rowid %s", j?"DESC":""); rc = sqlite3_prepare_v2(db, zQuery, -1, &pStmt, 0); if( rc==SQLITE_OK ){ while( sqlite3_step(pStmt)==SQLITE_ROW ){ int pgno = sqlite3_column_int(pStmt, 2); page_usage_btree(pgno, 0, 0, (const char*)sqlite3_column_text(pStmt,1)); } }else{ printf("ERROR: cannot query database: %s\n", sqlite3_errmsg(db)); } rc = sqlite3_finalize(pStmt); if( rc==SQLITE_OK ) break; } sqlite3_close(db); /* Print the report and free memory used */ for(i=1; i<=mxPage; i++){ printf("%5d: %s\n", i, zPageUse[i] ? zPageUse[i] : "???"); sqlite3_free(zPageUse[i]); } sqlite3_free(zPageUse); zPageUse = 0; }
int query::rows::get(int idx, int) const { return sqlite3_column_int(stmt_, idx); }
inline int32_t SQLite3StatementGetInt32WithColumn(SQLite3StatementRef statement, CFIndex index) { return (int32_t)sqlite3_column_int(statement->stmt, (int)index); }
void parse_from_db(list_t* list,db_t* db) { sqlite3_stmt * stmt=NULL; lanser * lan=Freelanser_new(); for(int i=0; i<db_count(db,"database"); i++) { lanser * lan=Freelanser_new(); stmt=db_getrow(db,"database",i); Freelanser_set(lan,sqlite3_column_text(stmt, 0),sqlite3_column_text(stmt, 1),sqlite3_column_double(stmt, 2),sqlite3_column_text(stmt, 4),sqlite3_column_int(stmt, 3)); list_push(list,lan,get_size()); free(lan); } Freelanser_free(lan); }
/* init_db -- * Prepare the database. Register the compress/uncompress functions and the * stopword tokenizer. * db_flag specifies the mode in which to open the database. 3 options are * available: * 1. DB_READONLY: Open in READONLY mode. An error if db does not exist. * 2. DB_READWRITE: Open in read-write mode. An error if db does not exist. * 3. DB_CREATE: Open in read-write mode. It will try to create the db if * it does not exist already. * RETURN VALUES: * The function will return NULL in case the db does not exist * and DB_CREATE * was not specified. And in case DB_CREATE was specified and yet NULL is * returned, then there was some other error. * In normal cases the function should return a handle to the db. */ sqlite3 * init_db(mandb_access_mode db_flag, const char *manconf) { sqlite3 *db = NULL; sqlite3_stmt *stmt; struct stat sb; int rc; int create_db_flag = 0; char *dbpath = get_dbpath(manconf); if (dbpath == NULL) errx(EXIT_FAILURE, "_mandb entry not found in man.conf"); if (!(stat(dbpath, &sb) == 0 && S_ISREG(sb.st_mode))) { /* Database does not exist, check if DB_CREATE was specified, * and set flag to create the database schema */ if (db_flag != (MANDB_CREATE)) { warnx("Missing apropos database. " "Please run makemandb to create it."); return NULL; } create_db_flag = 1; } else { /* * Database exists. Check if we have the permissions * to read/write the files */ int access_mode = R_OK; switch (db_flag) { case MANDB_CREATE: case MANDB_WRITE: access_mode |= W_OK; break; default: break; } if ((access(dbpath, access_mode)) != 0) { warnx("Unable to access the database, please check" " permissions for `%s'", dbpath); return NULL; } } sqlite3_initialize(); rc = sqlite3_open_v2(dbpath, &db, db_flag, NULL); if (rc != SQLITE_OK) { warnx("%s", sqlite3_errmsg(db)); goto error; } if (create_db_flag && create_db(db) < 0) { warnx("%s", "Unable to create database schema"); goto error; } rc = sqlite3_prepare_v2(db, "PRAGMA user_version", -1, &stmt, NULL); if (rc != SQLITE_OK) { warnx("Unable to query schema version: %s", sqlite3_errmsg(db)); goto error; } if (sqlite3_step(stmt) != SQLITE_ROW) { sqlite3_finalize(stmt); warnx("Unable to query schema version: %s", sqlite3_errmsg(db)); goto error; } if (sqlite3_column_int(stmt, 0) != APROPOS_SCHEMA_VERSION) { sqlite3_finalize(stmt); warnx("Incorrect schema version found. " "Please run makemandb -f."); goto error; } sqlite3_finalize(stmt); sqlite3_extended_result_codes(db, 1); /* Register the zip and unzip functions for FTS compression */ rc = sqlite3_create_function(db, "zip", 1, SQLITE_ANY, NULL, zip, NULL, NULL); if (rc != SQLITE_OK) { warnx("Unable to register function: compress: %s", sqlite3_errmsg(db)); goto error; } rc = sqlite3_create_function(db, "unzip", 1, SQLITE_ANY, NULL, unzip, NULL, NULL); if (rc != SQLITE_OK) { warnx("Unable to register function: uncompress: %s", sqlite3_errmsg(db)); goto error; } return db; error: close_db(db); return NULL; }
static gboolean changed_callback (GtkEntry *entry, dt_lib_collect_rule_t *dr) { // update related list dt_lib_collect_t *d = get_collect(dr); sqlite3_stmt *stmt; GtkTreeIter iter; GtkTreeView *view = d->view; GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(view)); g_object_ref(model); gtk_tree_view_set_model(GTK_TREE_VIEW(view), NULL); gtk_list_store_clear(GTK_LIST_STORE(model)); char query[1024]; int property = gtk_combo_box_get_active(dr->combo); const gchar *text = gtk_entry_get_text(GTK_ENTRY(dr->text)); gchar *escaped_text = dt_util_str_replace(text, "'", "''"); char confname[200]; snprintf(confname, 200, "plugins/lighttable/collect/string%1ld", dr->num); dt_conf_set_string (confname, text); snprintf(confname, 200, "plugins/lighttable/collect/item%1ld", dr->num); dt_conf_set_int (confname, property); switch(property) { case 0: // film roll snprintf(query, 1024, "select distinct folder, id from film_rolls where folder like '%%%s%%' order by folder desc", escaped_text); break; case 1: // camera snprintf(query, 1024, "select distinct maker || ' ' || model as model, 1 from images where maker || ' ' || model like '%%%s%%' order by model", escaped_text); break; case 2: // tag snprintf(query, 1024, "SELECT distinct name, id FROM tags WHERE name LIKE '%%%s%%' ORDER BY UPPER(name)", escaped_text); break; case 4: // History, 2 hardcoded alternatives gtk_list_store_append(GTK_LIST_STORE(model), &iter); gtk_list_store_set (GTK_LIST_STORE(model), &iter, DT_LIB_COLLECT_COL_TEXT,_("altered"), DT_LIB_COLLECT_COL_ID, 0, DT_LIB_COLLECT_COL_TOOLTIP,_("altered"), -1); gtk_list_store_append(GTK_LIST_STORE(model), &iter); gtk_list_store_set (GTK_LIST_STORE(model), &iter, DT_LIB_COLLECT_COL_TEXT,_("not altered"), DT_LIB_COLLECT_COL_ID, 1, DT_LIB_COLLECT_COL_TOOLTIP,_("not altered"), -1); goto entry_key_press_exit; break; case 5: // colorlabels gtk_list_store_append(GTK_LIST_STORE(model), &iter); gtk_list_store_set (GTK_LIST_STORE(model), &iter, DT_LIB_COLLECT_COL_TEXT,_("red"), DT_LIB_COLLECT_COL_ID, 0, DT_LIB_COLLECT_COL_TOOLTIP, _("red"), -1); gtk_list_store_append(GTK_LIST_STORE(model), &iter); gtk_list_store_set (GTK_LIST_STORE(model), &iter, DT_LIB_COLLECT_COL_TEXT,_("yellow"), DT_LIB_COLLECT_COL_ID, 1, DT_LIB_COLLECT_COL_TOOLTIP, _("yellow"), -1); gtk_list_store_append(GTK_LIST_STORE(model), &iter); gtk_list_store_set (GTK_LIST_STORE(model), &iter, DT_LIB_COLLECT_COL_TEXT,_("green"), DT_LIB_COLLECT_COL_ID, 2, DT_LIB_COLLECT_COL_TOOLTIP, _("green"), -1); gtk_list_store_append(GTK_LIST_STORE(model), &iter); gtk_list_store_set (GTK_LIST_STORE(model), &iter, DT_LIB_COLLECT_COL_TEXT,_("blue"), DT_LIB_COLLECT_COL_ID, 3, DT_LIB_COLLECT_COL_TOOLTIP, _("blue"), -1); gtk_list_store_append(GTK_LIST_STORE(model), &iter); gtk_list_store_set (GTK_LIST_STORE(model), &iter, DT_LIB_COLLECT_COL_TEXT,_("purple"), DT_LIB_COLLECT_COL_ID, 4, DT_LIB_COLLECT_COL_TOOLTIP, _("purple"), -1); goto entry_key_press_exit; break; // TODO: Add empty string for metadata? // TODO: Autogenerate this code? case 6: // title snprintf(query, 1024, "select distinct value, 1 from meta_data where key = %d and value like '%%%s%%' order by value", DT_METADATA_XMP_DC_TITLE, escaped_text); break; case 7: // description snprintf(query, 1024, "select distinct value, 1 from meta_data where key = %d and value like '%%%s%%' order by value", DT_METADATA_XMP_DC_DESCRIPTION, escaped_text); break; case 8: // creator snprintf(query, 1024, "select distinct value, 1 from meta_data where key = %d and value like '%%%s%%' order by value", DT_METADATA_XMP_DC_CREATOR, escaped_text); break; case 9: // publisher snprintf(query, 1024, "select distinct value, 1 from meta_data where key = %d and value like '%%%s%%' order by value", DT_METADATA_XMP_DC_PUBLISHER, escaped_text); break; case 10: // rights snprintf(query, 1024, "select distinct value, 1 from meta_data where key = %d and value like '%%%s%%'order by value ", DT_METADATA_XMP_DC_RIGHTS, escaped_text); break; case 11: // lens snprintf(query, 1024, "select distinct lens, 1 from images where lens like '%%%s%%' order by lens", escaped_text); break; case 12: // iso snprintf(query, 1024, "select distinct cast(iso as integer) as iso, 1 from images where iso like '%%%s%%' order by iso", escaped_text); break; case 13: // aperature snprintf(query, 1024, "select distinct round(aperture,1) as aperture, 1 from images where aperture like '%%%s%%' order by aperture", escaped_text); break; case 14: // filename snprintf(query, 1024, "select distinct filename, 1 from images where filename like '%%%s%%' order by filename", escaped_text); break; default: // case 3: // day snprintf(query, 1024, "SELECT DISTINCT datetime_taken, 1 FROM images WHERE datetime_taken LIKE '%%%s%%' ORDER BY datetime_taken DESC", escaped_text); break; } g_free(escaped_text); DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), query, -1, &stmt, NULL); while(sqlite3_step(stmt) == SQLITE_ROW) { gtk_list_store_append(GTK_LIST_STORE(model), &iter); const char *folder = (const char*)sqlite3_column_text(stmt, 0); if(property == 0) // film roll { folder = dt_image_film_roll_name(folder); } gchar *value = (gchar *)sqlite3_column_text(stmt, 0); gchar *escaped_text = g_markup_escape_text(value, strlen(value)); gtk_list_store_set (GTK_LIST_STORE(model), &iter, DT_LIB_COLLECT_COL_TEXT, folder, DT_LIB_COLLECT_COL_ID, sqlite3_column_int(stmt, 1), DT_LIB_COLLECT_COL_TOOLTIP, escaped_text, DT_LIB_COLLECT_COL_PATH, value, -1); } sqlite3_finalize(stmt); entry_key_press_exit: gtk_tree_view_set_tooltip_column(GTK_TREE_VIEW(view), DT_LIB_COLLECT_COL_TOOLTIP); gtk_tree_view_set_model(GTK_TREE_VIEW(view), model); g_object_unref(model); return FALSE; }
static void delete_button_clicked(GtkButton *button, gpointer user_data) { dt_lib_module_t *self = (dt_lib_module_t *)user_data; dt_lib_tagging_t *d = (dt_lib_tagging_t *)self->data; int res = GTK_RESPONSE_YES; guint tagid; GtkTreeIter iter; GtkTreeModel *model = NULL; GtkTreeView *view = d->related; GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(view)); if(!gtk_tree_selection_get_selected(selection, &model, &iter)) return; gtk_tree_model_get(model, &iter, DT_LIB_TAGGING_COL_ID, &tagid, -1); // First check how many images are affected by the remove int count = dt_tag_remove(tagid, FALSE); if(count > 0 && dt_conf_get_bool("plugins/lighttable/tagging/ask_before_delete_tag")) { GtkWidget *dialog; GtkWidget *win = dt_ui_main_window(darktable.gui->ui); gchar *tagname = dt_tag_get_name(tagid); dialog = gtk_message_dialog_new( GTK_WINDOW(win), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_QUESTION, GTK_BUTTONS_YES_NO, ngettext("do you really want to delete the tag `%s'?\n%d image is assigned this tag!", "do you really want to delete the tag `%s'?\n%d images are assigned this tag!", count), tagname, count); gtk_window_set_title(GTK_WINDOW(dialog), _("delete tag?")); res = gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); free(tagname); } if(res != GTK_RESPONSE_YES) return; GList *tagged_images = NULL; sqlite3_stmt *stmt; DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), "select imgid from tagged_images where tagid=?1", -1, &stmt, NULL); DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, tagid); while(sqlite3_step(stmt) == SQLITE_ROW) { tagged_images = g_list_append(tagged_images, GINT_TO_POINTER(sqlite3_column_int(stmt, 0))); } sqlite3_finalize(stmt); dt_tag_remove(tagid, TRUE); GList *list_iter; if((list_iter = g_list_first(tagged_images)) != NULL) { do { dt_image_synch_xmp(GPOINTER_TO_INT(list_iter->data)); } while((list_iter = g_list_next(list_iter)) != NULL); } g_list_free(g_list_first(tagged_images)); update(self, 0); update(self, 1); dt_control_signal_raise(darktable.signals, DT_SIGNAL_TAG_CHANGED); }
// Dump array attributes of an object void dump_arrays(sqlite3* db, long long oid) { int rv; unsigned long count; sqlite3_stmt* sqlcnt = NULL; sqlite3_stmt* sqlid = NULL; std::string commandcnt = "select count(id) from attribute_array where object_id=?;"; std::string commandid = "select id from attribute_array where object_id=?;"; rv = sqlite3_prepare_v2(db, commandcnt.c_str(), -1, &sqlcnt, NULL); if (rv != SQLITE_OK) { fprintf(stderr, "can't count the object table: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlcnt); return; } rv = sqlite3_bind_int64(sqlcnt, 1, oid); if (rv != SQLITE_OK) { fprintf(stderr, "can't bind the object id: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlcnt); return; } while ((rv = sqlite3_step(sqlcnt)) == SQLITE_BUSY) { sched_yield(); } if (rv != SQLITE_ROW) { fprintf(stderr, "can't count the object table: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlcnt); return; } count = sqlite3_column_int(sqlcnt, 0); sqlite3_finalize(sqlcnt); if (count == 0) return; printf("%lu array attributes for object %lld\n", count, oid); rv = sqlite3_prepare_v2(db, commandid.c_str(), -1, &sqlid, NULL); if (rv != SQLITE_OK) { fprintf(stderr, "can't count the object table: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlid); return; } rv = sqlite3_bind_int64(sqlid, 1, oid); if (rv != SQLITE_OK) { fprintf(stderr, "can't bind the object id: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlid); return; } while (count-- > 0) { while ((rv = sqlite3_step(sqlid)) == SQLITE_BUSY) { sched_yield(); } if (rv != SQLITE_ROW) { if (rv != SQLITE_DONE) { fprintf(stderr, "can't get next object id: %d(%s)\n", rv, sqlite3_errmsg(db)); } sqlite3_finalize(sqlid); return; } long long id = sqlite3_column_int64(sqlid, 0); uint64_t type; std::vector<Attribute> value; if (!getArray(db, oid, id, type, value)) { return; } dumpULong(type); if ((uint64_t)((uint32_t)type) != type) { printf("overflow attribute type\n"); } else { dumpCKA((unsigned long) type, 48); printf("\n"); } dumpULong((uint64_t) value.size()); printf("(length %lu)\n", (unsigned long) value.size()); dumpArray(value); } }
/**---------------------------------------------------------------------------- * SC_DA_GetDlMapAreaData * ダウンロードエリア データ取得 *-----------------------------------------------------------------------------*/ SC_DA_RESULT SC_DA_LoadDownloadAreaMapData(sqlite3* sqliteObj, UINT8 *kind, T_DAL_DLAREA *downloadArea, UINT8 *dataCnt) { SC_DA_RESULT dal_res = SC_DA_RES_NODATA; INT32 sqlite_res = SQLITE_OK; sqlite3_stmt *stmt; INT32 size = 0; UINT8 resCnt = 0; #ifdef ANDROID __android_log_print(ANDROID_LOG_DEBUG, SC_TAG_DAL, "SC_DA_LoadDownloadAreaMapData() start"); #endif // ANDROID do { if (NULL == kind) { #ifdef ANDROID __android_log_print(ANDROID_LOG_ERROR, SC_TAG_DAL, "SC_DA_LoadDownloadAreaMapData() param err[kind]"); #endif // ANDROID dal_res = SC_DA_RES_BADPARAM; break; } if (NULL == sqliteObj) { #ifdef ANDROID __android_log_print(ANDROID_LOG_ERROR, SC_TAG_DAL, "SC_DA_LoadDownloadAreaMapData() param err[sqliteObj]"); #endif // ANDROID dal_res = SC_DA_RES_BADPARAM; break; } // SQLITE prepare sqlite_res = sqlite3_prepare(sqliteObj, SC_DA_SQL_GET_DL_MAP_AREA_DATA, strlen(SC_DA_SQL_GET_DL_MAP_AREA_DATA), &stmt, NULL); if (SQLITE_OK != sqlite_res) { #ifdef ANDROID __android_log_print(ANDROID_LOG_ERROR, SC_TAG_DAL, "SC_DA_LoadDownloadAreaMapData() sqlite3_prepare err=%d", sqlite_res); #endif // ANDROID dal_res = SC_DA_RES_RDB_ACCESSERR; break; } // stmtの内部バッファを一旦クリア sqlite3_reset(stmt); // sqlの?の部分に、値を設定 sqlite3_bind_text(stmt, 1, kind, strlen(kind), SQLITE_TRANSIENT); // SQLITE step while (SQLITE_ROW == (sqlite_res = sqlite3_step(stmt))) { // 取得データの格納 // ダウンロード管理番号 downloadArea[resCnt].id = sqlite3_column_int(stmt, 0); // データ種別 size = sqlite3_column_bytes(stmt, 1); memcpy(downloadArea[resCnt].kind, (const char *) sqlite3_column_text(stmt, 1), size); downloadArea[resCnt].kind[size]='\0'; // 国識別コード downloadArea[resCnt].countryCode = sqlite3_column_int(stmt, 2); // 表示順 downloadArea[resCnt].displayNum = sqlite3_column_int(stmt, 3); // 国名称 size = sqlite3_column_bytes(stmt, 4); memcpy(downloadArea[resCnt].countryName, (const char *) sqlite3_column_text(stmt, 4), size); downloadArea[resCnt].countryName[size]='\0'; // グループ名称 size = sqlite3_column_bytes(stmt, 5); memcpy(downloadArea[resCnt].areaGroup, (const char *) sqlite3_column_text(stmt, 5), size); downloadArea[resCnt].areaGroup[size]='\0'; // エリア名称 size = sqlite3_column_bytes(stmt, 6); memcpy(downloadArea[resCnt].areaName, (const char *) sqlite3_column_text(stmt, 6), size); downloadArea[resCnt].areaName[size]='\0'; // ダウンロードフラグ downloadArea[resCnt].downloadFlag = sqlite3_column_int(stmt, 7); // ベースバージョン downloadArea[resCnt].baseVersion = sqlite3_column_int(stmt, 8); // 備考 size = sqlite3_column_bytes(stmt, 9); memcpy(downloadArea[resCnt].note, (const char *) sqlite3_column_text(stmt, 9), size); downloadArea[resCnt].note[size]='\0'; resCnt++; dal_res = SC_DA_RES_SUCCESS; } sqlite_res = sqlite3_finalize(stmt); if (SQLITE_OK != sqlite_res) { dal_res = SC_DA_RES_RDB_ACCESSERR; break; } } while (0); if (SC_DA_RES_SUCCESS != dal_res) { #ifdef ANDROID __android_log_print(ANDROID_LOG_ERROR, SC_TAG_DAL, "SC_DA_LoadDownloadAreaMapData() kind(%s) derr(0x%08x) serr(0x%08x) File %s(%d)", kind, dal_res, sqlite_res, __FILE__, __LINE__); #endif // ANDROID } // 件数を設定 *dataCnt = resCnt; #ifdef ANDROID __android_log_print(ANDROID_LOG_DEBUG, SC_TAG_DAL, "SC_DA_LoadDownloadAreaMapData() end"); #endif // ANDROID return (dal_res); }
/* update all values to reflect mouse over image id or no data at all */ static void _metadata_view_update_values(dt_lib_module_t *self) { dt_lib_metadata_view_t *d = (dt_lib_metadata_view_t *)self->data; int32_t mouse_over_id = dt_control_get_mouse_over_id(); if (mouse_over_id == -1) { const dt_view_t *cv = dt_view_manager_get_current_view(darktable.view_manager); if(cv->view((dt_view_t*)cv) == DT_VIEW_DARKROOM) { mouse_over_id = darktable.develop->image_storage.id; } else { sqlite3_stmt *stmt; DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), "select imgid from selected_images limit 1", -1, &stmt, NULL); if(sqlite3_step(stmt) == SQLITE_ROW) mouse_over_id = sqlite3_column_int(stmt, 0); sqlite3_finalize(stmt); } } if(mouse_over_id >= 0) { char value[512]; char pathname[PATH_MAX]; const dt_image_t *img = dt_image_cache_read_get(darktable.image_cache, mouse_over_id); if(!img) goto fill_minuses; if(img->film_id == -1) { dt_image_cache_read_release(darktable.image_cache, img); goto fill_minuses; } /* update all metadata */ dt_image_film_roll(img, value, sizeof(value)); _metadata_update_value(d->metadata[md_internal_filmroll], value); const int tp = 512; char tooltip[tp]; snprintf(tooltip, tp, _("double click to jump to film roll\n%s"), value); g_object_set(G_OBJECT(d->metadata[md_internal_filmroll]), "tooltip-text", tooltip, (char *)NULL); snprintf(value,sizeof(value),"%d", img->id); _metadata_update_value(d->metadata[md_internal_imgid], value); _metadata_update_value(d->metadata[md_internal_filename], img->filename); snprintf(value,sizeof(value),"%d", img->version); _metadata_update_value(d->metadata[md_internal_version], value); gboolean from_cache = FALSE; dt_image_full_path(img->id, pathname, sizeof(pathname), &from_cache); _metadata_update_value(d->metadata[md_internal_fullpath], pathname); snprintf(value, sizeof(value), "%s", (img->flags & DT_IMAGE_LOCAL_COPY)?_("yes"):_("no")); _metadata_update_value(d->metadata[md_internal_local_copy], value); /* EXIF */ _metadata_update_value_end(d->metadata[md_exif_model], img->exif_model); _metadata_update_value_end(d->metadata[md_exif_lens], img->exif_lens); _metadata_update_value_end(d->metadata[md_exif_maker], img->exif_maker); snprintf(value, sizeof(value), "F/%.1f", img->exif_aperture); _metadata_update_value(d->metadata[md_exif_aperture], value); if(img->exif_exposure <= 0.5) snprintf(value, sizeof(value), "1/%.0f", 1.0/img->exif_exposure); else snprintf(value, sizeof(value), "%.1f''", img->exif_exposure); _metadata_update_value(d->metadata[md_exif_exposure], value); snprintf(value, sizeof(value), "%.0f mm", img->exif_focal_length); _metadata_update_value(d->metadata[md_exif_focal_length], value); if (isnan(img->exif_focus_distance) || fpclassify(img->exif_focus_distance) == FP_ZERO) { _metadata_update_value(d->metadata[md_exif_focus_distance], NODATA_STRING); } else { snprintf(value, sizeof(value), "%.2f m", img->exif_focus_distance); _metadata_update_value(d->metadata[md_exif_focus_distance], value); } snprintf(value, sizeof(value), "%.0f", img->exif_iso); _metadata_update_value(d->metadata[md_exif_iso], value); _metadata_update_value(d->metadata[md_exif_datetime], img->exif_datetime_taken); snprintf(value, sizeof(value), "%d", img->height); _metadata_update_value(d->metadata[md_exif_height], value); snprintf(value, sizeof(value), "%d", img->width); _metadata_update_value(d->metadata[md_exif_width], value); /* XMP */ GList *res; if((res = dt_metadata_get(img->id, "Xmp.dc.title", NULL))!=NULL) { snprintf(value, sizeof(value), "%s", (char*)res->data); _filter_non_printable(value, sizeof(value)); g_list_free_full(res, &g_free); } else snprintf(value, sizeof(value), NODATA_STRING); _metadata_update_value(d->metadata[md_xmp_title], value); if((res = dt_metadata_get(img->id, "Xmp.dc.creator", NULL))!=NULL) { snprintf(value, sizeof(value), "%s", (char*)res->data); _filter_non_printable(value, sizeof(value)); g_list_free_full(res, &g_free); } else snprintf(value, sizeof(value), NODATA_STRING); _metadata_update_value(d->metadata[md_xmp_creator], value); if((res = dt_metadata_get(img->id, "Xmp.dc.rights", NULL))!=NULL) { snprintf(value, sizeof(value), "%s", (char*)res->data); _filter_non_printable(value, sizeof(value)); g_list_free_full(res, &g_free); } else snprintf(value, sizeof(value), NODATA_STRING); _metadata_update_value(d->metadata[md_xmp_rights], value); /* geotagging */ /* latitude */ if(isnan(img->latitude)) { _metadata_update_value(d->metadata[md_geotagging_lat], NODATA_STRING); } else { #ifdef HAVE_MAP if(dt_conf_get_bool("plugins/lighttable/metadata_view/pretty_location")) { gchar *latitude = osd_latitude_str(img->latitude); _metadata_update_value(d->metadata[md_geotagging_lat], latitude); g_free(latitude); } else { #endif gchar NS = img->latitude<0?'S':'N'; snprintf(value, sizeof(value), "%c %09.6f", NS, fabs(img->latitude)); _metadata_update_value(d->metadata[md_geotagging_lat], value); #ifdef HAVE_MAP } #endif } /* longitude */ if(isnan(img->longitude)) { _metadata_update_value(d->metadata[md_geotagging_lon], NODATA_STRING); } else { #ifdef HAVE_MAP if(dt_conf_get_bool("plugins/lighttable/metadata_view/pretty_location")) { gchar *longitude = osd_longitude_str(img->longitude); _metadata_update_value(d->metadata[md_geotagging_lon], longitude); g_free(longitude); } else { #endif gchar EW = img->longitude<0?'W':'E'; snprintf(value, sizeof(value), "%c %010.6f", EW, fabs(img->longitude)); _metadata_update_value(d->metadata[md_geotagging_lon], value); #ifdef HAVE_MAP } #endif } /* release img */ dt_image_cache_read_release(darktable.image_cache, img); } return; /* reset */ fill_minuses: for(int k=0; k<md_size; k++) _metadata_update_value(d->metadata[k],NODATA_STRING); }
int Database::Query::getInt(int column) { return _stmt ? sqlite3_column_int(_stmt, column) : 0; }
static bool handle_cmd_records(int fd, struct ircmsg_privmsg *msg, char *head) { // Normalize the nickname to lowercase, because that keeps the database // consistent (as is done in other places). for (char *c = head; *c != '\0'; ++c) { *c = tolower(*c); // Also turn the trailing CR/LF to NUL so we can use the nickname as a // null-terminated string. if (*c == '\r' || *c == '\n') { *c = '\0'; break; } } sqlite3_stmt *stmt; char out[BUF_LEN] = "\0"; char *cur = out; if (sqlite3_prepare(db, TOP_PRS, -1, &stmt, NULL) != SQLITE_OK) { // Something broke. :( irc_privmsg(fd, msg->chan, "%s: sorry, couldn't get PRs (prepare)"); return true; } sqlite3_bind_text(stmt, 1, head, -1, NULL); int retval; do { switch ((retval = sqlite3_step(stmt))) { case SQLITE_DONE: break; case SQLITE_ROW: { // There are 6 columns: // // 0. nick // 1. lift // 2. date // 3. sets // 4. reps // 5. kgs const char *nick = (const char *) sqlite3_column_text(stmt, 0); const char *lift = (const char *) sqlite3_column_text(stmt, 1); long date = (long) sqlite3_column_int64(stmt, 2); int sets = sqlite3_column_int(stmt, 3); int reps = sqlite3_column_int(stmt, 4); double kgs = sqlite3_column_double(stmt, 5); int n = snprintf(cur, BUF_LEN - (int) (cur - out), "| %s of %.2fkg %dx%d ", lift, kgs, sets, reps); if (n < 0) { // TODO: split output over multiple lines, rather than just silencing it goto finalize; } cur += n; break; } default: // Some error occured during PR retrieval. irc_privmsg(fd, msg->chan, "%s: sorry, couldn't get PRs (iterate)"); return true; } } while (retval == SQLITE_ROW); finalize: if (sqlite3_finalize(stmt)) { // Couldn't finalize statement. irc_privmsg(fd, msg->chan, "%s: sorry, couldn't get PRs (finalize)"); return true; } irc_privmsg(fd, msg->chan, "PRs for %s %s", head, out[0] == '\0' ? "| none" : out); return true; }
// TODO: Fix this function _MEMBER_FUNCTION_IMPL(db, query) { char * query; script_getstring(pVM, -1, (const char **)&query); if(query) { CSQLite * pSQLite = script_getinstance<CSQLite *>(pVM); if(!pSQLite) { CLogFile::Print("Failed to get the database instance."); script_pushbool(pVM, false); return 1; } sqlite3 * database = pSQLite->getDatabase(); sqlite3_stmt * stmt; if(sqlite3_prepare(database, query, strlen(query) + 1, &stmt, 0) != SQLITE_OK) { //const char * errmsg = sqlite3_errmsg(database); // TODO: let the user get the error message using a seperate function script_pushbool(pVM, false); //script_pushstring(vm, errmsg, sizeof(errmsg)); return 1; } script_newtable(pVM, 0); int rowCount = 0; //sqlite3_step(stmt); while(sqlite3_step(stmt) == SQLITE_ROW) { rowCount++; int colCount = sqlite3_column_count(stmt); script_pushinteger(pVM, rowCount); script_newtable(pVM, 0); for(int i = 0; i < colCount; i++) { int columnType = sqlite3_column_type(stmt, i); const char * columnName = sqlite3_column_name(stmt, i); script_pushlstring(pVM, columnName, strlen(columnName)); int type = sqlite3_column_type(stmt, i); switch(type) { case SQLITE_NULL: break; case SQLITE_INTEGER: script_pushinteger(pVM, sqlite3_column_int(stmt, i)); break; case SQLITE_FLOAT: script_pushfloat(pVM, (float)sqlite3_column_double(stmt, i)); break; case SQLITE_BLOB: /*int length = sqlite3_column_bytes(stmt, i); if(length > 0) { new unsigned char val[length]; memcpy(val, (const void *)sqlite3_column_blob(stmt, i), length); script_pushstring(vm, val, sizeof(val)); }*/ break; default: /*int length = sqlite3_column_bytes(stmt, i) + 1; new unsigned char val[length]; memcpy(val, sqlite3_column_text(stmt, i), length); script_pushstring(vm, val, sizeof(val));*/ break; } script_tableset(pVM, -3); } script_tableset(pVM, -3); } sqlite3_finalize(stmt); return 1; } script_pushbool(pVM, false); return 1; }
bool Extractor::extract(std::size_t pos, char& val) { if (isNull(pos)) return false; val = sqlite3_column_int(_pStmt, (int) pos); return true; }
int dt_history_copy_and_paste_on_image(int32_t imgid, int32_t dest_imgid, gboolean merge, GList *ops) { sqlite3_stmt *stmt; if(imgid == dest_imgid) return 1; if(imgid == -1) { dt_control_log(_("you need to copy history from an image before you paste it onto another")); return 1; } // be sure the current history is written before pasting some other history data const dt_view_t *cv = dt_view_manager_get_current_view(darktable.view_manager); if(cv->view((dt_view_t *)cv) == DT_VIEW_DARKROOM) dt_dev_write_history(darktable.develop); /* if merge onto history stack, lets find history offest in destination image */ int32_t offs = 0; if(merge) { /* apply on top of history stack */ // first trim the stack to get rid of whatever is above the selected entry DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), "DELETE FROM main.history WHERE imgid = ?1 AND num >= (SELECT history_end " "FROM main.images WHERE id = imgid)", -1, &stmt, NULL); DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, dest_imgid); sqlite3_step(stmt); sqlite3_finalize(stmt); DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), "SELECT IFNULL(MAX(num), -1)+1 FROM main.history WHERE imgid = ?1", -1, &stmt, NULL); DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, dest_imgid); if(sqlite3_step(stmt) == SQLITE_ROW) offs = sqlite3_column_int(stmt, 0); } else { /* replace history stack */ DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), "DELETE FROM main.history WHERE imgid = ?1", -1, &stmt, NULL); DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, dest_imgid); sqlite3_step(stmt); } sqlite3_finalize(stmt); /* delete all items from the temp styles_items, this table is used only to get a ROWNUM of the results */ DT_DEBUG_SQLITE3_EXEC(dt_database_get(darktable.db), "DELETE FROM memory.style_items", NULL, NULL, NULL); /* copy history items from styles onto temp table */ // prepare SQL request char req[2048]; g_strlcpy(req, "INSERT INTO memory.style_items (num, module, operation, op_params, enabled, blendop_params, " "blendop_version, multi_name, multi_priority) SELECT num, module, operation, " "op_params, enabled, blendop_params, blendop_version, multi_name, multi_priority FROM " "main.history WHERE imgid = ?1", sizeof(req)); // Add ops selection if any format: ... and num in (val1, val2) if(ops) { GList *l = ops; int first = 1; g_strlcat(req, " AND num IN (", sizeof(req)); while(l) { unsigned int value = GPOINTER_TO_UINT(l->data); char v[30]; if(!first) g_strlcat(req, ",", sizeof(req)); snprintf(v, sizeof(v), "%u", value); g_strlcat(req, v, sizeof(req)); first = 0; l = g_list_next(l); } g_strlcat(req, ")", sizeof(req)); } DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), req, -1, &stmt, NULL); DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, imgid); sqlite3_step(stmt); sqlite3_finalize(stmt); /* copy the history items into the history of the dest image */ /* note: rowid starts at 1 while num has to start at 0! */ DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), "INSERT INTO main.history " "(imgid,num,module,operation,op_params,enabled,blendop_params,blendop_" "version,multi_priority,multi_name) SELECT " "?1,?2+rowid-1,module,operation,op_params,enabled,blendop_params,blendop_" "version,multi_priority,multi_name FROM memory.style_items", -1, &stmt, NULL); DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, dest_imgid); DT_DEBUG_SQLITE3_BIND_INT(stmt, 2, offs); sqlite3_step(stmt); sqlite3_finalize(stmt); if(merge && ops) _dt_history_cleanup_multi_instance(dest_imgid, offs); // we have to copy masks too // what to do with existing masks ? if(merge) { // there's very little chance that we will have same shapes id. // but we may want to handle this case anyway // and it's not trivial at all ! } else { // let's remove all existing shapes DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), "DELETE FROM main.mask WHERE imgid = ?1", -1, &stmt, NULL); DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, dest_imgid); sqlite3_step(stmt); sqlite3_finalize(stmt); } // let's copy now g_strlcpy(req, "INSERT INTO main.mask (imgid, formid, form, name, version, points, points_count, source) SELECT " "?1, formid, form, name, version, points, points_count, source FROM main.mask WHERE imgid = ?2", sizeof(req)); DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), req, -1, &stmt, NULL); DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, dest_imgid); DT_DEBUG_SQLITE3_BIND_INT(stmt, 2, imgid); sqlite3_step(stmt); sqlite3_finalize(stmt); // always make the whole stack active DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), "UPDATE main.images SET history_end = (SELECT MAX(num) + 1 FROM main.history " "WHERE imgid = ?1) WHERE id = ?1", -1, &stmt, NULL); DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, dest_imgid); sqlite3_step(stmt); sqlite3_finalize(stmt); /* if current image in develop reload history */ if(dt_dev_is_current_image(darktable.develop, dest_imgid)) { dt_dev_reload_history_items(darktable.develop); dt_dev_modulegroups_set(darktable.develop, dt_dev_modulegroups_get(darktable.develop)); } /* update xmp file */ dt_image_synch_xmp(dest_imgid); dt_mipmap_cache_remove(darktable.mipmap_cache, dest_imgid); return 0; }
static void _dt_history_cleanup_multi_instance(int imgid, int minnum) { /* as we let the user decide which history item to copy, we can end with some gaps in multi-instance numbering. for ex., if user decide to not copy the 2nd instance of a module which as 3 instances. let's clean-up the history multi-instance. What we want to do is have a unique multi_priority value for each iop. Furthermore this value must start to 0 and increment one by one for each multi-instance of the same module. On SQLite there is no notion of ROW_NUMBER, so we use rather resource consuming SQL statement, but as an history has never a huge number of items that's not a real issue. We only do this for the given imgid and only for num>minnum, that is we only handle new history items just copied. */ typedef struct _history_item_t { int num; char op[1024]; int mi; int new_mi; } _history_item_t; // we first reload all the newly added history item sqlite3_stmt *stmt; DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), "SELECT num, operation, multi_priority FROM " "main.history WHERE imgid=?1 AND num>=?2 ORDER BY " "operation, multi_priority", -1, &stmt, NULL); DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, imgid); DT_DEBUG_SQLITE3_BIND_INT(stmt, 2, minnum); GList *hitems = NULL; while(sqlite3_step(stmt) == SQLITE_ROW) { const char *op = (const char *)sqlite3_column_text(stmt, 1); GList *modules = darktable.iop; while (modules) { dt_iop_module_so_t *find_op = (dt_iop_module_so_t *)(modules->data); if (!strcmp(find_op->op, op)) { break; } modules = g_list_next(modules); } if (modules && (((dt_iop_module_so_t *)(modules->data))->flags() & IOP_FLAGS_ONE_INSTANCE)) { // the current module is a single-instance one, so there's no point in trying to mess up our multi_priority value continue; } _history_item_t *hi = (_history_item_t *)calloc(1, sizeof(_history_item_t)); hi->num = sqlite3_column_int(stmt, 0); snprintf(hi->op, sizeof(hi->op), "%s", sqlite3_column_text(stmt, 1)); hi->mi = sqlite3_column_int(stmt, 2); hi->new_mi = -5; // means : not changed atm hitems = g_list_append(hitems, hi); } sqlite3_finalize(stmt); // then we change the multi-priority to be sure to have a correct numbering char op[1024] = ""; int c_mi = 0; int nb_change = 0; GList *items = g_list_first(hitems); while(items) { _history_item_t *hi = (_history_item_t *)(items->data); if(strcmp(op, hi->op) != 0) { g_strlcpy(op, hi->op, sizeof(op)); c_mi = 0; } if(hi->mi != c_mi) nb_change++; hi->new_mi = c_mi; c_mi++; items = g_list_next(items); } if(nb_change == 0) { // everything is ok, nothing to change g_list_free_full(hitems, free); return; } // and we update the history items char *req = NULL; req = dt_util_dstrcat(req, "%s", "UPDATE main.history SET multi_priority = CASE num "); items = g_list_first(hitems); while(items) { _history_item_t *hi = (_history_item_t *)(items->data); if(hi->mi != hi->new_mi) { req = dt_util_dstrcat(req, "WHEN %d THEN %d ", hi->num, hi->new_mi); } items = g_list_next(items); } req = dt_util_dstrcat(req, "%s", "else multi_priority end where imgid=?1 and num>=?2"); DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), req, -1, &stmt, NULL); DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, imgid); DT_DEBUG_SQLITE3_BIND_INT(stmt, 2, minnum); sqlite3_step(stmt); sqlite3_finalize(stmt); g_free(req); g_list_free_full(hitems, free); }
CPlaylistItem* CStateDB::getPlaylistItemFromStmt(sqlite3_stmt *pStmt) { unsigned hash = sqlite3_column_int(pStmt, 0); CPlaylistItem* item = new CPlaylistItem( hash ); return item; }
static tb_pointer_t tb_database_sqlite3_result_col_iterator_item(tb_iterator_ref_t iterator, tb_size_t itor) { // check tb_database_sqlite3_result_row_t* row = (tb_database_sqlite3_result_row_t*)iterator; tb_assert_and_check_return_val(row && itor < row->count, tb_null); // the sqlite tb_database_sqlite3_t* sqlite = (tb_database_sqlite3_t*)iterator->priv; tb_assert_and_check_return_val(sqlite, tb_null); // result? if (sqlite->result.result) { // init value tb_database_sql_value_name_set(&row->value, (tb_char_t const*)sqlite->result.result[itor]); tb_database_sql_value_set_text(&row->value, (tb_char_t const*)sqlite->result.result[((1 + sqlite->result.row.row) * row->count) + itor], 0); return (tb_pointer_t)&row->value; } // statement result? else if (sqlite->result.statement) { // init name tb_database_sql_value_name_set(&row->value, sqlite3_column_name(sqlite->result.statement, itor)); // init type tb_size_t type = sqlite3_column_type(sqlite->result.statement, itor); switch (type) { case SQLITE_INTEGER: tb_database_sql_value_set_int32(&row->value, sqlite3_column_int(sqlite->result.statement, itor)); break; case SQLITE_TEXT: tb_database_sql_value_set_text(&row->value, (tb_char_t const*)sqlite3_column_text(sqlite->result.statement, itor), sqlite3_column_bytes(sqlite->result.statement, itor)); break; case SQLITE_FLOAT: #ifdef TB_CONFIG_TYPE_FLOAT tb_database_sql_value_set_double(&row->value, sqlite3_column_double(sqlite->result.statement, itor)); break; #else // trace tb_trace1_e("float type is not supported, at col: %lu, please enable float config!", itor); return tb_null; #endif case SQLITE_BLOB: tb_database_sql_value_set_blob32(&row->value, (tb_byte_t const*)sqlite3_column_blob(sqlite->result.statement, itor), sqlite3_column_bytes(sqlite->result.statement, itor), tb_null); break; case SQLITE_NULL: tb_database_sql_value_set_null(&row->value); break; default: tb_trace_e("unknown field type: %s, at col: %lu", type, itor); return tb_null; } // ok return (tb_pointer_t)&row->value; } // failed tb_assert(0); return tb_null; }
/* * Executes SQL statement zSql on zDatabase, using parameters zArgs and file name substitutions zFileArgs * Result data is loaded onto pData, and pRowCnt and pColCnt will indicate number of loaded rows and * number of columns in the row. Total number of items in pData will be nRowCnt * nColCnt */ static int _runSql(char *zDatabase, char *zSrcSql, char *zArgs, char *zFileArgs, Array_t *pData, int *pColCnt, char *zEntryFilePath, char *zSubstFileNames) { int result; sqlite3 *pDB = NULL; sqlite3_stmt *pStmt = NULL; sqlite3_stmt *pArgsStmt = NULL; Array_t sqlArgs; char *zError = NULL; char *zFullFilePath = NULL; sqlite3_stmt *pSubstStmt = NULL; char *zFileContent = NULL; char *zSchemaSql = NULL; char *zSql = strCopy(zSrcSql, -1); /* * Only first 16 substitute parameters will be processed. This is related to the fact that in C there * is no non-hacking way to dynamically build variadic arguments. So, to support list of values we just * limit maximum number of substitute strings to reasonably high number (16) */ const char *zz[16]; memset(&zz, 0, sizeof(zz)); Array_init(&sqlArgs, sizeof(SqlArg_t), (void *) _freeSqlArg); *pColCnt = 0; // Array_init(pData, sizeof(sqlite3_value *), (void *) _freeSqliteValue); /* * Open database (use :memory: if not defined) */ if (zDatabase == NULL || strlen(zDatabase) == 0) { zDatabase = ":memory:"; } CHECK_CALL(sqlite3_open_v2(zDatabase, &pDB, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_SHAREDCACHE, NULL)); CHECK_CALL(sqlite3_enable_load_extension(pDB, 1)); // load extension library CHECK_CALL(sqlite3_load_extension(pDB, "../../bin/libFlexilite", NULL, &zError)); // load and run db schema CHECK_CALL(file_load_utf8("../../sql/dbschema.sql", &zSchemaSql)); CHECK_CALL(sqlite3_exec(pDB, (const char *) zSchemaSql, NULL, NULL, &zError)); /* * Substitute strings */ if (!STR_EMPTY(zSubstFileNames)) { CHECK_STMT_PREPARE(pDB, "select key, value from json_each(:1);", &pSubstStmt); CHECK_CALL(sqlite3_bind_text(pSubstStmt, 1, zSubstFileNames, -1, NULL)); int nSubst = 0; while ((result = sqlite3_step(pSubstStmt)) == SQLITE_ROW) { if (nSubst >= 16) { result = SQLITE_ERROR; zError = "Number of substitute strings must not exceed 16"; goto ONERROR; } sqlite3_free(zFullFilePath); zFullFilePath = NULL; Path_join(&zFullFilePath, zEntryFilePath, (char *) sqlite3_column_text(pSubstStmt, 1)); CHECK_CALL(file_load_utf8(zFullFilePath, &zFileContent)); zz[nSubst++] = zFileContent; zFileContent = NULL; // Memory will be freed by zz } if (result != SQLITE_DONE) goto ONERROR; char *zTemp = zSql; zSql = sqlite3_mprintf(zTemp, zz[0], zz[1], zz[2], zz[3], zz[4], zz[5], zz[6], zz[7], zz[8], zz[9], zz[10], zz[11], zz[12], zz[13], zz[14], zz[15]); sqlite3_free(zTemp); } // TODO use flexi('init') CHECK_STMT_PREPARE(pDB, zSql, &pStmt); // Check if we have arguments JSON. Prepare arguments if (!STR_EMPTY(zArgs)) { CHECK_STMT_PREPARE(pDB, "select value, type from json_each(:1);", &pArgsStmt); CHECK_CALL(sqlite3_bind_text(pArgsStmt, 1, zArgs, -1, NULL)); int nArgCnt = 0; while ((result = sqlite3_step(pArgsStmt)) == SQLITE_ROW) { SqlArg_t item; memset(&item, 0, sizeof(item)); item.pValue = sqlite3_value_dup(sqlite3_column_value(pArgsStmt, 0)); Array_setNth(&sqlArgs, sqlArgs.iCnt, &item); nArgCnt++; } if (result != SQLITE_DONE) goto ONERROR; /* * Process file args */ CHECK_CALL(sqlite3_reset(pArgsStmt)); CHECK_CALL(sqlite3_bind_text(pArgsStmt, 1, zFileArgs, -1, NULL)); while ((result = sqlite3_step(pArgsStmt)) == SQLITE_ROW) { int argNo = sqlite3_column_int(pArgsStmt, 0); if (argNo >= 1 && argNo <= nArgCnt) { sqlite3_free(zFullFilePath); zFullFilePath = NULL; SqlArg_t *arg = Array_getNth(&sqlArgs, (u32) argNo - 1); Path_join(&zFullFilePath, zEntryFilePath, (char *) sqlite3_value_text(arg->pValue)); CHECK_CALL(file_load_utf8(zFullFilePath, &arg->zText)); } } if (result != SQLITE_DONE) goto ONERROR; Array_each(&sqlArgs, (void *) _bindSqlArg, pStmt); } while ((result = sqlite3_step(pStmt)) == SQLITE_ROW) { if (*pColCnt == 0) *pColCnt = sqlite3_column_count(pStmt); int iCol; for (iCol = 0; iCol < *pColCnt; iCol++) { sqlite3_value *pVal = sqlite3_value_dup(sqlite3_column_value(pStmt, iCol)); Array_setNth(pData, pData->iCnt, &pVal); } } if (result != SQLITE_DONE) goto ONERROR; result = SQLITE_OK; goto EXIT; ONERROR: Array_clear(pData); if (pDB && zError == NULL) { zError = (char *) sqlite3_errmsg(pDB); } if (zError != NULL) printf("Error: %s\n", zError); EXIT: sqlite3_free(zSchemaSql); sqlite3_finalize(pStmt); sqlite3_finalize(pArgsStmt); sqlite3_finalize(pSubstStmt); if (pDB != NULL) { result = sqlite3_close(pDB); if (result != SQLITE_OK) { printf("DB Close Error %d. %s\n", result, sqlite3_errmsg(pDB)); } } Array_clear(&sqlArgs); sqlite3_free(zFullFilePath); sqlite3_free(zSql); for (int i = 0; i < ARRAY_LEN(zz); i++) sqlite3_free((void *) zz[i]); if (zFileContent != NULL) sqlite3_free(zFileContent); return result; }
static int command_releases(struct plugin_handle* plugin, struct plugin_user* user, struct plugin_command* cmd) { struct extras_data* extrasdata = (struct extras_data*) plugin->ptr; struct cbuffer* buf = cbuf_create(128); sqlite3_stmt *res; int error = 0; int rec_count = 0; const char *tail; char *query = "SELECT * FROM releases;"; cbuf_append_format(buf, "*** %s:", cmd->prefix); error = sqlite3_prepare_v2(extrasdata->db, query, strlen(query), &res, &tail); while (sqlite3_step(res) == SQLITE_ROW) { cbuf_append_format(buf, "\nID: %d\nTitle: %s\nMagnet link: magnet:?xt=urn:tree:tiger:%s\nPublished: %s", sqlite3_column_int(res, 0), (char*) sqlite3_column_text(res, 1), (char*) sqlite3_column_text(res, 2), (char*) sqlite3_column_text(res, 3)); rec_count++; } if (error != SQLITE_OK || rec_count < 1) { cbuf_append(buf, " No releases found."); } sqlite3_finalize(res); plugin->hub.send_message(plugin, user, cbuf_get(buf)); cbuf_destroy(buf); return 0; }
static void _lib_geotagging_calculate_offset_callback(GtkWidget *widget, dt_lib_module_t *self) { dt_lib_geotagging_t *d = (dt_lib_geotagging_t*)self->data; const gchar *gps_time = gtk_entry_get_text(GTK_ENTRY(d->floating_window_entry)); if(gps_time) { gchar **tokens = g_strsplit(gps_time, ":", 0); if(tokens[0] != '\0' && tokens[1] != '\0' && tokens[2] != '\0') { if(g_ascii_isdigit(tokens[0][0]) && g_ascii_isdigit(tokens[0][1]) && tokens[0][2] == '\0' && g_ascii_isdigit(tokens[1][0]) && g_ascii_isdigit(tokens[1][1]) && tokens[1][2] == '\0' && g_ascii_isdigit(tokens[2][0]) && g_ascii_isdigit(tokens[2][1]) && tokens[2][2] == '\0') { int h, m, s; h = (tokens[0][0] - '0')*10 + tokens[0][1] - '0'; m = (tokens[1][0] - '0')*10 + tokens[1][1] - '0'; s = (tokens[2][0] - '0')*10 + tokens[2][1] - '0'; if(h < 24 && m < 60 && s < 60) { // finally a valid time // get imgid int32_t imgid = -1; sqlite3_stmt *stmt; DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), "select imgid from selected_images order by imgid asc limit 1", -1, &stmt, NULL); if(sqlite3_step(stmt) == SQLITE_ROW) imgid = sqlite3_column_int(stmt, 0); else // no selection is used, use mouse over id DT_CTL_GET_GLOBAL(imgid, lib_image_mouse_over_id); sqlite3_finalize(stmt); if(imgid > 0) { const dt_image_t *cimg = dt_image_cache_read_get(darktable.image_cache, imgid); // get the exif_datetime_taken and parse it gint year; gint month; gint day; gint hour; gint minute; gint second; if (sscanf(cimg->exif_datetime_taken, "%d:%d:%d %d:%d:%d", (int*)&year, (int*)&month, (int*)&day, (int*)&hour,(int*)&minute,(int*)&second) == 6) { // calculate the offset long int exif_seconds = hour*60*60 + minute*60 + second; long int gps_seconds = h*60*60 + m*60 + s; long int offset = gps_seconds - exif_seconds; // transform the offset back into a string gchar sign = (offset < 0)?'-':'+'; offset = labs(offset); gint offset_h = offset / (60*60); offset -= offset_h*60*60; gint offset_m = offset / 60; offset -= offset_m*60; gchar *offset_str = g_strdup_printf("%c%02d:%02d:%02ld", sign, offset_h, offset_m, offset); // write the offset into d->offset_entry gtk_entry_set_text(GTK_ENTRY(d->offset_entry), offset_str); g_free(offset_str); } dt_image_cache_read_release(darktable.image_cache, cimg); } } } } g_strfreev(tokens); } gtk_widget_destroy(d->floating_window); }
void server_Sort(http_request_t req,socket_t* clientSocket,db_t* self) { char* key; char *com; char buf[500]="SELECT * FROM database WHERE "; char* tmp=strchr(req.uri,'?')+1; key=strtok(tmp,"&"); list_t* list=list_new(); int count; while(key!=NULL) { list_push(list,key,strlen(key)+1); key=strtok(NULL,"&"); } count=db_count(self,"database"); while(list_get_count(list)) { com=list_pop(list); if(!strncmp(com,"age",3)) { if(strpbrk(com,"0987654321")) { char * qw=strstr(com,"_")+1; if(!strncmp(qw,"gt",2)) { sprintf(com,"age<%i",atoi(strpbrk(com,"0123456789"))); } else if(!strncmp(qw,"lt",2)) { sprintf(com,"age>%i",atoi(strpbrk(com,"0123456789"))); } else { parse_from_db(list,self); server_GET_all(req,clientSocket,list); return; } } else { parse_from_db(list,self); server_GET_all(req,clientSocket,list); return; } strcat(buf,com); if(list_get_count(list)) strcat(buf," AND "); } else if(!strncmp(com,"salary",6)) { if(strpbrk(com,"0987654321")) { char * qw=strstr(com,"_")+1; if(!strncmp(qw,"gt",2)) { sprintf(com,"salary<%.2f",atof(strpbrk(com,"0123456789"))); } else if(!strncmp(qw,"lt",2)) { sprintf(com,"salary>%.2f",atof(strpbrk(com,"0123456789"))); } else { parse_from_db(list,self); server_GET_all(req,clientSocket,list); return; } } else { parse_from_db(list,self); server_GET_all(req,clientSocket,list); return; } strcat(buf,com); if(list_get_count(list)) strcat(buf," AND "); } else if(!strncmp(com,"count",5)) { if(strpbrk(com,"0987654321")) { count=atoi(strpbrk(com,"0123456789")); } else { parse_from_db(list,self); server_GET_all(req,clientSocket,list); return; } } } sqlite3_stmt * stmt = NULL; sqlite3_prepare_v2(get_db(self), buf, strlen(buf), &stmt, NULL); int i=0; puts(buf); while(1) { int rc = sqlite3_step(stmt); if (SQLITE_ROW == rc) { if(i<count) { lanser * FL=Freelanser_new(); Freelanser_set(FL,sqlite3_column_text(stmt, 0),sqlite3_column_text(stmt, 1),sqlite3_column_double(stmt, 2),sqlite3_column_text(stmt, 4),sqlite3_column_int(stmt, 3)); list_push(list,FL,get_size()); free(FL); } else break; i++; } else if (SQLITE_DONE == rc) { break; } } server_GET_all(req,clientSocket,list); }
void edit_row(http_request_t req, socket_t * clientSocket,db_t * db) { int id=atoi(strpbrk(req.uri,"0123456789")); ptrdiff_t nameLeng=(strpbrk(req.uri,"0123456789")-1)-(req.uri+10); char *name=malloc(sizeof(char)*nameLeng+1); memcpy(name,req.uri+10,nameLeng); name[nameLeng]='\0'; sqlite3_stmt * stmt = NULL; stmt=db_getrow(db,name,id); char buf[5000]=""; char text[5000]=""; sprintf(text, "<html>" "<body>" "<form align=\"center\" action=""http://127.0.0.1:5000/db/edit/%s/%i"" method=""POST"">" "Name:<br>" "<input type=""text"" name=""name"" value=%s><br>" "Surname:<br>" "<input type=""text"" name=""surname"" value=%s ><br>" "Age:<br>" "<input type=""text"" name=""age"" value=%i><br>" "<input type=""submit"" value='Send EDIT request' />" "</form>" "</body>",name,id,sqlite3_column_text(stmt, 0),sqlite3_column_text(stmt, 1),sqlite3_column_int(stmt, 2)); strcat(buf,text); socket_write_string(clientSocket,buf); }
inline bool SQLite3StatementGetBOOLWithColumn(SQLite3StatementRef statement, CFIndex index) { return sqlite3_column_int(statement->stmt, (int)index) != 0; }
void get_row(http_request_t req, socket_t * clientSocket,db_t * db) { int id=atoi(strpbrk(req.uri,"0123456789")); ptrdiff_t nameLeng=(strpbrk(req.uri,"0123456789")-1)-(req.uri+4); char *name=malloc(sizeof(char)*nameLeng+1); memcpy(name,req.uri+4,nameLeng); name[nameLeng]='\0'; sqlite3_stmt * stmt = NULL; stmt=db_getrow(db,name,id); char buf[5000]; sprintf(buf,"<html>" "<head>" "<title>Page Title</title>" "</head>" "<body>" "<p align=\"center\">NAME: %s<p>" "<p align=\"center\">SURNAME: %s<p>" "<p align=\"center\">AGE: %i<p><br><br><br>" "<p align=\"center\" ><a href=\"/db/%s\" onclick=\"doDelete()\">DELETE</a><p>" "<p align=\"center\"><a href=\"/db/editw/%s/%i\" >EDIT</a><p>" "<script>" "function doDelete(){" "var xhttp=new XMLHttpRequest();" "xhttp.open(\"DELETE\",\"/db/%s/%i\",true);" "xhttp.send();" "}" "</script>" "</body></html>",sqlite3_column_text(stmt, 0),sqlite3_column_text(stmt, 1),sqlite3_column_int(stmt, 2),name,name,id,name,id); socket_write_string(clientSocket,buf); sqlite3_finalize(stmt); }
static void update(dt_lib_module_t *user_data, gboolean early_bark_out) { // early_bark_out = FALSE; // FIXME: when barking out early we don't update on ctrl-a/ctrl-shift-a. but // otherwise it's impossible to edit text const dt_lib_module_t *self = (dt_lib_module_t *)user_data; dt_lib_metadata_t *d = (dt_lib_metadata_t *)self->data; const int imgsel = dt_control_get_mouse_over_id(); if(early_bark_out && imgsel == d->imgsel) return; d->imgsel = imgsel; sqlite3_stmt *stmt; GList *title = NULL; uint32_t title_count = 0; GList *description = NULL; uint32_t description_count = 0; GList *creator = NULL; uint32_t creator_count = 0; GList *publisher = NULL; uint32_t publisher_count = 0; GList *rights = NULL; uint32_t rights_count = 0; // using dt_metadata_get() is not possible here. we want to do all this in a single pass, everything else // takes ages. if(imgsel < 0) // selected images { DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), "SELECT key, value FROM main.meta_data WHERE id IN " "(SELECT imgid FROM main.selected_images) GROUP BY " "key, value ORDER BY value", -1, &stmt, NULL); } else // single image under mouse cursor { DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), "SELECT key, value FROM main.meta_data " "WHERE id = ?1 GROUP BY key, value ORDER BY value", -1, &stmt, NULL); DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, imgsel); } while(sqlite3_step(stmt) == SQLITE_ROW) { if(sqlite3_column_bytes(stmt, 1)) { char *value = g_strdup((char *)sqlite3_column_text(stmt, 1)); switch(sqlite3_column_int(stmt, 0)) { case DT_METADATA_XMP_DC_CREATOR: creator_count++; creator = g_list_append(creator, value); break; case DT_METADATA_XMP_DC_PUBLISHER: publisher_count++; publisher = g_list_append(publisher, value); break; case DT_METADATA_XMP_DC_TITLE: title_count++; title = g_list_append(title, value); break; case DT_METADATA_XMP_DC_DESCRIPTION: description_count++; description = g_list_append(description, value); break; case DT_METADATA_XMP_DC_RIGHTS: rights_count++; rights = g_list_append(rights, value); break; } } } sqlite3_finalize(stmt); fill_combo_box_entry(d->title, title_count, title, &(d->multi_title)); fill_combo_box_entry(d->description, description_count, description, &(d->multi_description)); fill_combo_box_entry(d->rights, rights_count, rights, &(d->multi_rights)); fill_combo_box_entry(d->creator, creator_count, creator, &(d->multi_creator)); fill_combo_box_entry(d->publisher, publisher_count, publisher, &(d->multi_publisher)); g_list_free_full(title, g_free); g_list_free_full(description, g_free); g_list_free_full(creator, g_free); g_list_free_full(publisher, g_free); g_list_free_full(rights, g_free); }
int Sqlite3Statement::getInt(int column) { return sqlite3_column_int(m_stmt, column); }
/* ** Parameter zTab is the name of a table in database db with nCol ** columns. This function allocates an array of integers nCol in ** size and populates it according to any implicit or explicit ** indices on table zTab. ** ** If successful, SQLITE_OK is returned and *paIndex set to point ** at the allocated array. Otherwise, an error code is returned. ** ** See comments associated with the member variable aIndex above ** "struct echo_vtab" for details of the contents of the array. */ static int getIndexArray( sqlite3 *db, /* Database connection */ const char *zTab, /* Name of table in database db */ int nCol, int **paIndex ){ sqlite3_stmt *pStmt = 0; int *aIndex = 0; int rc; char *zSql; /* Allocate space for the index array */ aIndex = (int *)sqlite3MallocZero(sizeof(int) * nCol); if( !aIndex ){ rc = SQLITE_NOMEM; goto get_index_array_out; } /* Compile an sqlite pragma to loop through all indices on table zTab */ zSql = sqlite3_mprintf("PRAGMA index_list(%s)", zTab); if( !zSql ){ rc = SQLITE_NOMEM; goto get_index_array_out; } rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); sqlite3_free(zSql); /* For each index, figure out the left-most column and set the ** corresponding entry in aIndex[] to 1. */ while( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ const char *zIdx = (const char *)sqlite3_column_text(pStmt, 1); sqlite3_stmt *pStmt2 = 0; zSql = sqlite3_mprintf("PRAGMA index_info(%s)", zIdx); if( !zSql ){ rc = SQLITE_NOMEM; goto get_index_array_out; } rc = sqlite3_prepare(db, zSql, -1, &pStmt2, 0); sqlite3_free(zSql); if( pStmt2 && sqlite3_step(pStmt2)==SQLITE_ROW ){ int cid = sqlite3_column_int(pStmt2, 1); assert( cid>=0 && cid<nCol ); aIndex[cid] = 1; } if( pStmt2 ){ rc = sqlite3_finalize(pStmt2); } if( rc!=SQLITE_OK ){ goto get_index_array_out; } } get_index_array_out: if( pStmt ){ int rc2 = sqlite3_finalize(pStmt); if( rc==SQLITE_OK ){ rc = rc2; } } if( rc!=SQLITE_OK ){ sqlite3_free(aIndex); aIndex = 0; } *paIndex = aIndex; return rc; }
int main(int argc, char **argv) { // MPI variables int my_rank, NP; int source, dest; int tag; int length; char name[MPI_MAX_PROCESSOR_NAME + 1]; char message[MESSAGE_SIZE]; MPI_Status status; MPI_Init(&argc, &argv); // argc and argv passed by address to all MPI processes MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); // returns taskID = rank of calling process MPI_Comm_size(MPI_COMM_WORLD, &NP); // returns total no of MPI processes available if (my_rank == MASTER) { // Head Office (master) // Print startup info printf("HO: started\n"); MPI_Get_processor_name(name, &length); printf("HO: name = %s, my_rank = %d\n", name, my_rank); // Socket stuff int socket_descriptor, client_sock, c, *new_sock; struct sockaddr_in server, client; void *thread_status = 0; // Create socket socket_descriptor = socket(AF_INET, SOCK_STREAM, 0); if (socket_descriptor == -1) { printf("HO: Could not create socket"); } puts("HO: Socket created"); // Prepare sockaddr_in structure server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons( PORT_NUMBER ); // Bind if ( bind(socket_descriptor, (struct sockaddr *)&server, sizeof(server)) < 0 ) { perror("HO: Socket bind failed. Error"); return 1; } puts("HO: Socket bind done"); // Listen for new requests listen(socket_descriptor, MAX_CONN_REQ_IN_QUEUE); puts("HO: Waiting for incoming connections..."); // Accept incoming connection c = sizeof(struct sockaddr_in); while ( (client_sock = accept(socket_descriptor, (struct sockaddr *)&client, (socklen_t*)&c)) ) { puts("HO: Connection accepted!"); pthread_t sniffer_thread; new_sock = malloc(1); *new_sock = client_sock; // Start a new thread with connection_handler if ( pthread_create(&sniffer_thread, NULL, connection_handler, (void*) new_sock) < 0) { perror("HO: Could not create thread"); return 1; } // Join the thread, so that MASTER doesn't terminate before the thread pthread_join(sniffer_thread, &thread_status); if (thread_status == 42) { printf("HO: Killing signal sent, shutdown system!\n"); // What to do here? // MPI_Abort? // MPI_Finalize? // break should get us down to MPI_Finalize and return 0, but doesn't work.. break; } puts("HO: Socket handler thread exited"); } if (client_sock < 0) { perror("HO: Connection accept failed"); return 1; } // for (source = 1; source < NP; source++) { // MPI_Recv(message, MESSAGE_SIZE, MPI_CHAR, MPI_ANY_SOURCE, tag, MPI_COMM_WORLD, &status); // printf("HO received: %s\n", message); // } } else { // Branch Office (slave) // Branch variables pid_t pid = 0; int account_status = 0, wpid; // sqlite3 variables sqlite3 *db; int rc; char query[QUERY_SIZE]; MPI_Get_processor_name(name, &length); printf("BO %d: starting on name = %s\n", my_rank, name); // Get the number of accounts to start from DB rc = sqlite3_open_v2("accounts.db", &db, SQLITE_OPEN_READONLY, NULL); if (rc) { fprintf(stderr, "BO %d: Can't open database: %s\n", my_rank, sqlite3_errmsg(db)); sqlite3_close(db); return(1); } // Find all account ids for this branch sqlite3_stmt *statement; sprintf(query, "SELECT id, balance FROM accounts WHERE branch = %d", my_rank); sqlite3_prepare_v2(db, query, strlen(query) + 1, &statement, NULL); // For each account, start a new process while (1) { int row = sqlite3_step(statement); if (row == SQLITE_ROW) { int account_id; account_id = sqlite3_column_int(statement, 0); balance = sqlite3_column_double(statement, 1); pid = fork(); if (pid < 0 ) { printf("BO %d: pid < 0, fork failed!\n", my_rank); continue; } if (pid == 0) { // Inside bank account process printf("BO %d: account_id = %d, balance = %f\n", my_rank, account_id, balance); // RPC // printf("BO %d_%d: before execl", my_rank, account_id); // execl("rpc/accounts/account_server", "account_server", (char*)NULL); // printf("BO %d_%d: after execl", my_rank, account_id); // return 0; } else { printf("BO %d: created pid = %d\n", my_rank, pid); } } else if (row == SQLITE_DONE) { printf("BO %d: Done creating account processes.\n", my_rank); break; } else { fprintf(stderr, "BO : sqlite row failed..\n"); return 1; } } sqlite3_finalize(statement); sqlite3_close(db); // Let Head Office know Branch up and is running // sprintf(message, "Branch %d successfully started on processor %s", my_rank, name); // MPI_Send(message, strlen(message) + 1, MPI_CHAR, MASTER, tag, MPI_COMM_WORLD); // Wait for messages from Head Office for eternity while (1) { printf("BO %d waiting for MPI_Recv again\n", my_rank); MPI_Recv(message, MESSAGE_SIZE, MPI_CHAR, MASTER, MPI_ANY_TAG, MPI_COMM_WORLD, &status); printf("BO %d MPI_Recv from master with tag %d: %s\n", my_rank, status.MPI_TAG, message); char *token, *params[3]; int account_id, to_account_id; double amount, result; int j = 0; // Separate message parameters token = strtok(message, separator); while (token != NULL) { params[j++] = token; token = strtok(NULL, separator); } account_id = atoi(params[0]); amount = atof(params[1]); to_account_id = atoi(params[2]); // Query process for account... // RPC not working, use DB instead // Operation sent as TAG, get it from status switch (status.MPI_TAG) { case GET_BALANCE_OPERATION: result = get_balance(account_id); printf("%f\n", result); if (result < 0) { sprintf(message, "Couldn't get balance...\n"); } else { sprintf(message, "Balance is £%.2f\n", result); } break; case DEPOSIT_OPERATION: result = deposit(account_id, amount); if (result < 0) { sprintf(message, "Couldn't make deposit...\n"); } else { sprintf(message, "New balance is £%.2f\n", result); } break; case WITHDRAW_OPERATION: result = withdraw(account_id, amount); if (result < 0) { sprintf(message, "Couldn't make withdraw...\n"); } else { sprintf(message, "New balance is £%.2f\n", result); } break; case TRANSFER_OPERATION: sprintf(message, transfer(account_id, to_account_id, amount)); break; } MPI_Send(message, MESSAGE_SIZE, MPI_CHAR, MASTER, status.MPI_TAG, MPI_COMM_WORLD); printf("BO %d sent: %s\n", my_rank, message); } printf("BO %d: shutting down\n", my_rank); // RPC // wait for all children to exit // while ( (wpid = wait(&account_status) ) > 0) {} } MPI_Finalize(); return 0; }