sql - Clojure 和 HugSQL;如何提供SQL关键字?

标签 sql jdbc clojure

我使用 HugSQL 定义了这个查询:

-- :name ins! :! :n
INSERT INTO table (col0, col1, col2) VALUES :tuple*:values;

如何从 Clojure 向此查询发送 SQL 关键字?特别是我怎么能做这样的事情,

(ins! db {:values [[val0 val1 :DEFAULT] [val2 val3 val4]]})

这样查询就变成了

INSERT INTO table (col0, col1, col2) VALUES (val0, val1, DEFAULT), (val2, val3, val4)

也就是说,如何使用 Clojure 中的 SQL 关键字 DEFAULT?

谢谢。

附注我正在使用 clojure.java.jdbc 和 postgresql。

最佳答案

由于元组列表参数类型(:tuple*)是基于值的参数类型,遵循底层 jdbc 库进行参数替换,因此您不能使用它来插入原始/关键字 sql。这实际上是关于 JDBC 缺乏对此的支持的: Sending the DEFAULT placeholder via JDBC? .

但是,您可以使用 HugSQL 的 Clojure Expressions获取 :values 元组列表并重新编写查询,将 Clojure 关键字视为 SQL 关键字,并将所有其他值视为 SQL 值参数。下面,我们使用 HugSQL 的 Deep Get Param Name用于引用元组中给定索引的值参数的功能。

-- :name insert-with-default :<!
/* :require [clojure.string :as string] */
insert into test (c1, c2, c3)
values
/*~ 
(string/join ","
  (map-indexed
    (fn [tuple-index tuple]
      (str 
        "(" 
        (string/join ","
          (map-indexed
            (fn [value-index value]
              (if (keyword? value)
                (name value)
                (str 
                  ":v:values." 
                  tuple-index "." 
                  value-index))) 
            tuple))
        ")"))
     (:values params)))
~*/
returning *

结果(假设 5 是 c3 的默认值):

(insert-with-default-sqlvec {:values [[1 2 :default]
                                      [3 4 :default]]})

;=> ["insert into test (c1, c2, c3)\n
      values  (?,?,default),(?,?,default) returning *" 1 2 3 4]

(insert-with-default db {:values [[1 2 :default]
                                  [3 4 :default]]})

;=> ({:c1 1, :c2 2, :c3 5} {:c1 3, :c2 4, :c3 5})

关于sql - Clojure 和 HugSQL;如何提供SQL关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36179332/

相关文章:

mysql - 删除数据库 SQL 查询中的第一个元素

mysql - 如何用随机值填充 MySQL 数据库?

SQL Server 2005 RIGHT OUTER JOIN 不起作用

java - Clojure 代码的 Sonarqube 静态代码分析

clojure - 让 Leiningen 和 Cygwin 工作

mysql - 查询从数据库中选择所有表而不是物化 View

java - 在 Hibernate 3.2 中使用连接池 (c3p0-0.9.1.2) 时出现异常且应用程序无法连接 MySqL 数据库?

java.sql.SQLSyntaxErrorException : ORA-01747

java.sql.SQLException : ORA-01704: string literal too long When Insert Or Update

clojure - 匹配并生成可变长度的有序向量的 Clojure 规范