diff options
Diffstat (limited to 'src/guff/tag-model.cr')
-rw-r--r-- | src/guff/tag-model.cr | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/src/guff/tag-model.cr b/src/guff/tag-model.cr index 5d758d1..2aa9d89 100644 --- a/src/guff/tag-model.cr +++ b/src/guff/tag-model.cr @@ -1,10 +1,52 @@ 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)) + # get ids of existing tags + ids = get_ids(tags) + + query(:add_tags, nil, { + "tags": tags.reject { |tag| + ids[tag]? + }.map { |tag| + "'" + @db.quote(tag) + "'" + }.join(','), + }) + 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| + r[row["name"] as String] = (row["tag_id"] as String).to_i + end + + # return result + r + end end end |