aboutsummaryrefslogtreecommitdiff
path: root/src/guff/models/tag.cr
blob: 997cdfd91867b5c662d2dfe6f7dd86fa76022515 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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