使用Clojure / Korma / Postgres进行子选择的准备语句

时间:2012-10-27 06:02:02

标签: postgresql clojure korma

我一直试图在Korma做以下事情无济于事:

SQL:

PREPARE q (int) AS SELECT * FROM post a
    WHERE EXISTS 
        (SELECT parent_id
         FROM post_map 
         WHERE parent_id=a.id AND parent_id=$1);
EXECUTE q(1);

我最好的Korma尝试:

(defn children [parent-id]        ;; clojure
      (if (number? parent-id)
        (exec-raw (str
          "PREPARE q (int) AS SELECT * FROM post a WHERE EXISTS 
               (SELECT parent_id FROM post_map WHERE parent_id=a.id AND parent_id=$1); 
           EXECUTE q(" parent-id ")") 
         :results)))

这是我一直得到的错误: (我真的不了解下面的::运算符:)

Failure to execute query with SQL:
PREPARE q (int) AS SELECT * FROM post a WHERE EXISTS 
          (SELECT parent_id FROM post_map WHERE parent_id=a.id AND parent_id=$1); 
       EXECUTE q(1)  ::  nil
PSQLException:
 Message: No results were returned by the query.
 SQLState: 02000
 Error Code: 0
PSQLException No results were returned by the query.  org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery (AbstractJdbc2Statement.java:274)

我不认为这是一个非常古怪的事情想要查询,所以我想知道Korma是否不会为我的项目工作。我只是做错了吗?

更新:这就是我最终做的事情(在我保释Korma之后[抱歉Korma])。

(defn children [parent-id]
  (if (unsigned? parent-id)
    (sql/with-connection db
      (sql/with-query-results results
         [(str "select " field-list ", b.parent_id from post a, post_map b where a.id=b.child_id and a.id in "
               "(select child_id from post c, post_map d where c.id=d.parent_id and c.id=?)") parent-id]
           (into [] results)))))

1 个答案:

答案 0 :(得分:2)

Korma在引擎盖下使用做好准备,只适用于单一声明,并为您做好准备。

这有效:

;; but isn't it more 'parent' than 'children'?
(defn children-raw [parent-id]
  (if (number? parent-id)
    (exec-raw [(str
                "SELECT * FROM post a WHERE EXISTS
               (SELECT parent_id FROM post_map WHERE parent_id=a.id AND parent_id=?)")
               [parent-id]]
              :results)))
但是,我对你的命名/架构感到有些困惑,即使从这个小例子中很难说清楚。你的函数被称为“childREN”但是使用EXISTS()我认为它将返回最多一条记录。此外,它似乎选择,但使用隐式连接它将始终选择自己?

如果post_map是从id到parent_id的链接,并且你想要让孩子们接受,我会更多地考虑以下几点:

(defentity post
  (entity-fields :id))
(defentity post_map
  (entity-fields :id :parent_id))
(defn children-dsl [parent-id]
  (if (number? parent-id)
    (select post
            (where {:id [in (subselect post_map
                                       (fields :id)
                                       (where {:parent_id parent-id}))]}))))