From d5f49eee6c08bda1dad31bc906f54e44737e843f Mon Sep 17 00:00:00 2001 From: Paul Duncan Date: Tue, 8 Mar 2016 17:12:46 -0500 Subject: mv src/guff/{,models/}*-model.cr --- src/guff/models/tag.cr | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/guff/models/tag.cr (limited to 'src/guff/models/tag.cr') 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 -- cgit v1.2.3