简体   繁体   English

如何在Clojure中使用yesql插入和更新postgres数组?

[英]How to insert and update postgres arrays using yesql in clojure?

I have tried passing a clojure vector, also tried the following format: 我尝试过传递clojure向量,也尝试过以下格式:

-- name: insert-into-sometable<!
-- inserts in the sometable the lid and uids
INSERT INTO sometable
(lid, uids) values(:lid, ARRAY[:uids])

But both the methods throws data mismatch error. 但是这两种方法都会引发数据不匹配错误。

I think if I can call the postgres array functions from the query file then update and insert can be done easily. 我认为,如果可以从查询文件中调用postgres数组函数,则可以轻松完成更新和插入。 Please help. 请帮忙。

Thanks in advance 提前致谢

The error message of your 2nd try gives a subtile hint: 第二次尝试的错误消息给出了一个微妙的提示:

AssertionError Assert failed: Query argument mismatch.
Expected keys: (:uids])
Actual keys: (:uids)
Missing keys: (:uids])

Apparently things go south when yesql tries to parse the :uids key as it appends the closing bracket of the array definition. 显然,当yesql尝试解析:uids键时,事情就白了,因为它附加了数组定义的右括号。 Lets try something else: 让我们尝试一下:

-- name: insert-into-sometable<!
-- inserts in the sometable the lid and uids
INSERT INTO sometable
(lid, uids) values(:lid, ARRAY[ :uids ])

Notice the extra spaces between :uids and the array brackets. 注意:uids和数组括号之间的多余空格。

=> (insert-into-sometable<! {:lid 1, :uids [1 2 42])
;; => 1

Looks like a bug in yesql to me, :uid] should never get parsed as a valid key. 在我看来,yesql中的错误, :uid]永远都不应被解析为有效密钥。

Edit: Was about to file a bug with yesql, but it's already fixed with the recently released 0.5.2 version. 编辑:打算用yesql提交一个错误,但是最近发布的0.5.2版本已经修复了该错误。

SQL Arrays are not supported by yesql, but clojure.java.jdbc offers an extension point in the ISQLParameter protocol , which you can use as: yesql不支持SQL数组,但是clojure.java.jdbc在ISQLParameter协议中提供了扩展点,您可以将其用作:

(deftype StringArray [items]
  clojure.java.jdbc/ISQLParameter
  (set-parameter [_ stmt ix]
    (let [as-array (into-array Object items)
          jdbc-array (.createArrayOf (.getConnection stmt) "text" as-array)]
      (.setArray stmt ix jdbc-array))))

(insert-into-sometable<! db-spec "hi" (->StringArray ["one" "two"]))

Note that you cannot extend Clojure's vectors as vectors has a special meaning in yesql 请注意,您无法扩展Clojure的向量,因为向量在yesql中具有特殊含义

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM