sql - 如何使用 Clojure JDBC 插入 Postgres 枚举值?

标签 sql jdbc clojure

例如,这是 PostgreSQL 中的产品表,状态为枚举:

create type product_status as enum ('InStock', 'OutOfStock');

create table product (
    pid            int primary key default nextval('product_pid_seq'),
    sku            text not null unique,
    name           text not null,
    description    text not null,
    quantity       int not null,
    cost           numeric(10,2) not null,
    price          numeric(10,2) not null,
    weight         numeric(10,2),
    status         product_status not null
);

插入产品的典型 Clojure 代码是:
(def prod-12345 {:sku "12345"
                 :name "My Product"
                 :description "yada yada yada"
                 :quantity 100
                 :cost 42.00
                 :price 59.00
                 :weight 0.3
                 :status "InStock"})

(sql/with-connection db-spec
   (sql/insert-record :product prod-12345))

然而,status是一个枚举,因此您不能将其作为普通字符串插入而不将其转换为枚举:
'InStock'::product_status

我知道您可以使用准备好的语句来做到这一点,例如:
INSERT INTO product (name, status) VALUES (?, ?::product_status)

但是有没有办法在不使用准备好的语句的情况下做到这一点?

最佳答案

我今天使用 stringtype=unspecified 完成了这项工作黑客解决方法。

您可以将此参数添加到您的 db-spec如下:

(def db-spec {:classname "org.postgresql.Driver"
              :subprotocol "postgresql"
              :subname "//myserver:5432/mydatabase"
              :user "myuser"
              :password "mypassword"
              :stringtype "unspecified"}) ; HACK to support enums

然后只需使用 insert!照常。

最好有一个不会削弱类型安全性的解决方案。

关于sql - 如何使用 Clojure JDBC 插入 Postgres 枚举值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14719207/

相关文章:

sql - 是否有任何单个 sql 命令可以将整个数据库从一个 sql 服务器导出到另一台?

mysql - 插入时间戳而不使用准备好的语句

java - 从多个类访问用户数据库

java - 将字符串转换为 TIMESTAMP,以便从 servlet java 插入数据库 oracle

sql - 使用整数值的日期算术

mysql - 长文本字段的数据过滤

clojure - 使用 Enlive 重新抓取数据

java - 如何在 Java 或 clojure 中使用 ImageJ 进行批量图像处理?

java - 如何在 Clojure 中实现 Java 接口(interface)

java - 找到重复的主键时替换行