You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用HoneySQL向PostgreSQL插入Clojure对象到JSON字段?

在PostgreSQL中用HoneySQL将Clojure映射写入JSON字段

1. 基础依赖准备

确保你的Clojure项目中引入了HoneySQL和PostgreSQL JDBC驱动:

;; project.clj 或 deps.edn 中的依赖
[com.github.seancorfield/honeysql "2.4.980"]
[org.postgresql/postgresql "42.7.3"]

2. 插入JSON字段

假设你有一张users表,包含id(整数)和profile(JSON类型)字段。要将Clojure映射写入profile字段,只需用HoneySQL的:json(或:jsonb对应JSONB类型)表达式包装映射:

(require '[honey.sql :as sql]
         '[honey.sql.helpers :refer [insert-into values]])

;; 待插入的Clojure映射
(def user-profile {:name "Alice" :age 30 :hobbies ["reading" "hiking"]})

;; 构建插入SQL
(def insert-query
  (-> (insert-into :users)
      (values [{:id 1 :profile (sql/format-expr [:json user-profile])}])
      sql/format))

执行后生成的SQL为:

INSERT INTO users (id, profile) VALUES (1, ?::json)

PostgreSQL JDBC驱动会自动将Clojure映射转换为符合JSON格式的字符串,配合::json类型转换,确保字段类型匹配。

3. 更新JSON字段

更新已有记录的JSON字段时,逻辑和插入类似,在SET子句中用:json包装更新后的映射:

(require '[honey.sql.helpers :refer [update set where]])

;; 更新后的Clojure映射
(def updated-profile {:name "Alice" :age 31 :hobbies ["reading" "hiking" "cooking"]})

;; 构建更新SQL
(def update-query
  (-> (update :users)
      (set {:profile (sql/format-expr [:json updated-profile])})
      (where [:= :id 1])
      sql/format))

生成的SQL为:

UPDATE users SET profile = ?::json WHERE id = 1

4. 查询JSON字段内容

要提取JSON字段中的特定值,可以使用PostgreSQL的JSON函数或操作符,通过HoneySQL生成对应SQL:

方式1:使用JSON函数

(require '[honey.sql.helpers :refer [select from]])

(def query-query
  (-> (select :id [:json_extract_path_text :profile "name"] :as :user-name)
      (from :users)
      (where [:= :id 1])
      sql/format))

生成的SQL为:

SELECT id, json_extract_path_text(profile, 'name') AS "user-name" FROM users WHERE id = 1

方式2:使用->>操作符

(def query-query
  (-> (select :id [(sql/raw "profile->>'name'") :as :user-name])
      (from :users)
      (where [:= :id 1])
      sql/format))

生成的SQL为:

SELECT id, profile->>'name' AS "user-name" FROM users WHERE id = 1

注意事项

  • 如果你的字段是JSONB类型,只需将上述代码中的:json替换为:jsonb即可,生成的SQL会使用?::jsonb进行类型转换。
  • PostgreSQL JDBC驱动会自动处理Clojure映射/序列与JSON格式的转换,无需手动序列化字符串。

内容的提问来源于stack exchange,提问作者FuzzyAmi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 13:03:35