(* Implement subcommands for listing and adding tags. *) open CalendarLib open Todo_types open Todo_utils open Todo_tag_utils open Printf let cmd_tag_list dbh anon_params = if anon_params <> [] then error "extra parameters to 'tag-list' subcommand"; (* Used tags. *) let rows = PGSQL(dbh) " select tags.name, tags.colour, tasks.id from tags_tasks, tags, tasks where tags_tasks.tagid = tags.id and tags_tasks.taskid = tasks.id order by tags.name, tasks.id" in if rows <> [] then printf "Tags used:\n"; let prev = ref None in List.iter ( fun (name, colour, taskid) -> let cur = name, colour in (match !prev with | None -> printf " %s used by" (string_of_tag name colour) | Some prev when prev <> cur -> printf "\n %s used by" (string_of_tag name colour) | Some _ -> () ); prev := Some cur; printf " #%ld" taskid ) rows; if !prev <> None then printf "\n"; (* Unused tags. *) let rows = PGSQL(dbh) " select tags.name, tags.colour from tags where not exists (select 1 from tags_tasks where tagid = tags.id) order by tags.name" in if rows <> [] then printf "Tags not used (delete with 'todo tag-del'):\n"; List.iter ( fun (name, colour) -> printf " %s\n" (string_of_tag name colour) ) rows let cmd_tag dbh anon_params tag_del = let id, tag_add = match anon_params with | id :: rest -> Int32.of_string id, rest | _ -> error "incorrect parameters to 'tag' subcommand" in if anon_params = [] && tag_del = [] then error "no tags to add or delete from this task"; (* Map the tag_add and tag_del names to tag IDs. *) let tag_add = if tag_add <> [] then PGSQL(dbh) "select id from tags where name in $@tag_add" else [] in let tag_del = if tag_del <> [] then PGSQL(dbh) "select id from tags where name in $@tag_del" else [] in PGOCaml.begin_work dbh; if tag_del <> [] then PGSQL(dbh) "delete from tags_tasks where taskid = $id and tagid in $@tag_del"; List.iter ( fun tag -> PGSQL(dbh) "insert into tags_tasks (taskid, tagid) values ($id, $tag)" ) tag_add; PGOCaml.commit dbh let cmd_tag_add dbh anon_params = let name, colour = match anon_params with | [name; colour] -> name, colour | _ -> error "incorrect parameters to 'tag-add' subcommand" in PGOCaml.begin_work dbh; PGSQL(dbh) "insert into tags (name, colour) values ($name, $colour)"; PGOCaml.commit dbh let cmd_tag_del dbh anon_params = let name = match anon_params with | [name] -> name | _ -> error "incorrect parameters to 'tag-del' subcommand" in PGOCaml.begin_work dbh; PGSQL(dbh) "delete from tags where name = $name"; PGOCaml.commit dbh let cmd_tag_colour dbh anon_params = let name, colour = match anon_params with | [name; colour] -> name, colour | _ -> error "incorrect parameters to 'tag-colour' subcommand" in PGOCaml.begin_work dbh; PGSQL(dbh) "update tags set colour = $colour where name = $name"; PGOCaml.commit dbh