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