aboutsummaryrefslogtreecommitdiff
path: root/src/guff/post-model.cr
blob: 4a20db835f5cf60ccc0962905895b9796c7c4269 (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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
module Guff
  class PostModel < Model
    SQL = TemplateCache.new({
      tags: "
        SELECT DISTINCT
               post_id

          FROM (%{sql})
      ",

      tag: "
        SELECT a.post_id

          FROM post_tags a
          JOIN tags b
            ON (b.tag_id = a.tag_id)

         WHERE b.name = '%{tag}'
      ",

      count_posts: "
        SELECT COUNT(*)

          FROM posts a
          JOIN (%{tags}) b
            ON (b.post_id = a.post_id)

         WHERE a.site_id = :site_id
           AND %{filter}
      ",

      get_posts: "
        SELECT %{cols}

          FROM posts a
          JOIN (%{tags}) b
            ON (b.post_id = a.post_id)

         WHERE a.site_id = :site_id
           AND %{filter}

         ORDER BY %{sort} %{dir}
         OFFSET :offset LIMIT :limit
      ",
    })

    def initialize(models : Models)
      super(models, SQL)
    end

    COLUMNS = {
      "post_id": {
        default:  true,
        sortable: true,
        clause:   "a.post_id",
      },

      "name": {
        default:  true,
        sortable: true,
        clause:   "a.name",
      },

      "body": {
        default:  false,
        sortable: true,
        clause:   "a.body",
      },

      "html": {
        default:  true,
        sortable: true,
        clause:   "a.html",
      },

      "posted_at": {
        default:  true,
        sortable: true,
        clause:   "a.posted_at",
      },

      "created_at": {
        default:  true,
        sortable: true,
        clause:   "a.created_at",
      },

      "tags": {
        default:  true,
        sortable: false,
        clause:   "
          (SELECT group_agg(d.name, '|')

             FROM post_tags c
             JOIN tags d
               ON (d.tag_id = c.tag_id)

            WHERE d.post_id = a.post_id)
        ",
      },
    }

    #####################
    # get_posts methods #
    #####################

    def get_posts(
      cols = nil                  : Array(String)?,
      site_id = nil               : Int?,
      q = ""                      : String,
      tags = [] of Array(String)  : Array(Array(String)),
      page = 1                    : Int,
      limit = 20                  : Int,
      sort = "posted_at"          : String,
      dir = "desc"                : String,
    )
      # build sql args
      sql_args = {
        "site_id": (site_id || @models.site.get_default).to_s,
      } of String => String

      # verify sort column
      raise "unknown sort column" unless COLUMNS.has_key?(sort)
      raise "column is not sortable" unless COLUMNS[sort][:sortable]

      # build tmpl args
      tmpl_args = {
        # TODO
        "filter":   "1 = 1", # true
        "sort":     COLUMNS[sort][:col],
        "dir":      dir,
        "tags":     get_tags_filter(tags),
        "cols":     get_columns_clause(cols),
      } of String => String

      # count number of matching rows
      num_rows = (one(:count_posts, sql_args, tmpl_args).to_s || 0).to_i

      # TODO: add Post class?
      rows = [] of Hash(String, ::SQLite3::Value)
      if num_rows > 0
        all(:get_posts, sql_args.merge({
          ":offset":  ((page - 1) * limit).to_s,
          ":limit":   limit.to_s,
        }), tmpl_args) do |row|
          rows << Post.new(row)
          nil
        end
      end

      # return result
      Results(Post).new(
        page:     page,
        limit:    limit,
        num_rows: num_rows,
        rows:     rows,
      )
    end

    private def get_columns_clause(cols : Array(String)?)
      (cols || COLUMNS.keys.select { |col|
        COLUMNS[key][:default]
      }).map { |col|
        "%s AS %s" % [COLUMNS[col][:clause], col]
      }.join(", ")
    end

    NO_POSTS = "
      SELECT post_id
        FROM posts
       LIMIT 0
    "

    private def get_tags_filter(tag_sets : Array(Array(String)))
      (tag_sets.size > 0) ? template(:tags, {
        "sql": tag_sets.map { |tags|
          template(:tags, {
            "sql": tags.map { |tag|
              template(:tag, {
                "tag": @models.db.quote(tag),
              })
            }.join(" INTERSECTS "),
          })
        }.join(" UNION "),
      }) : NO_POSTS
    end

    def add_post(req)
      # TODO: return post id
      {ok: true}
    end

    def remove_posts(req)
      # TODO
      {ok: true}
    end

    def set_tags(req)
      # TODO
      {ok: true}
    end
  end
end