实现字符串中每个查询的结果

时间:2016-07-18 18:18:33

标签: postgresql jdbc clojure

我是Clojure的新手并且正在开发一个jdbc应用程序,其中我有一个字符串,其中包含在该字符串中定义的三个查询,如下所示。

(def tpch_query15
      (str "create view revenue0 (supplier_no, total_revenue) as select l_suppkey, sum(l_extendedprice * (1 - l_discount)) "
        "from lineitem where l_shipdate >= date '1993-04-01' and l_shipdate < date '1993-04-01' + interval '3' month group by l_suppkey; "
            "select s_suppkey, s_name, s_address, s_phone, total_revenue from supplier, revenue0 where s_suppkey = supplier_no "
        "and total_revenue = (select max(total_revenue) from revenue0) order by s_suppkey LIMIT 1; drop view revenue0"))

(defn run-a-query
  "Run a query three times and return the average time."
  [conn-db query queryno]
  (println (str "Running query " queryno))
  (let [starttime (System/currentTimeMillis)]
    (dotimes [n 3]
      (try
        (let
          [rs (sql/query conn-db query)]
        ;; Print column names with | as delimiter
        (dorun 0 (map #(println (clojure.string/join " | " (keys %))) rs))
        ;; Print a seperator between column names and rows
        (println "------------------------------------------------------")
        ;; Print rows with | as delimiter
        (dorun (map #(println (clojure.string/join " | " (vals %))) rs)))
        (catch Exception e)))
      (/ (- (System/currentTimeMillis) starttime) 3.0)))

;;https://clojuredocs.org/clojure.core/conj!
(defn run-all-queries
  "Run all TPC-H queries. Return a vector of average time taken for each query."
  [conn-db]
  (loop [i 0 v (transient [])]
    (if (< i 22)
      (recur (inc i) (conj! v (run-a-query conn-db (get queries-to-run i) (+ i 1))))
      (persistent! v))))

是否可以使用run-a-query函数打印该字符串中定义的所有三个查询的结果。目前,当tpch_query15传递run-a-query时,它不会打印出任何结果。据我所知,这是因为作为drop视图的三个查询中的最后一个不返回结果集,它只返回最后一个查询结果。

1 个答案:

答案 0 :(得分:0)

使用WITH子句(https://www.postgresql.org/docs/current/static/queries-with.html)将查询重新组织为单个SQL SELECT语句,而不是创建然后删除视图:

Meteor.users.update(Meteor.userId(), {$set: {'emails.0.address': pDetails.contactDetails.email, 'profile.name': pDetails.contactDetails.firstName}});

你真的不需要这里的视图,有或没有Clojure,JDBC等。无论如何,在同一个连接上混合DDL和查询/ DML(特别是在同一个请求中)通常是一个坏主意 - 性能可能会受到很大影响,具体取决于数据库,版本,驱动程序等。