A tool for managing my collection of notes.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.7 KiB

#!/usr/bin/env bash
assignTags(){
local filename
local tags
local tagIDs
local tagIDsOr
local fileID
filename="$(findFile "$1")"
[ ! -e "$filename" ] && exit 1
tags="$(cat - | sed '/^$/d')"
fileID="$(findFileId "$filename")"
# If there are tags
if [ -n "$tags" ]; then
local values
local orlist
while read -r line; do
values+=",('$(safeSQL "$line")')"
orlist+=" OR name = '$(safeSQL "$line")'"
done <<<"$(echo "$tags")"
values="$(echo "$values" | sed 's/^,//')"
orlist="$(echo "$orlist" | sed 's/^ OR //')"
# Ensure that all the tags exist
echo "INSERT INTO tags (name) VALUES $values
EXCEPT SELECT name FROM tags;" |
sqlite3 "${sqliteFile}"
# Get the tag ids we need to assosiate with the current file
tagIDs="$(echo "SELECT id FROM tags WHERE $orlist" |
sqlite3 "${sqliteFile}")"
#Loop through them all
while read -r tagID; do
tagIDsOr+=" OR tagID = $(safeSQL "$tagID")"
# Check the tag is already linkded with the file
local existing
existing="$(echo "SELECT id FROM links
WHERE itemID = $(safeSQL "$fileID")
AND tagID = $(safeSQL "$tagID")" |
sqlite3 "${sqliteFile}"
)"
# If not, add a link
if [ -z "$existing" ]; then
echo "INSERT INTO links (itemID,tagID)
VALUES ($(safeSQL "$fileID"),$(safeSQL "$tagID"))" |
sqlite3 "${sqliteFile}"
fi
done <<<"$(echo "$tagIDs")"
tagIDsOr="$(echo "$tagIDsOr" | sed 's/^ OR //')"
# Delete any links that are not in the list
echo "DELETE FROM links
WHERE itemID = $(safeSQL "$fileID")
AND NOT ( $tagIDsOr )" |
sqlite3 "${sqliteFile}"
else # If there are no tags, simply delete any that are referenced
echo "DELETE FROM links WHERE itemID = '$(safeSQL "$fileID")'" |
sqlite3 "${sqliteFile}"
fi
}