summaryrefslogtreecommitdiffstats
path: root/src/model/books.phel
blob: 26dbe6fe4e2504a53ad4f20fab83ebe49741c332 (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
(ns lezer.model.books
  (:require lezer.db :refer [conn])
  (:require phel.pdo)
  (:require phel.sql)
  (:require lezer.model.authors))

(defn all []
  (let [[query _] (sql/format {:select [:*]
                               :from [:books]})]
    (pdo/select conn query)))

(defn create [fields]
  (pdo/insert conn :books fields))

(defn pages [book-id]
  (let [[query params] (sql/format {:select [:pages]
                                    :from [:books]
                                    :where [:= :id book-id]})]
    (-> (pdo/prepare conn query)
        (pdo/execute params)
        (pdo/fetch-column))))

(defn find [id]
  (let [[query params] (sql/format {:select [:*]
                                    :from [:books]
                                    :where [:= :id id]})]
    (-> (pdo/prepare conn query)
        (pdo/execute params)
        (pdo/fetch))))

(defn for-author [author-id]
  (let [[query params] (sql/format {:select [:*]
                                    :from [:books]
                                    :where [:in :id {:select [:book_id]
                                                     :from [:authors_books]
                                                     :where [:= :author_id author-id]}]})]
    (-> (pdo/prepare conn query)
        (pdo/execute params)
        (pdo/fetch-all))))

(defn add-author [id fields]
  (pdo/insert conn :authors_books {:book_id id
                                   :author_id (authors/find-or-create (:name fields) fields)}))