X-Git-Url: https://git.deb.at/?a=blobdiff_plain;f=database.c;h=1b337c6b59f69bcc6687aa45b0000dfdfed5c6ad;hb=0541360161a8512d9852c5381ad0ac9953956edd;hp=893cb9902cd5dd8456394007b9108e8b4a9d38c9;hpb=4909ba20244f55ee7326a40d751cf6737c2bc2b6;p=pkg%2Fabook.git diff --git a/database.c b/database.c index 893cb99..1b337c6 100644 --- a/database.c +++ b/database.c @@ -26,9 +26,10 @@ abook_field_list *fields_list = NULL; int fields_count = 0; list_item *database = NULL; -int items = 0; +static int items = 0; #define ITEM_SIZE (fields_count * sizeof(char *)) +#define LAST_ITEM (items - 1) #define INITIAL_LIST_CAPACITY 30 static int list_capacity = 0; @@ -202,9 +203,11 @@ declare_unknown_field(char *key) if(!database) return; - for(i = 0; i < fields_count; i++) - if(database[i]) + for(i = 0; i < items; i++) + if(database[i]) { database[i] = xrealloc(database[i], ITEM_SIZE); + database[i][fields_count - 1] = NULL; + } } /* @@ -345,23 +348,36 @@ int save_database() { FILE *out; + int ret = 0; struct db_enumerator e = init_db_enumerator(ENUM_ALL); + char *datafile_new = strconcat(datafile, ".new", NULL); + char *datafile_old = strconcat(datafile, "~", NULL); - if( (out = abook_fopen(datafile, "w")) == NULL ) - return -1; - - if(list_is_empty()) { - fclose(out); - unlink(datafile); - return 1; + if( (out = abook_fopen(datafile_new, "w")) == NULL ) { + ret = -1; + goto out; } - - write_database(out, e); + if(!list_is_empty()) + /* + * Possibly should check if write_database failed. + * Currently it returns always zero. + */ + write_database(out, e); fclose(out); - return 0; + if(access(datafile, F_OK) == 0 && + (rename(datafile, datafile_old)) == -1) + ret = -1; + + if((rename(datafile_new, datafile)) == -1) + ret = -1; + +out: + free(datafile_new); + free(datafile_old); + return ret; } static void @@ -522,9 +538,6 @@ surnamecmp(const void *i1, const void *i2) int ret, idx = field_id(NAME); char *n1, *n2, *s1, *s2; - if(idx == 0) - return 0; /* no 'name' field */ - n1 = (*(list_item *)i1)[idx]; n2 = (*(list_item *)i2)[idx]; @@ -642,6 +655,17 @@ is_valid_item(int item) return item <= LAST_ITEM && item >= 0; } +int +last_item() +{ + return LAST_ITEM; +} + +int +db_n_items() +{ + return items; +} int real_db_enumerate_items(struct db_enumerator e) @@ -805,3 +829,22 @@ db_item_get(int i) return database[i]; } +/* Fetch addresses from all fields of FIELD_EMAILS type */ +/* Memory has to be freed by the caller */ +char * +db_email_get(int item) +{ + int i; + char *res; + abook_field_list *cur; + abook_list *emails = NULL; + + for(cur = fields_list, i = 0; cur; cur = cur->next, i++) + if(cur->field->type == FIELD_EMAILS && *database[item][i]) + abook_list_append(&emails, database[item][i]); + + res = abook_list_to_csv(emails); + abook_list_free(&emails); + return res ? res : xstrdup(""); +} +