diff options
author | Paul Duncan <pabs@pablotron.org> | 2016-03-08 17:12:46 -0500 |
---|---|---|
committer | Paul Duncan <pabs@pablotron.org> | 2016-03-08 17:12:46 -0500 |
commit | d5f49eee6c08bda1dad31bc906f54e44737e843f (patch) | |
tree | 0aa984fb37197112c396de10ffbf4a05dc8ee041 /src/guff/models/tag.cr | |
parent | 8989c5b2601028f575211d7443c7c082b122079e (diff) | |
download | old-guff-d5f49eee6c08bda1dad31bc906f54e44737e843f.tar.bz2 old-guff-d5f49eee6c08bda1dad31bc906f54e44737e843f.zip |
mv src/guff/{,models/}*-model.cr
Diffstat (limited to 'src/guff/models/tag.cr')
-rw-r--r-- | src/guff/models/tag.cr | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/src/guff/models/tag.cr b/src/guff/models/tag.cr new file mode 100644 index 0000000..997cdfd --- /dev/null +++ b/src/guff/models/tag.cr @@ -0,0 +1,62 @@ +module Guff + class TagModel < Model + SQL = TemplateCache.new({ + add_tags: " + INSERT INTO tags(name) VALUES %{tags} + ", + + get_tags: " + SELECT tag_id, + name + + FROM tags + + WHERE name IN (%{tags}) + ", + } of Symbol => String) + + def initialize(models : Models) + super(models, SQL) + end + + def add_tags(tags : Array(String)) + missing_tags = get_missing_tags(tags) + + if missing_tags.size > 0 + query(:add_tags, nil, { + "tags": missing_tags.map { |tag| + "('" + @db.quote(tag) + "')" + }.join(','), + }) + end + end + + private def get_missing_tags( + tags : Array(String) + ) : Array(String) + # get ids of existing tags + ids = get_ids(tags) + + # return missing tags + tags.reject { |tag| ids[tag]? } + end + + private def get_ids( + tags = [] of String : Array(String) + ) : Hash(String, Int32) + r = {} of String => Int32 + + all(:get_tags, nil, { + "tags": tags.map { |tag| + "'" + @db.quote(tag) + "'" + }.join(','), + }) do |row| + # add to results + r[row["name"] as String] = row["tag_id"].to_s.to_i + end + + # return result + r + end + end +end |